level_editor.vala 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816
  1. /*
  2. * Copyright (c) 2012-2023 Daniele Bartolini et al.
  3. * SPDX-License-Identifier: GPL-3.0-or-later
  4. */
  5. using Gdk; // Pixbuf
  6. using Gee;
  7. using Gtk;
  8. namespace Crown
  9. {
  10. const int WINDOW_DEFAULT_WIDTH = 1280;
  11. const int WINDOW_DEFAULT_HEIGHT = 720;
  12. const string LEVEL_EDITOR_WINDOW_TITLE = "Crown Editor";
  13. const string CROWN_ICON_NAME = "crown";
  14. public enum Theme
  15. {
  16. DARK,
  17. LIGHT,
  18. COUNT
  19. }
  20. public enum ToolType
  21. {
  22. PLACE,
  23. MOVE,
  24. ROTATE,
  25. SCALE,
  26. COUNT
  27. }
  28. public enum SnapMode
  29. {
  30. RELATIVE,
  31. ABSOLUTE
  32. }
  33. public enum ReferenceSystem
  34. {
  35. LOCAL,
  36. WORLD
  37. }
  38. public enum CameraViewType
  39. {
  40. PERSPECTIVE,
  41. FRONT,
  42. BACK,
  43. RIGHT,
  44. LEFT,
  45. TOP,
  46. BOTTOM,
  47. COUNT
  48. }
  49. public class LevelEditorWindow : Gtk.ApplicationWindow
  50. {
  51. private const GLib.ActionEntry[] action_entries =
  52. {
  53. { "fullscreen", on_fullscreen, null, null }
  54. };
  55. public bool _fullscreen;
  56. public LevelEditorWindow(Gtk.Application app)
  57. {
  58. Object(application: app);
  59. this.add_action_entries(action_entries, this);
  60. this.title = LEVEL_EDITOR_WINDOW_TITLE;
  61. this.key_press_event.connect(this.on_key_press);
  62. this.key_release_event.connect(this.on_key_release);
  63. this.window_state_event.connect(this.on_window_state_event);
  64. this.delete_event.connect(this.on_delete_event);
  65. this.focus_out_event.connect(this.on_focus_out);
  66. _fullscreen = false;
  67. }
  68. private void on_fullscreen(GLib.SimpleAction action, GLib.Variant? param)
  69. {
  70. if (_fullscreen)
  71. unfullscreen();
  72. else
  73. fullscreen();
  74. }
  75. private bool on_key_press(Gdk.EventKey ev)
  76. {
  77. LevelEditorApplication app = (LevelEditorApplication)application;
  78. string str = "";
  79. if (ev.keyval == Gdk.Key.Control_L)
  80. str += LevelEditorApi.key_down("ctrl_left");
  81. else if (ev.keyval == Gdk.Key.Shift_L)
  82. str += LevelEditorApi.key_down("shift_left");
  83. else if (ev.keyval == Gdk.Key.Alt_L)
  84. str += LevelEditorApi.key_down("alt_left");
  85. if (str.length != 0) {
  86. app._editor.send_script(str);
  87. app._editor.send(DeviceApi.frame());
  88. }
  89. return Gdk.EVENT_PROPAGATE;
  90. }
  91. private bool on_key_release(Gdk.EventKey ev)
  92. {
  93. LevelEditorApplication app = (LevelEditorApplication)application;
  94. string str = "";
  95. if (ev.keyval == Gdk.Key.Control_L)
  96. str += LevelEditorApi.key_up("ctrl_left");
  97. else if (ev.keyval == Gdk.Key.Shift_L)
  98. str += LevelEditorApi.key_up("shift_left");
  99. else if (ev.keyval == Gdk.Key.Alt_L)
  100. str += LevelEditorApi.key_up("alt_left");
  101. if (str.length != 0) {
  102. app._editor.send_script(str);
  103. app._editor.send(DeviceApi.frame());
  104. }
  105. return Gdk.EVENT_PROPAGATE;
  106. }
  107. private bool on_window_state_event(Gdk.EventWindowState ev)
  108. {
  109. _fullscreen = (ev.new_window_state & Gdk.WindowState.FULLSCREEN) != 0;
  110. return Gdk.EVENT_STOP;
  111. }
  112. private bool on_delete_event()
  113. {
  114. LevelEditorApplication app = (LevelEditorApplication)application;
  115. if (app.should_quit())
  116. app.stop_backend_and_quit();
  117. return Gdk.EVENT_STOP; // Keep window alive.
  118. }
  119. private bool on_focus_out(Gdk.EventFocus ev)
  120. {
  121. LevelEditorApplication app = (LevelEditorApplication)application;
  122. app._editor.send_script(LevelEditorApi.key_up("ctrl_left"));
  123. app._editor.send_script(LevelEditorApi.key_up("shift_left"));
  124. app._editor.send_script(LevelEditorApi.key_up("alt_left"));
  125. return Gdk.EVENT_PROPAGATE;
  126. }
  127. }
  128. public enum StartGame
  129. {
  130. NORMAL,
  131. TEST
  132. }
  133. public class LevelEditorApplication : Gtk.Application
  134. {
  135. // Constants
  136. private const GLib.ActionEntry[] action_entries_file =
  137. {
  138. // parameter type
  139. // name activate() | state
  140. // | | | |
  141. { "menu-file", null, null, null },
  142. { "new-level", on_new_level, null, null },
  143. { "open-level", on_open_level, "s", null },
  144. { "new-project", on_new_project, null, null },
  145. { "open-project", on_open_project, "s", null },
  146. { "save", on_save, null, null },
  147. { "save-as", on_save_as, null, null },
  148. { "import", on_import, "s", null },
  149. { "preferences", on_preferences, null, null },
  150. { "deploy", on_deploy, null, null },
  151. { "close", on_close, null, null },
  152. { "quit", on_quit, null, null },
  153. { "open-resource", on_open_resource, "s", null }
  154. };
  155. private const GLib.ActionEntry[] action_entries_edit =
  156. {
  157. { "menu-edit", null, null, null },
  158. { "undo", on_undo, null, null },
  159. { "redo", on_redo, null, null },
  160. { "duplicate", on_duplicate, null, null },
  161. { "delete", on_delete, null, null },
  162. { "tool", on_tool, "i", "1" }, // See: Crown.ToolType
  163. { "snap", on_snap, "i", "0" }, // See: Crown.SnapMode
  164. { "reference-system", on_reference_system, "i", "0" }, // See: Crown.ReferenceSystem
  165. { "snap-to-grid", on_snap_to_grid, null, "true" },
  166. { "menu-grid", null, null, null },
  167. { "grid-show", on_show_grid, null, "true" },
  168. { "grid-size", on_grid_size, "i", "10" }, // 10*meters.
  169. { "menu-rotation-snap", null, null, null },
  170. { "rotation-snap-size", on_rotation_snap_size, "i", "15" }
  171. };
  172. private const GLib.ActionEntry[] action_entries_create =
  173. {
  174. { "menu-create", null, null, null },
  175. { "menu-primitives", null, null, null },
  176. { "primitive-cube", on_create_primitive, null, null },
  177. { "primitive-sphere", on_create_primitive, null, null },
  178. { "primitive-cone", on_create_primitive, null, null },
  179. { "primitive-cylinder", on_create_primitive, null, null },
  180. { "primitive-plane", on_create_primitive, null, null },
  181. { "camera", on_create_primitive, null, null },
  182. { "light", on_create_primitive, null, null },
  183. { "sound-source", on_create_primitive, null, null },
  184. { "unit-empty", on_create_unit, null, null }
  185. };
  186. private const GLib.ActionEntry[] action_entries_camera =
  187. {
  188. { "menu-camera", null, null, null },
  189. { "camera-view", on_camera_view, "i", "0" } // See: Crown.CameraViewType
  190. };
  191. private const GLib.ActionEntry[] action_entries_view =
  192. {
  193. { "menu-view", null, null, null },
  194. { "resource-chooser", on_resource_chooser, null, null },
  195. { "project-browser", on_project_browser, null, null },
  196. { "console", on_console, null, null },
  197. { "statusbar", on_statusbar, null, null },
  198. { "inspector", on_inspector, null, null },
  199. { "debug-render-world", on_debug_render_world, null, "false" },
  200. { "debug-physics-world", on_debug_physics_world, null, "false" }
  201. };
  202. private const GLib.ActionEntry[] action_entries_debug =
  203. {
  204. { "menu-debug", null, null, null },
  205. { "test-level", on_run_game, null, null },
  206. { "run-game", on_run_game, null, null },
  207. { "build-data", on_build_data, null, null },
  208. { "reload-lua", on_refresh_lua, null, null },
  209. { "restart-editor-view", on_restart_editor_view, null, null }
  210. };
  211. private const GLib.ActionEntry[] action_entries_help =
  212. {
  213. { "menu-help", null, null, null },
  214. { "manual", on_manual, null, null },
  215. { "report-issue", on_report_issue, null, null },
  216. { "browse-logs", on_browse_logs, null, null },
  217. { "changelog", on_changelog, null, null },
  218. { "about", on_about, null, null }
  219. };
  220. private const GLib.ActionEntry[] action_entries_project =
  221. {
  222. { "delete-file", on_delete_file, "s", null }
  223. };
  224. // Command line options
  225. private string? _source_dir = null;
  226. private string _level_resource = "";
  227. private User _user;
  228. private Hashtable _settings;
  229. // Subprocess launcher service.
  230. private SubprocessLauncher _subprocess_launcher;
  231. // Editor state
  232. private double _grid_size;
  233. private double _rotation_snap;
  234. private bool _show_grid;
  235. private bool _snap_to_grid;
  236. private bool _debug_render_world;
  237. private bool _debug_physics_world;
  238. private ToolType _tool_type;
  239. private ToolType _tool_type_prev;
  240. private SnapMode _snap_mode;
  241. private ReferenceSystem _reference_system;
  242. private CameraViewType _camera_view_type;
  243. // Project state
  244. private string _placeable_type;
  245. private string _placeable_name;
  246. // Accelerators
  247. private string[] _tool_place_accels;
  248. private string[] _tool_move_accels;
  249. private string[] _tool_rotate_accels;
  250. private string[] _tool_scale_accels;
  251. private string[] _delete_accels;
  252. private string[] _camera_view_perspective_accels;
  253. private string[] _camera_view_front_accels;
  254. private string[] _camera_view_back_accels;
  255. private string[] _camera_view_right_accels;
  256. private string[] _camera_view_left_accels;
  257. private string[] _camera_view_top_accels;
  258. private string[] _camera_view_bottom_accels;
  259. // Engine connections
  260. private uint32 _compiler_process;
  261. private uint32 _editor_process;
  262. private uint32 _resource_preview_process;
  263. private uint32 _game_process;
  264. private GLib.SourceFunc _stop_data_compiler_callback = null;
  265. private GLib.SourceFunc _stop_editor_callback = null;
  266. private GLib.SourceFunc _stop_game_callback = null;
  267. private GLib.SourceFunc _stop_resource_preview_callback = null;
  268. private ConsoleClient _compiler;
  269. public ConsoleClient _editor;
  270. private ConsoleClient _resource_preview;
  271. private ConsoleClient _game;
  272. // Level data
  273. private UndoRedo _undo_redo;
  274. private Database _database;
  275. private Project _project;
  276. private ProjectStore _project_store;
  277. private Level _level;
  278. private DataCompiler _data_compiler;
  279. // Widgets
  280. private Gtk.CssProvider _css_provider;
  281. private ProjectBrowser _project_browser;
  282. private EditorView _editor_view;
  283. private EditorView _resource_preview_view;
  284. private LevelTreeView _level_treeview;
  285. private LevelLayersTreeView _level_layers_treeview;
  286. private PropertiesView _properties_view;
  287. private PreferencesDialog _preferences_dialog;
  288. private ResourceChooser _resource_chooser;
  289. private Gtk.Popover _resource_popover;
  290. private Gtk.Overlay _editor_view_overlay;
  291. private Gtk.Stack _project_stack;
  292. private Gtk.Label _project_stack_compiling_data_label;
  293. private Gtk.Label _project_stack_connecting_to_data_compiler_label;
  294. private Gtk.Label _project_stack_compiler_crashed_label;
  295. private Gtk.Label _project_stack_compiler_failed_compilation_label;
  296. private Gtk.Stack _editor_stack;
  297. private Gtk.Label _editor_stack_compiling_data_label;
  298. private Gtk.Label _editor_stack_connecting_to_data_compiler_label;
  299. private Gtk.Label _editor_stack_compiler_crashed_label;
  300. private Gtk.Label _editor_stack_compiler_failed_compilation_label;
  301. private Gtk.Label _editor_stack_disconnected_label;
  302. private Gtk.Label _editor_stack_oops_label;
  303. public Gtk.Stack _resource_preview_stack;
  304. public Gtk.Label _resource_preview_disconnected_label;
  305. public Gtk.Label _resource_preview_oops_label;
  306. public Gtk.Label _resource_preview_no_preview_label;
  307. private Gtk.Stack _inspector_stack;
  308. private Gtk.Label _inspector_stack_compiling_data_label;
  309. private Gtk.Label _inspector_stack_connecting_to_data_compiler_label;
  310. private Gtk.Label _inspector_stack_compiler_crashed_label;
  311. private Gtk.Label _inspector_stack_compiler_failed_compilation_label;
  312. private Gtk.Toolbar _toolbar;
  313. private Gtk.ToolButton _toolbar_run;
  314. private Gtk.Notebook _level_tree_view_notebook;
  315. private Gtk.Paned _editor_pane;
  316. private Gtk.Paned _content_pane;
  317. private Gtk.Paned _inspector_pane;
  318. private Gtk.Paned _main_pane;
  319. private Statusbar _statusbar;
  320. private Gtk.Box _main_vbox;
  321. private Gtk.FileFilter _file_filter;
  322. private Gtk.ComboBoxText _combo;
  323. private PanelNewProject _panel_new_project;
  324. private PanelProjectsList _panel_projects_list;
  325. private PanelWelcome _panel_welcome;
  326. private Gtk.Stack _main_stack;
  327. private uint _save_timer_id;
  328. public LevelEditorApplication(SubprocessLauncher subprocess_launcher)
  329. {
  330. Object(application_id: "org.crown.level_editor"
  331. , flags: GLib.ApplicationFlags.FLAGS_NONE
  332. );
  333. _subprocess_launcher = subprocess_launcher;
  334. }
  335. public Theme theme_name_to_enum(string theme)
  336. {
  337. if (theme == "dark")
  338. return Theme.DARK;
  339. else if (theme == "light")
  340. return Theme.LIGHT;
  341. else
  342. return Theme.COUNT;
  343. }
  344. public void set_theme_from_name(string theme_name)
  345. {
  346. Theme theme = theme_name_to_enum(theme_name);
  347. set_theme(theme);
  348. }
  349. public void set_theme(Theme theme)
  350. {
  351. if (theme == Theme.COUNT)
  352. return;
  353. string css = "/org/crown/level_editor/theme/Adwaita/gtk%s.css".printf(theme == Theme.DARK ? "-dark" : "");
  354. _css_provider.load_from_resource(css);
  355. }
  356. protected override void startup()
  357. {
  358. base.startup();
  359. Intl.setlocale(LocaleCategory.ALL, "C");
  360. _css_provider = new Gtk.CssProvider();
  361. var default_screen = Gdk.Display.get_default().get_default_screen();
  362. Gtk.StyleContext.add_provider_for_screen(default_screen
  363. , _css_provider
  364. , STYLE_PROVIDER_PRIORITY_APPLICATION
  365. );
  366. _settings = SJSON.load_from_path(_settings_file.get_path());
  367. // Set theme.
  368. set_theme(Theme.DARK);
  369. if (_settings.has_key("preferences")) {
  370. Hashtable preferences = (Hashtable)_settings["preferences"];
  371. if (preferences.has_key("theme"))
  372. set_theme_from_name((string)preferences["theme"]);
  373. }
  374. // HACK: register CrownClamp type within GObject's type system to
  375. // make GtkBuilder able to find it when creating the widget from
  376. // .ui files.
  377. // https://stackoverflow.com/questions/24235937/custom-gtk-widget-with-template-ui
  378. new Clamp().get_type().ensure();
  379. this.add_action_entries(action_entries_file, this);
  380. this.add_action_entries(action_entries_edit, this);
  381. this.add_action_entries(action_entries_create, this);
  382. this.add_action_entries(action_entries_camera, this);
  383. this.add_action_entries(action_entries_view, this);
  384. this.add_action_entries(action_entries_debug, this);
  385. this.add_action_entries(action_entries_help, this);
  386. this.add_action_entries(action_entries_project, this);
  387. _tool_place_accels = this.get_accels_for_action("app.tool(0)");
  388. _tool_move_accels = this.get_accels_for_action("app.tool(1)");
  389. _tool_rotate_accels = this.get_accels_for_action("app.tool(2)");
  390. _tool_scale_accels = this.get_accels_for_action("app.tool(3)");
  391. _delete_accels = this.get_accels_for_action("app.delete");
  392. _camera_view_perspective_accels = this.get_accels_for_action("app.camera-view(0)");
  393. _camera_view_front_accels = this.get_accels_for_action("app.camera-view(1)");
  394. _camera_view_back_accels = this.get_accels_for_action("app.camera-view(2)");
  395. _camera_view_right_accels = this.get_accels_for_action("app.camera-view(3)");
  396. _camera_view_left_accels = this.get_accels_for_action("app.camera-view(4)");
  397. _camera_view_top_accels = this.get_accels_for_action("app.camera-view(5)");
  398. _camera_view_bottom_accels = this.get_accels_for_action("app.camera-view(6)");
  399. _compiler = new ConsoleClient();
  400. _compiler.connected.connect(on_data_compiler_connected);
  401. _compiler.message_received.connect(on_message_received);
  402. _data_compiler = new DataCompiler(_compiler);
  403. _project = new Project(_data_compiler);
  404. _project.set_toolchain_dir(_toolchain_dir.get_path());
  405. _project.register_importer("Sprite", { "png" }, SpriteResource.import, 0.0);
  406. _project.register_importer("Mesh", { "mesh" }, MeshResource.import, 1.0);
  407. _project.register_importer("Sound", { "wav" }, SoundResource.import, 2.0);
  408. _project.register_importer("Texture", { "png", "tga", "dds", "ktx", "pvr" }, TextureResource.import, 2.0);
  409. uint32 undo_redo_size = DEFAULT_UNDO_REDO_MAX_SIZE;
  410. if (_settings.has_key("preferences")) {
  411. Hashtable preferences = (Hashtable)_settings["preferences"];
  412. if (preferences.has_key("undo_redo_max_size"))
  413. undo_redo_size = (uint32)(double)preferences["undo_redo_max_size"];
  414. }
  415. _undo_redo = new UndoRedo(undo_redo_size*1024*1024);
  416. _database = new Database(_project, _undo_redo);
  417. _database.key_changed.connect(() => { update_active_window_title(); });
  418. _editor = new ConsoleClient();
  419. _editor.connected.connect(on_editor_connected);
  420. _editor.message_received.connect(on_message_received);
  421. _resource_preview = new ConsoleClient();
  422. _resource_preview.connected.connect(on_resource_preview_connected);
  423. _resource_preview.message_received.connect(on_resource_preview_message_received);
  424. _game = new ConsoleClient();
  425. _game.connected.connect(on_game_connected);
  426. _game.message_received.connect(on_message_received);
  427. _level = new Level(_database, _editor, _project);
  428. // Editor state
  429. _grid_size = 1.0;
  430. _rotation_snap = 15.0;
  431. _show_grid = true;
  432. _snap_to_grid = true;
  433. _debug_render_world = false;
  434. _debug_physics_world = false;
  435. _tool_type = ToolType.MOVE;
  436. _tool_type_prev = _tool_type;
  437. _snap_mode = SnapMode.RELATIVE;
  438. _reference_system = ReferenceSystem.LOCAL;
  439. _camera_view_type = CameraViewType.PERSPECTIVE;
  440. // Project state
  441. _placeable_type = "";
  442. _placeable_name = "";
  443. // Engine connections
  444. _compiler_process = uint32.MAX;
  445. _editor_process = uint32.MAX;
  446. _resource_preview_process = uint32.MAX;
  447. _game_process = uint32.MAX;
  448. _project_store = new ProjectStore(_project);
  449. // Widgets
  450. _preferences_dialog = new PreferencesDialog(this);
  451. _preferences_dialog.delete_event.connect(_preferences_dialog.hide_on_delete);
  452. _combo = new Gtk.ComboBoxText();
  453. _combo.append("editor", "Editor");
  454. _combo.append("game", "Game");
  455. _combo.set_active_id("editor");
  456. _console_view = new ConsoleView(_project, _combo, _preferences_dialog);
  457. _project_browser = new ProjectBrowser(this, _project, _project_store);
  458. _level_treeview = new LevelTreeView(_database, _level);
  459. _level_layers_treeview = new LevelLayersTreeView(_database, _level);
  460. _properties_view = new PropertiesView(_level, _project_store);
  461. _project_stack = new Gtk.Stack();
  462. _project_stack.add(_project_browser);
  463. _project_stack_compiling_data_label = compiling_data_label();
  464. _project_stack.add(_project_stack_compiling_data_label);
  465. _project_stack_connecting_to_data_compiler_label = connecting_to_data_compiler_label();
  466. _project_stack.add(_project_stack_connecting_to_data_compiler_label);
  467. _project_stack_compiler_crashed_label = compiler_crashed_label();
  468. _project_stack.add(_project_stack_compiler_crashed_label);
  469. _project_stack_compiler_failed_compilation_label = compiler_failed_compilation_label();
  470. _project_stack.add(_project_stack_compiler_failed_compilation_label);
  471. _editor_stack = new Gtk.Stack();
  472. _editor_stack_compiling_data_label = compiling_data_label();
  473. _editor_stack.add(_editor_stack_compiling_data_label);
  474. _editor_stack_connecting_to_data_compiler_label = connecting_to_data_compiler_label();
  475. _editor_stack.add(_editor_stack_connecting_to_data_compiler_label);
  476. _editor_stack_compiler_crashed_label = compiler_crashed_label();
  477. _editor_stack.add(_editor_stack_compiler_crashed_label);
  478. _editor_stack_compiler_failed_compilation_label = compiler_failed_compilation_label();
  479. _editor_stack.add(_editor_stack_compiler_failed_compilation_label);
  480. _editor_stack_disconnected_label = new Gtk.Label("Disconnected.");
  481. _editor_stack.add(_editor_stack_disconnected_label);
  482. _editor_stack_oops_label = new Gtk.Label(null);
  483. _editor_stack_oops_label.track_visited_links = false;
  484. _editor_stack_oops_label.set_markup("Something went wrong.\rTry to <a href=\"restart\">restart this view</a>.");
  485. _editor_stack_oops_label.activate_link.connect(() => {
  486. activate_action("restart-editor-view", null);
  487. return true;
  488. });
  489. _editor_stack.add(_editor_stack_oops_label);
  490. _resource_preview_stack = new Gtk.Stack();
  491. _resource_preview_no_preview_label = new Gtk.Label("No Preview");
  492. _resource_preview_no_preview_label.set_size_request(300, 300);
  493. _resource_preview_stack.add(_resource_preview_no_preview_label);
  494. _resource_preview_disconnected_label = new Gtk.Label("Disconnected");
  495. _resource_preview_stack.add(_resource_preview_disconnected_label);
  496. _resource_preview_oops_label = new Gtk.Label(null);
  497. _resource_preview_oops_label.track_visited_links = false;
  498. _resource_preview_oops_label.set_markup("Something went wrong.\rTry to <a href=\"restart\">restart this view</a>.");
  499. _resource_preview_oops_label.activate_link.connect(() => {
  500. restart_resource_preview.begin((obj, res) => {
  501. restart_resource_preview.end(res);
  502. });
  503. return true;
  504. });
  505. _resource_preview_stack.add(_resource_preview_oops_label);
  506. _inspector_stack = new Gtk.Stack();
  507. _inspector_stack_compiling_data_label = compiling_data_label();
  508. _inspector_stack.add(_inspector_stack_compiling_data_label);
  509. _inspector_stack_connecting_to_data_compiler_label = connecting_to_data_compiler_label();
  510. _inspector_stack.add(_inspector_stack_connecting_to_data_compiler_label);
  511. _inspector_stack_compiler_crashed_label = compiler_crashed_label();
  512. _inspector_stack.add(_inspector_stack_compiler_crashed_label);
  513. _inspector_stack_compiler_failed_compilation_label = compiler_failed_compilation_label();
  514. _inspector_stack.add(_inspector_stack_compiler_failed_compilation_label);
  515. Gtk.Builder builder = new Gtk.Builder.from_resource("/org/crown/level_editor/ui/toolbar.ui");
  516. _toolbar = builder.get_object("toolbar") as Gtk.Toolbar;
  517. _toolbar_run = builder.get_object("run") as Gtk.ToolButton;
  518. _editor_view_overlay = new Gtk.Overlay();
  519. _editor_view_overlay.add_overlay(_toolbar);
  520. _resource_popover = new Gtk.Popover(_toolbar);
  521. _resource_popover.key_press_event.connect((ev) => {
  522. if (ev.keyval == Gdk.Key.Escape) {
  523. // Do not transition-animate (i.e. call hide() instead of popdown()).
  524. _resource_popover.hide();
  525. return Gdk.EVENT_STOP;
  526. }
  527. return Gdk.EVENT_PROPAGATE;
  528. });
  529. _resource_popover.button_press_event.connect((ev) => {
  530. // Do not transition-animate (i.e. call hide() instead of popdown()).
  531. // See: https://gitlab.gnome.org/GNOME/gtk/-/blob/3.22.30/gtk/gtkpopover.c
  532. Gtk.Widget child = _resource_popover.get_child();
  533. Gtk.Widget event_widget = Gtk.get_event_widget(ev);
  534. if (child != null && ev.window == event_widget.get_window()) {
  535. Gtk.Allocation child_alloc;
  536. child.get_allocation(out child_alloc);
  537. if ((int)ev.x < child_alloc.x
  538. || (int)ev.x > child_alloc.x + child_alloc.width
  539. || (int)ev.y < child_alloc.y
  540. || (int)ev.y > child_alloc.y + child_alloc.height
  541. ) {
  542. _resource_popover.hide();
  543. }
  544. } else if (!event_widget.is_ancestor(_resource_popover)) {
  545. _resource_popover.hide();
  546. }
  547. return Gdk.EVENT_PROPAGATE;
  548. });
  549. _resource_popover.events |= Gdk.EventMask.STRUCTURE_MASK; // unmap_event
  550. _resource_popover.unmap_event.connect(() => {
  551. // Redraw the editor view when the popover is not on-screen anymore.
  552. device_frame_delayed(16, _editor);
  553. return Gdk.EVENT_PROPAGATE;
  554. });
  555. _resource_popover.delete_event.connect(_resource_popover.hide_on_delete);
  556. _resource_popover.modal = true;
  557. _resource_chooser = new ResourceChooser(_project, _project_store, _resource_preview_stack, _resource_preview);
  558. _resource_chooser.resource_selected.connect(on_resource_browser_resource_selected);
  559. _resource_chooser.destroy.connect(() => {
  560. stop_resource_preview.begin((obj, res) => {
  561. stop_resource_preview.end(res);
  562. });
  563. });
  564. _resource_popover.add(_resource_chooser);
  565. _level_tree_view_notebook = new Notebook();
  566. _level_tree_view_notebook.show_border = false;
  567. _level_tree_view_notebook.append_page(_level_treeview, new Gtk.Image.from_icon_name("level-tree", IconSize.SMALL_TOOLBAR));
  568. _level_tree_view_notebook.append_page(_level_layers_treeview, new Gtk.Image.from_icon_name("level-layers", IconSize.SMALL_TOOLBAR));
  569. _editor_pane = new Gtk.Paned(Gtk.Orientation.HORIZONTAL);
  570. _editor_pane.pack1(_project_stack, false, false);
  571. _editor_pane.pack2(_editor_stack, true, false);
  572. _content_pane = new Gtk.Paned(Gtk.Orientation.VERTICAL);
  573. _content_pane.pack1(_editor_pane, true, false);
  574. _content_pane.pack2(_console_view, false, false);
  575. _inspector_pane = new Gtk.Paned(Gtk.Orientation.VERTICAL);
  576. _inspector_pane.pack1(_level_tree_view_notebook, true, false);
  577. _inspector_pane.pack2(_properties_view, false, false);
  578. _inspector_stack.add(_inspector_pane);
  579. _main_pane = new Gtk.Paned(Gtk.Orientation.HORIZONTAL);
  580. _main_pane.pack1(_content_pane, true, false);
  581. _main_pane.pack2(_inspector_stack, false, false);
  582. _statusbar = new Statusbar();
  583. _main_vbox = new Gtk.Box(Gtk.Orientation.VERTICAL, 0);
  584. _main_vbox.pack_start(_main_pane, true, true, 0);
  585. _main_vbox.pack_start(_statusbar, false, false, 0);
  586. _main_vbox.set_visible(true);
  587. _file_filter = new Gtk.FileFilter();
  588. _file_filter.set_filter_name("Level (*.level)");
  589. _file_filter.add_pattern("*.level");
  590. _user = new User();
  591. _panel_new_project = new PanelNewProject(this, _user, _project);
  592. _panel_new_project.fill_templates_list(_templates_dir.get_path());
  593. _panel_welcome = new PanelWelcome();
  594. _panel_projects_list = new PanelProjectsList(this, _user);
  595. _panel_welcome.pack_start(_panel_projects_list);
  596. _panel_welcome.set_visible(true); // To make Gtk.Stack work...
  597. _main_stack = new Gtk.Stack();
  598. _main_stack.add_named(_panel_welcome, "panel_welcome");
  599. _main_stack.add_named(_panel_new_project, "panel_new_project");
  600. _main_stack.add_named(_main_vbox, "main_vbox");
  601. _preferences_dialog.decode(_settings);
  602. // Delete expired logs
  603. if (_preferences_dialog._log_delete_after_days.value != 0) {
  604. try {
  605. FileEnumerator enumerator = _logs_dir.enumerate_children("standard::*"
  606. , FileQueryInfoFlags.NOFOLLOW_SYMLINKS
  607. );
  608. GLib.FileInfo info = null;
  609. while ((info = enumerator.next_file()) != null) {
  610. if (info.get_file_type() != GLib.FileType.REGULAR)
  611. continue; // Skip anything but regular files
  612. // Parse DateTime from log filename
  613. int year = 1970;
  614. int month = 1;
  615. int day = 1;
  616. if (info.get_name().scanf("%d-%d-%d.log", &year, &month, &day) != 3)
  617. continue; // Skip malformed filenames
  618. GLib.DateTime time_log = new GLib.DateTime.local(year, month, day, 0, 0, 0.0);
  619. if (time_log == null)
  620. continue; // Skip invalid dates
  621. GLib.DateTime time_now = new GLib.DateTime.now_local();
  622. if (time_now.difference(time_log) <= GLib.TimeSpan.DAY*_preferences_dialog._log_delete_after_days.value)
  623. continue; // Skip if date is within range
  624. // Delete
  625. GLib.File log_file = _logs_dir.resolve_relative_path(info.get_name());
  626. log_file.delete();
  627. }
  628. }
  629. catch (GLib.Error e) {
  630. loge(e.message);
  631. }
  632. }
  633. _user.load(_user_file.get_path());
  634. _console_view._entry_history.load(_console_history_file.get_path());
  635. if (_source_dir == null) {
  636. show_panel("panel_welcome");
  637. } else {
  638. show_panel("main_vbox");
  639. restart_backend.begin(_source_dir, _level_resource);
  640. }
  641. }
  642. protected override void activate()
  643. {
  644. if (this.active_window == null) {
  645. LevelEditorWindow win = new LevelEditorWindow(this);
  646. win.set_default_size(WINDOW_DEFAULT_WIDTH, WINDOW_DEFAULT_HEIGHT);
  647. win.add(_main_stack);
  648. try {
  649. win.icon = IconTheme.get_default().load_icon(CROWN_ICON_NAME, 256, 0);
  650. }
  651. catch (Error e) {
  652. loge(e.message);
  653. }
  654. }
  655. this.active_window.show_all();
  656. this.active_window.maximize();
  657. }
  658. protected override bool local_command_line(ref unowned string[] args, out int exit_status)
  659. {
  660. if (args.length > 1) {
  661. if (!GLib.FileUtils.test(args[1], FileTest.EXISTS) || !GLib.FileUtils.test(args[1], FileTest.IS_DIR)) {
  662. loge("Source directory does not exist or it is not a directory");
  663. exit_status = 1;
  664. return true;
  665. }
  666. _source_dir = args[1];
  667. }
  668. if (args.length > 2) {
  669. // Validation is done below after the Project object instantiation
  670. _level_resource = args[2];
  671. }
  672. exit_status = 0;
  673. return false;
  674. }
  675. protected override int command_line(ApplicationCommandLine command_line)
  676. {
  677. this.activate();
  678. return 0;
  679. }
  680. public ConsoleClient? current_selected_client()
  681. {
  682. if (_combo.get_active_id() == "editor")
  683. return _editor;
  684. else if (_combo.get_active_id() == "game")
  685. return _game;
  686. else
  687. return null;
  688. }
  689. private void on_resource_browser_resource_selected(string type, string name)
  690. {
  691. set_placeable(type, name);
  692. activate_action("tool", new GLib.Variant.int32(ToolType.PLACE));
  693. }
  694. private void on_data_compiler_connected(string address, int port)
  695. {
  696. logi("Connected to data_compiler@%s:%d".printf(address, port));
  697. _compiler.receive_async();
  698. }
  699. private void on_data_compiler_disconnected()
  700. {
  701. logi("Disconnected from data_compiler");
  702. if (_stop_data_compiler_callback != null)
  703. _stop_data_compiler_callback();
  704. }
  705. private async void on_data_compiler_disconnected_unexpected()
  706. {
  707. logw("Disconnected from data_compiler unexpectedly");
  708. try {
  709. if (_compiler_process != uint32.MAX)
  710. _subprocess_launcher.wait(_compiler_process);
  711. _compiler_process = uint32.MAX;
  712. } catch (GLib.Error e) {
  713. loge(e.message);
  714. }
  715. yield stop_heads();
  716. // Reset the callback
  717. _data_compiler.finished(false);
  718. _project_stack.set_visible_child(_project_stack_compiler_crashed_label);
  719. _editor_stack.set_visible_child(_editor_stack_compiler_crashed_label);
  720. _inspector_stack.set_visible_child(_inspector_stack_compiler_crashed_label);
  721. }
  722. private void on_editor_connected(string address, int port)
  723. {
  724. logi("Connected to level_editor@%s:%d".printf(address, port));
  725. // Start receiving data from the editor view.
  726. _editor.receive_async();
  727. // Update editor view with current editor state.
  728. _level.send_level();
  729. send_state();
  730. _preferences_dialog.apply();
  731. _editor.send(DeviceApi.frame());
  732. }
  733. private void on_editor_disconnected()
  734. {
  735. logi("Disconnected from editor");
  736. if (_stop_editor_callback != null)
  737. _stop_editor_callback();
  738. }
  739. private void on_editor_disconnected_unexpected()
  740. {
  741. logw("Disconnected from editor unexpectedly");
  742. try {
  743. if (_editor_process != uint32.MAX)
  744. _subprocess_launcher.wait(_editor_process);
  745. _editor_process = uint32.MAX;
  746. } catch (GLib.Error e) {
  747. loge(e.message);
  748. }
  749. _editor_stack.set_visible_child(_editor_stack_oops_label);
  750. }
  751. private void on_resource_preview_connected(string address, int port)
  752. {
  753. logi("Connected to preview@%s:%d".printf(address, port));
  754. // Start receiving data from the editor view.
  755. _resource_preview.receive_async();
  756. }
  757. private void on_resource_preview_disconnected()
  758. {
  759. logi("Disconnected from preview");
  760. if (_stop_resource_preview_callback != null)
  761. _stop_resource_preview_callback();
  762. }
  763. private void on_resource_preview_disconnected_unexpected()
  764. {
  765. logw("Disconnected from preview unexpectedly");
  766. try {
  767. if (_resource_preview_process != uint32.MAX)
  768. _subprocess_launcher.wait(_resource_preview_process);
  769. _resource_preview_process = uint32.MAX;
  770. } catch (GLib.Error e) {
  771. loge(e.message);
  772. }
  773. _resource_preview_stack.set_visible_child(_resource_preview_oops_label);
  774. }
  775. private void on_resource_preview_message_received(ConsoleClient client, uint8[] json)
  776. {
  777. // Ignore the message content.
  778. client.receive_async();
  779. }
  780. private void on_game_connected(string address, int port)
  781. {
  782. logi("Connected to game@%s:%d".printf(address, port));
  783. _game.receive_async();
  784. _combo.set_active_id("game");
  785. }
  786. private void on_game_disconnected()
  787. {
  788. logi("Disconnected from game");
  789. _project.delete_garbage();
  790. _combo.set_active_id("editor");
  791. _toolbar_run.icon_name = "game-run";
  792. if (_stop_game_callback != null)
  793. _stop_game_callback();
  794. }
  795. private void on_game_disconnected_externally()
  796. {
  797. on_game_disconnected();
  798. try {
  799. if (_game_process != uint32.MAX)
  800. _subprocess_launcher.wait(_game_process);
  801. _game_process = uint32.MAX;
  802. } catch (GLib.Error e) {
  803. loge(e.message);
  804. }
  805. }
  806. private void on_message_received(ConsoleClient client, uint8[] json)
  807. {
  808. Hashtable msg = JSON.decode(json) as Hashtable;
  809. string msg_type = msg["type"] as string;
  810. if (msg_type == "message") {
  811. log((string)msg["system"], (string)msg["severity"], (string)msg["message"]);
  812. } else if (msg_type == "add_file") {
  813. string path = (string)msg["path"];
  814. _project.add_file(path);
  815. } else if (msg_type == "remove_file") {
  816. string path = (string)msg["path"];
  817. _project.remove_file(path);
  818. } else if (msg_type == "add_tree") {
  819. string path = (string)msg["path"];
  820. _project.add_tree(path);
  821. } else if (msg_type == "remove_tree") {
  822. string path = (string)msg["path"];
  823. _project.remove_tree(path);
  824. } else if (msg_type == "compile") {
  825. // Guid id = Guid.parse((string)msg["id"]);
  826. if (msg.has_key("start")) {
  827. // FIXME
  828. } else if (msg.has_key("success")) {
  829. _data_compiler.finished((bool)msg["success"]);
  830. }
  831. } else if (msg_type == "unit_spawned") {
  832. string id = (string)msg["id"];
  833. string name = (string)msg["name"];
  834. ArrayList<Value?> pos = (ArrayList<Value?>)msg["position"];
  835. ArrayList<Value?> rot = (ArrayList<Value?>)msg["rotation"];
  836. ArrayList<Value?> scl = (ArrayList<Value?>)msg["scale"];
  837. _level.on_unit_spawned(Guid.parse(id)
  838. , name
  839. , Vector3.from_array(pos)
  840. , Quaternion.from_array(rot)
  841. , Vector3.from_array(scl)
  842. );
  843. } else if (msg_type == "sound_spawned") {
  844. string id = (string)msg["id"];
  845. string name = (string)msg["name"];
  846. ArrayList<Value?> pos = (ArrayList<Value?>)msg["position"];
  847. ArrayList<Value?> rot = (ArrayList<Value?>)msg["rotation"];
  848. ArrayList<Value?> scl = (ArrayList<Value?>)msg["scale"];
  849. double range = (double)msg["range"];
  850. double volume = (double)msg["volume"];
  851. bool loop = (bool)msg["loop"];
  852. _level.on_sound_spawned(Guid.parse(id)
  853. , name
  854. , Vector3.from_array(pos)
  855. , Quaternion.from_array(rot)
  856. , Vector3.from_array(scl)
  857. , range
  858. , volume
  859. , loop
  860. );
  861. } else if (msg_type == "move_objects") {
  862. Hashtable ids = (Hashtable)msg["ids"];
  863. Hashtable new_positions = (Hashtable)msg["new_positions"];
  864. Hashtable new_rotations = (Hashtable)msg["new_rotations"];
  865. Hashtable new_scales = (Hashtable)msg["new_scales"];
  866. ArrayList<string> keys = new ArrayList<string>.wrap(ids.keys.to_array());
  867. keys.sort(Gee.Functions.get_compare_func_for(typeof(string)));
  868. Guid[] n_ids = new Guid[keys.size];
  869. Vector3[] n_positions = new Vector3[keys.size];
  870. Quaternion[] n_rotations = new Quaternion[keys.size];
  871. Vector3[] n_scales = new Vector3[keys.size];
  872. for (int i = 0; i < keys.size; ++i) {
  873. string k = keys[i];
  874. n_ids[i] = Guid.parse((string)ids[k]);
  875. n_positions[i] = Vector3.from_array((ArrayList<Value?>)(new_positions[k]));
  876. n_rotations[i] = Quaternion.from_array((ArrayList<Value?>)new_rotations[k]);
  877. n_scales[i] = Vector3.from_array((ArrayList<Value?>)new_scales[k]);
  878. }
  879. _level.on_move_objects(n_ids, n_positions, n_rotations, n_scales);
  880. } else if (msg_type == "selection") {
  881. Hashtable objects = (Hashtable)msg["objects"];
  882. ArrayList<string> keys = new ArrayList<string>.wrap(objects.keys.to_array());
  883. keys.sort(Gee.Functions.get_compare_func_for(typeof(string)));
  884. Guid[] ids = new Guid[keys.size];
  885. for (int i = 0; i < keys.size; ++i) {
  886. string k = keys[i];
  887. ids[i] = Guid.parse((string)objects[k]);
  888. }
  889. _level.on_selection(ids);
  890. } else if (msg_type == "error") {
  891. loge((string)msg["message"]);
  892. } else {
  893. loge("Unknown message type: " + msg_type);
  894. }
  895. // Receive next message
  896. client.receive_async();
  897. }
  898. private void append_editor_state(StringBuilder sb)
  899. {
  900. // This state is common to any project.
  901. sb.append(LevelEditorApi.set_grid_size(_grid_size));
  902. sb.append(LevelEditorApi.set_rotation_snap(_rotation_snap));
  903. sb.append(LevelEditorApi.enable_show_grid(_show_grid));
  904. sb.append(LevelEditorApi.enable_snap_to_grid(_snap_to_grid));
  905. sb.append(LevelEditorApi.enable_debug_render_world(_debug_render_world));
  906. sb.append(LevelEditorApi.enable_debug_physics_world(_debug_physics_world));
  907. sb.append(LevelEditorApi.set_tool_type(_tool_type));
  908. sb.append(LevelEditorApi.set_snap_mode(_snap_mode));
  909. sb.append(LevelEditorApi.set_reference_system(_reference_system));
  910. sb.append(LevelEditorApi.set_camera_view_type(_camera_view_type));
  911. }
  912. private void append_project_state(StringBuilder sb)
  913. {
  914. // This state is not guaranteed to be applicable to any project.
  915. if (_placeable_type != "")
  916. sb.append(LevelEditorApi.set_placeable(_placeable_type, _placeable_name));
  917. }
  918. private void send_state()
  919. {
  920. StringBuilder sb = new StringBuilder();
  921. append_editor_state(sb);
  922. append_project_state(sb);
  923. _editor.send_script(sb.str);
  924. }
  925. private bool on_button_press(Gdk.EventButton ev)
  926. {
  927. return Gdk.EVENT_STOP;
  928. }
  929. private bool on_button_release(Gdk.EventButton ev)
  930. {
  931. return Gdk.EVENT_STOP;
  932. }
  933. Gtk.Label compiling_data_label()
  934. {
  935. return new Gtk.Label("Compiling resources, please wait...");
  936. }
  937. Gtk.Label connecting_to_data_compiler_label()
  938. {
  939. return new Gtk.Label("Connecting to Data Compiler...");
  940. }
  941. Gtk.Label compiler_crashed_label()
  942. {
  943. Gtk.Label label = new Gtk.Label(null);
  944. label.track_visited_links = false;
  945. label.set_markup("Data Compiler disconnected.\rTry to <a href=\"restart\">restart the compiler</a> to continue.");
  946. label.activate_link.connect(() => {
  947. restart_backend.begin(_project.source_dir(), _level._name != null ? _level._name : "");
  948. return true;
  949. });
  950. return label;
  951. }
  952. Gtk.Label compiler_failed_compilation_label()
  953. {
  954. Gtk.Label label = new Gtk.Label(null);
  955. label.track_visited_links = false;
  956. label.set_markup("Data compilation failed.\rFix errors and <a href=\"restart\">restart the compiler</a> to continue.");
  957. label.activate_link.connect(() => {
  958. restart_backend.begin(_project.source_dir(), _level._name != null ? _level._name : "");
  959. return true;
  960. });
  961. return label;
  962. }
  963. public async void restart_backend(string source_dir, string level_name)
  964. {
  965. string sd = source_dir.dup();
  966. string ln = level_name.dup();
  967. yield stop_backend();
  968. // Reset project state.
  969. _placeable_type = "unit";
  970. _placeable_name = "core/units/primitives/cube";
  971. // Load project and level if any.
  972. logi("Loading project: `%s`...".printf(sd));
  973. _project.load(sd);
  974. // Spawn the data compiler.
  975. string args[] =
  976. {
  977. ENGINE_EXE,
  978. "--source-dir",
  979. _project.source_dir(),
  980. "--data-dir",
  981. _project.data_dir(),
  982. "--map-source-dir",
  983. "core",
  984. _project.toolchain_dir(),
  985. "--server",
  986. "--wait-console"
  987. };
  988. try {
  989. _compiler_process = _subprocess_launcher.spawnv_async(subprocess_flags(), args, ENGINE_DIR);
  990. } catch (Error e) {
  991. loge(e.message);
  992. }
  993. // It is an error if the data compiler. disconnects after here.
  994. _compiler.disconnected.disconnect(on_data_compiler_disconnected);
  995. _compiler.disconnected.connect(on_data_compiler_disconnected_unexpected);
  996. _project_stack.set_visible_child(_project_stack_connecting_to_data_compiler_label);
  997. _editor_stack.set_visible_child(_editor_stack_connecting_to_data_compiler_label);
  998. _inspector_stack.set_visible_child(_inspector_stack_connecting_to_data_compiler_label);
  999. int tries = yield _compiler.connect_async(DATA_COMPILER_ADDRESS
  1000. , DATA_COMPILER_TCP_PORT
  1001. , DATA_COMPILER_CONNECTION_TRIES
  1002. , DATA_COMPILER_CONNECTION_INTERVAL
  1003. );
  1004. if (tries == DATA_COMPILER_CONNECTION_TRIES) {
  1005. loge("Cannot connect to data_compiler");
  1006. return;
  1007. }
  1008. _project_stack.set_visible_child(_project_stack_compiling_data_label);
  1009. _editor_stack.set_visible_child(_editor_stack_compiling_data_label);
  1010. _inspector_stack.set_visible_child(_inspector_stack_compiling_data_label);
  1011. // Compile data.
  1012. _data_compiler.compile.begin(_project.data_dir(), _project.platform(), (obj, res) => {
  1013. if (_data_compiler.compile.end(res)) {
  1014. load_level(ln);
  1015. // If successful, start the level editor.
  1016. restart_editor.begin((obj, res) => {
  1017. restart_editor.end(res);
  1018. _project_stack.set_visible_child(_project_browser);
  1019. _inspector_stack.set_visible_child(_inspector_pane);
  1020. });
  1021. } else {
  1022. _project_stack.set_visible_child(_project_stack_compiler_failed_compilation_label);
  1023. _editor_stack.set_visible_child(_editor_stack_compiler_failed_compilation_label);
  1024. _inspector_stack.set_visible_child(_inspector_stack_compiler_failed_compilation_label);
  1025. }
  1026. });
  1027. }
  1028. public async void stop_heads()
  1029. {
  1030. yield stop_game();
  1031. yield stop_editor();
  1032. }
  1033. public async void stop_backend()
  1034. {
  1035. yield stop_heads();
  1036. yield stop_data_compiler();
  1037. _level.reset();
  1038. _project.reset();
  1039. this.active_window.title = LEVEL_EDITOR_WINDOW_TITLE;
  1040. }
  1041. private async void stop_data_compiler()
  1042. {
  1043. if (_compiler != null) {
  1044. // Reset "disconnected" signal.
  1045. _compiler.disconnected.disconnect(on_data_compiler_disconnected);
  1046. _compiler.disconnected.disconnect(on_data_compiler_disconnected_unexpected);
  1047. // Explicit call to this function should not produce error messages.
  1048. _compiler.disconnected.connect(on_data_compiler_disconnected);
  1049. if (_compiler.is_connected()) {
  1050. _stop_data_compiler_callback = stop_data_compiler.callback;
  1051. _compiler.send(DataCompilerApi.quit());
  1052. yield; // Wait for ConsoleClient to disconnect.
  1053. _stop_data_compiler_callback = null;
  1054. }
  1055. }
  1056. try {
  1057. if (_compiler_process != uint32.MAX)
  1058. _subprocess_launcher.wait(_compiler_process);
  1059. _compiler_process = uint32.MAX;
  1060. } catch (GLib.Error e) {
  1061. loge(e.message);
  1062. }
  1063. }
  1064. private async void start_editor(uint window_xid)
  1065. {
  1066. if (window_xid == 0)
  1067. return;
  1068. // Spawn the level editor.
  1069. string args[] =
  1070. {
  1071. ENGINE_EXE,
  1072. "--data-dir",
  1073. _project.data_dir(),
  1074. "--boot-dir",
  1075. LEVEL_EDITOR_BOOT_DIR,
  1076. "--parent-window",
  1077. window_xid.to_string(),
  1078. "--wait-console",
  1079. "--pumped"
  1080. };
  1081. try {
  1082. _editor_process = _subprocess_launcher.spawnv_async(subprocess_flags(), args, ENGINE_DIR);
  1083. } catch (Error e) {
  1084. loge(e.message);
  1085. }
  1086. // It is an error if the level editor disconnects after here.
  1087. _editor.disconnected.disconnect(on_editor_disconnected);
  1088. _editor.disconnected.connect(on_editor_disconnected_unexpected);
  1089. // Try to connect to the level editor.
  1090. int tries = yield _editor.connect_async(EDITOR_ADDRESS
  1091. , EDITOR_TCP_PORT
  1092. , EDITOR_CONNECTION_TRIES
  1093. , EDITOR_CONNECTION_INTERVAL
  1094. );
  1095. if (tries == EDITOR_CONNECTION_TRIES) {
  1096. loge("Cannot connect to level_editor");
  1097. return;
  1098. }
  1099. }
  1100. private async void start_resource_preview(uint window_xid)
  1101. {
  1102. if (window_xid == 0)
  1103. return;
  1104. // Spawn unit_preview.
  1105. string args[] =
  1106. {
  1107. ENGINE_EXE,
  1108. "--data-dir",
  1109. _project.data_dir(),
  1110. "--boot-dir",
  1111. UNIT_PREVIEW_BOOT_DIR,
  1112. "--parent-window",
  1113. window_xid.to_string(),
  1114. "--console-port",
  1115. UNIT_PREVIEW_TCP_PORT.to_string(),
  1116. "--wait-console",
  1117. "--pumped"
  1118. };
  1119. try {
  1120. _resource_preview_process = _subprocess_launcher.spawnv_async(subprocess_flags(), args, ENGINE_DIR);
  1121. } catch (Error e) {
  1122. loge(e.message);
  1123. }
  1124. // It is an error if the unit_preview disconnects after here.
  1125. _resource_preview.disconnected.disconnect(on_resource_preview_disconnected);
  1126. _resource_preview.disconnected.connect(on_resource_preview_disconnected_unexpected);
  1127. // Try to connect to unit_preview.
  1128. int tries = yield _resource_preview.connect_async(UNIT_PREVIEW_ADDRESS
  1129. , UNIT_PREVIEW_TCP_PORT
  1130. , EDITOR_CONNECTION_TRIES
  1131. , EDITOR_CONNECTION_INTERVAL
  1132. );
  1133. if (tries == EDITOR_CONNECTION_TRIES) {
  1134. loge("Cannot connect to unit_preview.");
  1135. return;
  1136. }
  1137. // FIXME: This should be done in ResourceChooser.
  1138. _resource_chooser._tree_view.set_cursor(new Gtk.TreePath.first(), null, false);
  1139. }
  1140. private async void stop_editor()
  1141. {
  1142. yield stop_resource_preview();
  1143. if (_editor != null) {
  1144. // Reset "disconnected" signal.
  1145. _editor.disconnected.disconnect(on_editor_disconnected);
  1146. _editor.disconnected.disconnect(on_editor_disconnected_unexpected);
  1147. // Explicit call to this function should not produce error messages.
  1148. _editor.disconnected.connect(on_editor_disconnected);
  1149. if (_editor.is_connected()) {
  1150. _stop_editor_callback = stop_editor.callback;
  1151. _editor.send_script("Device.quit()");
  1152. yield; // Wait for ConsoleClient to disconnect.
  1153. _stop_editor_callback = null;
  1154. _editor_stack.set_visible_child(_editor_stack_disconnected_label);
  1155. }
  1156. }
  1157. try {
  1158. if (_editor_process != uint32.MAX)
  1159. _subprocess_launcher.wait(_editor_process);
  1160. _editor_process = uint32.MAX;
  1161. } catch (GLib.Error e) {
  1162. loge(e.message);
  1163. }
  1164. }
  1165. public async void stop_resource_preview()
  1166. {
  1167. if (_resource_preview != null) {
  1168. // Reset "disconnected" signal.
  1169. _resource_preview.disconnected.disconnect(on_resource_preview_disconnected);
  1170. _resource_preview.disconnected.disconnect(on_resource_preview_disconnected_unexpected);
  1171. // Explicit call to this function should not produce error messages.
  1172. _resource_preview.disconnected.connect(on_resource_preview_disconnected);
  1173. if (_resource_preview.is_connected()) {
  1174. _stop_resource_preview_callback = stop_resource_preview.callback;
  1175. _resource_preview.send_script("Device.quit()");
  1176. yield; // Wait for ConsoleClient to disconnect.
  1177. _stop_resource_preview_callback = null;
  1178. _resource_preview_stack.set_visible_child(_resource_preview_disconnected_label);
  1179. }
  1180. }
  1181. try {
  1182. if (_resource_preview_process != uint32.MAX)
  1183. _subprocess_launcher.wait(_resource_preview_process);
  1184. _resource_preview_process = uint32.MAX;
  1185. } catch (GLib.Error e) {
  1186. loge(e.message);
  1187. }
  1188. }
  1189. private async void restart_editor()
  1190. {
  1191. yield stop_editor();
  1192. if (_editor_view != null) {
  1193. _editor_view_overlay.remove(_editor_view);
  1194. _editor_stack.remove(_editor_view_overlay);
  1195. _editor_view = null;
  1196. }
  1197. _editor_view = new EditorView(_editor);
  1198. _editor_view.realized.connect(on_editor_view_realized);
  1199. _editor_view.button_press_event.connect(on_button_press);
  1200. _editor_view.button_release_event.connect(on_button_release);
  1201. _editor_view_overlay.add(_editor_view);
  1202. _editor_view_overlay.show_all();
  1203. _editor_stack.add(_editor_view_overlay);
  1204. _editor_stack.set_visible_child(_editor_view_overlay);
  1205. yield restart_resource_preview();
  1206. }
  1207. private async void restart_resource_preview()
  1208. {
  1209. yield stop_resource_preview();
  1210. if (_resource_preview_view != null) {
  1211. _resource_preview_stack.remove(_resource_preview_view);
  1212. _resource_preview_view = null;
  1213. }
  1214. _resource_preview_view = new EditorView(_resource_preview, false);
  1215. _resource_preview_view.set_size_request(300, 300);
  1216. _resource_preview_view.realized.connect(on_resource_preview_view_realized);
  1217. _resource_preview_view.show_all();
  1218. _resource_preview_stack.add(_resource_preview_view);
  1219. _resource_preview_stack.set_visible_child(_resource_preview_view);
  1220. }
  1221. private async void start_game(StartGame sg)
  1222. {
  1223. // Save test level to file
  1224. _database.dump(_project._level_editor_test_level.get_path(), _level._id);
  1225. // Save temporary package to reference test level
  1226. ArrayList<Value?> level = new ArrayList<Value?>();
  1227. level.add("_level_editor_test");
  1228. Hashtable package = new Hashtable();
  1229. package["level"] = level;
  1230. SJSON.save(package, _project._level_editor_test_package.get_path());
  1231. bool success = yield _data_compiler.compile(_project.data_dir(), _project.platform());
  1232. if (!success) {
  1233. _toolbar_run.icon_name = "game-run";
  1234. return;
  1235. }
  1236. // Spawn the game.
  1237. string args[] =
  1238. {
  1239. ENGINE_EXE,
  1240. "--data-dir",
  1241. _project.data_dir(),
  1242. "--console-port",
  1243. GAME_TCP_PORT.to_string(),
  1244. "--wait-console",
  1245. "--lua-string",
  1246. sg == StartGame.TEST ? "TEST=true" : ""
  1247. };
  1248. try {
  1249. _game_process = _subprocess_launcher.spawnv_async(subprocess_flags(), args, ENGINE_DIR);
  1250. } catch (Error e) {
  1251. loge(e.message);
  1252. }
  1253. // Try to connect to the game.
  1254. int tries = yield _game.connect_async(GAME_ADDRESS
  1255. , GAME_TCP_PORT
  1256. , GAME_CONNECTION_TRIES
  1257. , GAME_CONNECTION_INTERVAL
  1258. );
  1259. if (tries == GAME_CONNECTION_TRIES) {
  1260. loge("Cannot connect to game");
  1261. return;
  1262. }
  1263. }
  1264. private async void stop_game()
  1265. {
  1266. if (_game != null) {
  1267. // Reset "disconnected" signal.
  1268. _game.disconnected.disconnect(on_game_disconnected);
  1269. _game.disconnected.disconnect(on_game_disconnected_externally);
  1270. // Explicit call to this function should not produce error messages.
  1271. _game.disconnected.connect(on_game_disconnected);
  1272. if (_game.is_connected()) {
  1273. _stop_game_callback = stop_game.callback;
  1274. _game.send_script("Device.quit()");
  1275. yield; // Wait for SocketClient to disconnect.
  1276. _stop_game_callback = null;
  1277. }
  1278. }
  1279. try {
  1280. if (_game_process != uint32.MAX)
  1281. _subprocess_launcher.wait(_game_process);
  1282. _game_process = uint32.MAX;
  1283. } catch (GLib.Error e) {
  1284. loge(e.message);
  1285. }
  1286. }
  1287. private void deploy_game()
  1288. {
  1289. Gtk.FileChooserDialog fcd = new Gtk.FileChooserDialog("Select destination directory..."
  1290. , this.active_window
  1291. , FileChooserAction.SELECT_FOLDER
  1292. , "Cancel"
  1293. , ResponseType.CANCEL
  1294. , "Open"
  1295. , ResponseType.ACCEPT
  1296. );
  1297. if (fcd.run() == ResponseType.ACCEPT) {
  1298. GLib.File data_dir = File.new_for_path(fcd.get_filename());
  1299. string args[] =
  1300. {
  1301. ENGINE_EXE,
  1302. "--source-dir",
  1303. _project.source_dir(),
  1304. "--map-source-dir",
  1305. "core",
  1306. _project.toolchain_dir(),
  1307. "--data-dir",
  1308. data_dir.get_path(),
  1309. "--compile"
  1310. };
  1311. try {
  1312. uint32 compiler = _subprocess_launcher.spawnv_async(subprocess_flags(), args, ENGINE_DIR);
  1313. int exit_status = _subprocess_launcher.wait(compiler);
  1314. if (exit_status == 0) {
  1315. string game_name = DEPLOY_DEFAULT_NAME;
  1316. GLib.File engine_exe_src = File.new_for_path(DEPLOY_EXE);
  1317. GLib.File engine_exe_dst = File.new_for_path(Path.build_filename(data_dir.get_path(), game_name + EXE_SUFFIX));
  1318. engine_exe_src.copy(engine_exe_dst, FileCopyFlags.OVERWRITE);
  1319. #if CROWN_PLATFORM_WINDOWS
  1320. string lua51_name = "lua51.dll";
  1321. GLib.File lua51_dll_src = File.new_for_path(lua51_name);
  1322. GLib.File lua51_dll_dst = File.new_for_path(Path.build_filename(data_dir.get_path(), lua51_name));
  1323. lua51_dll_src.copy(lua51_dll_dst, FileCopyFlags.OVERWRITE);
  1324. string openal_name = "openal-release.dll";
  1325. GLib.File openal_dll_src = File.new_for_path(openal_name);
  1326. GLib.File openal_dll_dst = File.new_for_path(Path.build_filename(data_dir.get_path(), openal_name));
  1327. openal_dll_src.copy(openal_dll_dst, FileCopyFlags.OVERWRITE);
  1328. #endif
  1329. logi("Project deployed to `%s`".printf(data_dir.get_path()));
  1330. }
  1331. }
  1332. catch (Error e) {
  1333. loge("%s".printf(e.message));
  1334. loge("Failed to deploy project");
  1335. }
  1336. }
  1337. fcd.destroy();
  1338. }
  1339. private async void on_editor_view_realized()
  1340. {
  1341. start_editor.begin(_editor_view.window_id);
  1342. }
  1343. private async void on_resource_preview_view_realized()
  1344. {
  1345. start_resource_preview.begin(_resource_preview_view.window_id);
  1346. }
  1347. private void on_tool(GLib.SimpleAction action, GLib.Variant? param)
  1348. {
  1349. ToolType type = (ToolType)param.get_int32();
  1350. if (type == ToolType.PLACE) {
  1351. // Store previous tool for it to be restored later.
  1352. if (_tool_type != ToolType.PLACE)
  1353. _tool_type_prev = _tool_type;
  1354. }
  1355. _tool_type = type;
  1356. _editor_view.grab_focus();
  1357. send_state();
  1358. _editor.send(DeviceApi.frame());
  1359. action.set_state(param);
  1360. }
  1361. private void on_snap(GLib.SimpleAction action, GLib.Variant? param)
  1362. {
  1363. _snap_mode = (SnapMode)param.get_int32();
  1364. send_state();
  1365. _editor.send(DeviceApi.frame());
  1366. action.set_state(param);
  1367. }
  1368. private void on_reference_system(GLib.SimpleAction action, GLib.Variant? param)
  1369. {
  1370. _reference_system = (ReferenceSystem)param.get_int32();
  1371. send_state();
  1372. _editor.send(DeviceApi.frame());
  1373. action.set_state(param);
  1374. }
  1375. private void on_grid_size(GLib.SimpleAction action, GLib.Variant? param)
  1376. {
  1377. int32 new_size = param.get_int32();
  1378. if (new_size != 0) {
  1379. _grid_size = (double)new_size / 10.0;
  1380. send_state();
  1381. _editor.send(DeviceApi.frame());
  1382. action.set_state(param);
  1383. return;
  1384. }
  1385. // Custom grid size.
  1386. Gtk.Dialog dg = new Gtk.Dialog.with_buttons("Grid size"
  1387. , this.active_window
  1388. , DialogFlags.MODAL
  1389. , "Cancel"
  1390. , ResponseType.CANCEL
  1391. , "Ok"
  1392. , ResponseType.OK
  1393. , null
  1394. );
  1395. EntryDouble sb = new EntryDouble(_grid_size, 0.1, 1000);
  1396. sb.activate.connect(() => { dg.response(ResponseType.OK); });
  1397. dg.get_content_area().add(sb);
  1398. dg.skip_taskbar_hint = true;
  1399. dg.show_all();
  1400. if (dg.run() == ResponseType.OK) {
  1401. _grid_size = sb.value;
  1402. send_state();
  1403. _editor.send(DeviceApi.frame());
  1404. action.set_state(param);
  1405. }
  1406. dg.destroy();
  1407. }
  1408. private void new_level()
  1409. {
  1410. _level.load_from_path(LEVEL_EMPTY);
  1411. _level.send_level();
  1412. _editor.send(DeviceApi.frame());
  1413. }
  1414. private void update_active_window_title()
  1415. {
  1416. string title = "";
  1417. if (_level._name != null) {
  1418. title += (_level._name == LEVEL_EMPTY) ? "untitled" : _level._name;
  1419. if (_database.changed())
  1420. title += " • ";
  1421. title += " - ";
  1422. }
  1423. title += LEVEL_EDITOR_WINDOW_TITLE;
  1424. if (this.active_window.title != title)
  1425. this.active_window.title = title;
  1426. }
  1427. private void load_level(string name)
  1428. {
  1429. if (name == _level._name)
  1430. return;
  1431. string resource_name = name != "" ? name : LEVEL_EMPTY;
  1432. if (_level.load_from_path(resource_name) != 0) {
  1433. loge("Unable to load level %s".printf(resource_name));
  1434. return;
  1435. }
  1436. if (_editor.is_connected()) {
  1437. _level.send_level();
  1438. send_state();
  1439. _editor.send(DeviceApi.frame());
  1440. }
  1441. update_active_window_title();
  1442. }
  1443. private bool save_as(string? filename)
  1444. {
  1445. string path = filename;
  1446. if (path == null) {
  1447. Gtk.FileChooserDialog fcd = new Gtk.FileChooserDialog("Save As..."
  1448. , this.active_window
  1449. , FileChooserAction.SAVE
  1450. , "Cancel"
  1451. , ResponseType.CANCEL
  1452. , "Save"
  1453. , ResponseType.ACCEPT
  1454. );
  1455. fcd.add_filter(_file_filter);
  1456. fcd.set_current_folder(_project.source_dir());
  1457. int rt = ResponseType.CANCEL;
  1458. do {
  1459. // Select the file
  1460. rt = fcd.run();
  1461. if (rt != ResponseType.ACCEPT) {
  1462. fcd.destroy();
  1463. return false;
  1464. }
  1465. path = fcd.get_filename();
  1466. // Append file extension
  1467. if (!path.has_suffix(".level"))
  1468. path += ".level";
  1469. // Check if the file is within the source directory
  1470. if (!_project.path_is_within_source_dir(path)) {
  1471. Gtk.MessageDialog md = new Gtk.MessageDialog(fcd
  1472. , DialogFlags.MODAL
  1473. , MessageType.WARNING
  1474. , Gtk.ButtonsType.OK
  1475. , "The file must be within the source directory."
  1476. );
  1477. md.set_default_response(ResponseType.OK);
  1478. md.run();
  1479. md.destroy();
  1480. fcd.set_current_folder(_project.source_dir());
  1481. continue;
  1482. }
  1483. // Check if the file already exists
  1484. rt = ResponseType.YES;
  1485. if (GLib.FileUtils.test(path, FileTest.EXISTS)) {
  1486. Gtk.MessageDialog md = new Gtk.MessageDialog(fcd
  1487. , DialogFlags.MODAL
  1488. , MessageType.QUESTION
  1489. , Gtk.ButtonsType.YES_NO
  1490. , "A file named `%s` already exists.\nOverwrite?".printf(_project.basename(path))
  1491. );
  1492. md.set_default_response(ResponseType.NO);
  1493. rt = md.run();
  1494. md.destroy();
  1495. }
  1496. } while (rt != ResponseType.YES);
  1497. fcd.destroy();
  1498. }
  1499. // Save level
  1500. string resource_filename = _project.absolute_path_to_resource_filename(path);
  1501. string resource_path = _project.resource_filename_to_resource_path(resource_filename);
  1502. string resource_name = _project.resource_path_to_resource_name(resource_path);
  1503. _level.save(resource_name);
  1504. _statusbar.set_temporary_message("Saved %s".printf(_level._path));
  1505. update_active_window_title();
  1506. return true;
  1507. }
  1508. private bool save()
  1509. {
  1510. return save_as(_level._path);
  1511. }
  1512. private bool save_timeout()
  1513. {
  1514. if (_level._path != null)
  1515. save();
  1516. return GLib.Source.CONTINUE;
  1517. }
  1518. protected override void shutdown()
  1519. {
  1520. // Disable auto-save.
  1521. if (_save_timer_id > 0)
  1522. GLib.Source.remove(_save_timer_id);
  1523. // Save editor settings.
  1524. _user.save(_user_file.get_path());
  1525. _preferences_dialog.encode(_settings);
  1526. SJSON.save(_settings, _settings_file.get_path());
  1527. _console_view._entry_history.save(_console_history_file.get_path());
  1528. // Destroy widgets.
  1529. if (_resource_chooser != null)
  1530. _resource_chooser.destroy();
  1531. if (_preferences_dialog != null)
  1532. _preferences_dialog.destroy();
  1533. base.shutdown();
  1534. }
  1535. // Returns true if the level has been saved or the user decided it
  1536. // should be discarded.
  1537. public bool should_quit()
  1538. {
  1539. int rt = ResponseType.YES;
  1540. if (_database.changed())
  1541. rt = run_level_changed_dialog(this.active_window);
  1542. if (!_database.changed() || rt == ResponseType.YES && save() || rt == ResponseType.NO)
  1543. return true;
  1544. return false;
  1545. }
  1546. private void on_new_level(GLib.SimpleAction action, GLib.Variant? param)
  1547. {
  1548. int rt = ResponseType.YES;
  1549. if (_database.changed())
  1550. rt = run_level_changed_dialog(this.active_window);
  1551. if (!_database.changed() || rt == ResponseType.YES && save() || rt == ResponseType.NO) {
  1552. new_level();
  1553. send_state();
  1554. _editor.send(DeviceApi.frame());
  1555. }
  1556. }
  1557. private void on_open_level_from_menubar(GLib.SimpleAction action, GLib.Variant? param)
  1558. {
  1559. string path = "";
  1560. Gtk.FileChooserDialog fcd = new Gtk.FileChooserDialog("Open Level..."
  1561. , this.active_window
  1562. , FileChooserAction.OPEN
  1563. , "Cancel"
  1564. , ResponseType.CANCEL
  1565. , "Open"
  1566. , ResponseType.ACCEPT
  1567. );
  1568. fcd.add_filter(_file_filter);
  1569. fcd.set_current_folder(_project.source_dir());
  1570. int err = 1;
  1571. int rt = ResponseType.CANCEL;
  1572. do {
  1573. // Select the file
  1574. rt = fcd.run();
  1575. if (rt != ResponseType.ACCEPT) {
  1576. fcd.destroy();
  1577. return;
  1578. }
  1579. path = fcd.get_filename();
  1580. err = 0;
  1581. // Append file extension
  1582. if (!path.has_suffix(".level"))
  1583. path += ".level";
  1584. if (!_project.path_is_within_source_dir(path)) {
  1585. Gtk.MessageDialog md = new Gtk.MessageDialog(fcd
  1586. , DialogFlags.MODAL
  1587. , MessageType.WARNING
  1588. , Gtk.ButtonsType.OK
  1589. , "The file must be within the source directory."
  1590. );
  1591. md.set_default_response(ResponseType.OK);
  1592. md.run();
  1593. md.destroy();
  1594. fcd.set_current_folder(_project.source_dir());
  1595. err = 1;
  1596. continue;
  1597. }
  1598. } while (err != 0);
  1599. fcd.destroy();
  1600. assert(path != "");
  1601. // Load level
  1602. string resource_filename = _project.absolute_path_to_resource_filename(path);
  1603. string resource_path = _project.resource_filename_to_resource_path(resource_filename);
  1604. string resource_name = _project.resource_path_to_resource_name(resource_path);
  1605. load_level(resource_name);
  1606. }
  1607. private void on_open_level(GLib.SimpleAction action, GLib.Variant? param)
  1608. {
  1609. int rt = ResponseType.YES;
  1610. string level_name = param.get_string();
  1611. if (level_name != "" && level_name == _level._name)
  1612. return;
  1613. if (_database.changed())
  1614. rt = run_level_changed_dialog(this.active_window);
  1615. if (!_database.changed() || rt == ResponseType.YES && save() || rt == ResponseType.NO) {
  1616. if (level_name != "")
  1617. load_level(level_name);
  1618. else // Action invoked from menubar File > Open Level...
  1619. on_open_level_from_menubar(action, param);
  1620. }
  1621. }
  1622. private void on_open_project(GLib.SimpleAction action, GLib.Variant? param)
  1623. {
  1624. int rt = ResponseType.YES;
  1625. if (_database.changed())
  1626. rt = run_level_changed_dialog(this.active_window);
  1627. if (!_database.changed() || rt == ResponseType.YES && save() || rt == ResponseType.NO) {
  1628. string source_dir;
  1629. source_dir = param.get_string();
  1630. if (source_dir == "") {
  1631. // Project opened from menubar.
  1632. rt = run_open_project_dialog(out source_dir, this.active_window);
  1633. if (rt != ResponseType.ACCEPT)
  1634. return;
  1635. }
  1636. if (_project.source_dir() == source_dir)
  1637. return;
  1638. this.show_panel("main_vbox", Gtk.StackTransitionType.NONE);
  1639. _user.add_or_touch_recent_project(source_dir, source_dir);
  1640. restart_backend.begin(source_dir, LEVEL_NONE);
  1641. }
  1642. }
  1643. private void on_new_project(GLib.SimpleAction action, GLib.Variant? param)
  1644. {
  1645. int rt = ResponseType.YES;
  1646. if (_database.changed())
  1647. rt = run_level_changed_dialog(this.active_window);
  1648. if (!_database.changed() || rt == ResponseType.YES && save() || rt == ResponseType.NO) {
  1649. stop_backend.begin((obj, res) => {
  1650. stop_backend.end(res);
  1651. show_panel("panel_new_project");
  1652. });
  1653. }
  1654. }
  1655. private void on_save(GLib.SimpleAction action, GLib.Variant? param)
  1656. {
  1657. save();
  1658. }
  1659. private void on_save_as(GLib.SimpleAction action, GLib.Variant? param)
  1660. {
  1661. save_as(null);
  1662. }
  1663. private void on_import(GLib.SimpleAction action, GLib.Variant? param)
  1664. {
  1665. string destination_dir = param.get_string();
  1666. _project.import(destination_dir != "" ? destination_dir : null, this.active_window);
  1667. }
  1668. private void on_preferences(GLib.SimpleAction action, GLib.Variant? param)
  1669. {
  1670. _preferences_dialog.set_transient_for(this.active_window);
  1671. _preferences_dialog.set_position(Gtk.WindowPosition.CENTER_ON_PARENT);
  1672. _preferences_dialog.show_all();
  1673. }
  1674. private void on_deploy(GLib.SimpleAction action, GLib.Variant? param)
  1675. {
  1676. deploy_game();
  1677. }
  1678. private int run_level_changed_dialog(Gtk.Window? parent)
  1679. {
  1680. Gtk.MessageDialog md = new Gtk.MessageDialog(parent
  1681. , Gtk.DialogFlags.MODAL
  1682. , Gtk.MessageType.WARNING
  1683. , Gtk.ButtonsType.NONE
  1684. , "Save changes to Level before closing?"
  1685. );
  1686. md.add_button("Close _without Saving", ResponseType.NO);
  1687. md.add_button("_Cancel", ResponseType.CANCEL);
  1688. md.add_button("_Save", ResponseType.YES);
  1689. md.set_default_response(ResponseType.YES);
  1690. int rt = md.run();
  1691. md.destroy();
  1692. return rt;
  1693. }
  1694. public int run_open_project_dialog(out string source_dir, Gtk.Window? parent)
  1695. {
  1696. Gtk.FileChooserDialog fcd = new Gtk.FileChooserDialog("Open Project..."
  1697. , parent
  1698. , FileChooserAction.SELECT_FOLDER
  1699. , "Cancel"
  1700. , ResponseType.CANCEL
  1701. , "Open"
  1702. , ResponseType.ACCEPT
  1703. );
  1704. int rt = fcd.run();
  1705. source_dir = fcd.get_filename();
  1706. fcd.destroy();
  1707. return rt;
  1708. }
  1709. private void on_close(GLib.SimpleAction action, GLib.Variant? param)
  1710. {
  1711. int rt = ResponseType.YES;
  1712. if (_database.changed())
  1713. rt = run_level_changed_dialog(this.active_window);
  1714. if (!_database.changed() || rt == ResponseType.YES && save() || rt == ResponseType.NO) {
  1715. stop_backend.begin((obj, res) => {
  1716. stop_backend.end(res);
  1717. show_panel("panel_welcome");
  1718. });
  1719. }
  1720. }
  1721. public void stop_backend_and_quit()
  1722. {
  1723. stop_backend.begin((obj, res) => {
  1724. stop_backend.end(res);
  1725. this.quit();
  1726. });
  1727. }
  1728. private void on_quit(GLib.SimpleAction action, GLib.Variant? param)
  1729. {
  1730. if (should_quit())
  1731. stop_backend_and_quit();
  1732. }
  1733. public static bool is_image_file(string path)
  1734. {
  1735. return path.has_suffix(".png")
  1736. || path.has_suffix(".tga")
  1737. ;
  1738. }
  1739. private void on_open_resource(GLib.SimpleAction action, GLib.Variant? param)
  1740. {
  1741. if (param == null)
  1742. return;
  1743. string resource_path = param.get_string();
  1744. string? type = Crown.resource_type(resource_path);
  1745. string? name = Crown.resource_name(type, resource_path);
  1746. if (type == null || name == null)
  1747. return;
  1748. if (type == "level") {
  1749. activate_action("open-level", name);
  1750. return;
  1751. }
  1752. GLib.AppInfo? app = null;
  1753. if (type == "lua") {
  1754. app = _preferences_dialog._lua_external_tool_button.get_app_info();
  1755. } else if (is_image_file(resource_path)) {
  1756. app = _preferences_dialog._image_external_tool_button.get_app_info();
  1757. }
  1758. try {
  1759. GLib.File file = GLib.File.new_for_path(_project.resource_path_to_absolute_path(resource_path));
  1760. if (app == null)
  1761. app = file.query_default_handler();
  1762. GLib.List<GLib.File> files = new GLib.List<GLib.File>();
  1763. files.append(file);
  1764. app.launch(files, null);
  1765. }
  1766. catch (Error e) {
  1767. loge(e.message);
  1768. }
  1769. }
  1770. private void on_show_grid(GLib.SimpleAction action, GLib.Variant? param)
  1771. {
  1772. _show_grid = !action.get_state().get_boolean();
  1773. send_state();
  1774. _editor.send(DeviceApi.frame());
  1775. action.set_state(new GLib.Variant.boolean(_show_grid));
  1776. }
  1777. private void on_rotation_snap_size(GLib.SimpleAction action, GLib.Variant? param)
  1778. {
  1779. int32 new_size = param.get_int32();
  1780. if (new_size != 0) {
  1781. _rotation_snap = (double)new_size;
  1782. send_state();
  1783. _editor.send(DeviceApi.frame());
  1784. action.set_state(param);
  1785. return;
  1786. }
  1787. // Custom rotation size.
  1788. Gtk.Dialog dg = new Gtk.Dialog.with_buttons("Rotation snap"
  1789. , this.active_window
  1790. , DialogFlags.MODAL
  1791. , "Cancel"
  1792. , ResponseType.CANCEL
  1793. , "Ok"
  1794. , ResponseType.OK
  1795. , null
  1796. );
  1797. EntryDouble sb = new EntryDouble(_rotation_snap, 1.0, 180.0);
  1798. sb.activate.connect(() => { dg.response(ResponseType.OK); });
  1799. dg.get_content_area().add(sb);
  1800. dg.skip_taskbar_hint = true;
  1801. dg.show_all();
  1802. if (dg.run() == ResponseType.OK) {
  1803. _rotation_snap = sb.value;
  1804. send_state();
  1805. _editor.send(DeviceApi.frame());
  1806. action.set_state(param);
  1807. }
  1808. dg.destroy();
  1809. }
  1810. private void on_create_primitive(GLib.SimpleAction action, GLib.Variant? param)
  1811. {
  1812. if (action.name == "primitive-cube")
  1813. set_placeable("unit", "core/units/primitives/cube");
  1814. else if (action.name == "primitive-sphere")
  1815. set_placeable("unit", "core/units/primitives/sphere");
  1816. else if (action.name == "primitive-cone")
  1817. set_placeable("unit", "core/units/primitives/cone");
  1818. else if (action.name == "primitive-cylinder")
  1819. set_placeable("unit", "core/units/primitives/cylinder");
  1820. else if (action.name == "primitive-plane")
  1821. set_placeable("unit", "core/units/primitives/plane");
  1822. else if (action.name == "camera")
  1823. set_placeable("unit", "core/units/camera");
  1824. else if (action.name == "light")
  1825. set_placeable("unit", "core/units/light");
  1826. else if (action.name == "sound-source")
  1827. set_placeable("sound", "");
  1828. activate_action("tool", new GLib.Variant.int32(ToolType.PLACE));
  1829. }
  1830. private void on_create_unit(GLib.SimpleAction action, GLib.Variant? param)
  1831. {
  1832. _level.spawn_empty_unit();
  1833. _editor.send(DeviceApi.frame());
  1834. }
  1835. private void on_camera_view(GLib.SimpleAction action, GLib.Variant? param)
  1836. {
  1837. _camera_view_type = (CameraViewType)param.get_int32();
  1838. send_state();
  1839. _editor.send(DeviceApi.frame());
  1840. action.set_state(param);
  1841. }
  1842. private void on_resource_chooser(GLib.SimpleAction action, GLib.Variant? param)
  1843. {
  1844. _resource_popover.show_all();
  1845. }
  1846. private void on_project_browser(GLib.SimpleAction action, GLib.Variant? param)
  1847. {
  1848. if (_project_stack.is_visible()) {
  1849. _project_stack.hide();
  1850. } else {
  1851. _project_stack.show_all();
  1852. }
  1853. }
  1854. private void on_console(GLib.SimpleAction action, GLib.Variant? param)
  1855. {
  1856. if (_console_view.is_visible()) {
  1857. if (_console_view._entry.has_focus)
  1858. _console_view.hide();
  1859. else
  1860. _console_view._entry.grab_focus_without_selecting();
  1861. } else {
  1862. _console_view.show_all();
  1863. _console_view._entry.grab_focus_without_selecting();
  1864. }
  1865. }
  1866. private void on_statusbar(GLib.SimpleAction action, GLib.Variant? param)
  1867. {
  1868. if (_statusbar.is_visible()) {
  1869. _statusbar.hide();
  1870. } else {
  1871. _statusbar.show_all();
  1872. }
  1873. }
  1874. private void on_inspector(GLib.SimpleAction action, GLib.Variant? param)
  1875. {
  1876. if (_inspector_stack.is_visible()) {
  1877. _inspector_stack.hide();
  1878. } else {
  1879. _inspector_stack.show_all();
  1880. }
  1881. }
  1882. private void on_restart_editor_view(GLib.SimpleAction action, GLib.Variant? param)
  1883. {
  1884. restart_editor.begin((obj, res) => {
  1885. restart_editor.end(res);
  1886. });
  1887. }
  1888. private void on_build_data(GLib.SimpleAction action, GLib.Variant? param)
  1889. {
  1890. _data_compiler.compile.begin(_project.data_dir(), _project.platform(), (obj, res) => {
  1891. _data_compiler.compile.end(res);
  1892. });
  1893. }
  1894. private void on_refresh_lua(GLib.SimpleAction action, GLib.Variant? param)
  1895. {
  1896. _data_compiler.compile.begin(_project.data_dir(), _project.platform(), (obj, res) => {
  1897. if (_data_compiler.compile.end(res)) {
  1898. _editor.send(DeviceApi.refresh());
  1899. _editor.send(DeviceApi.frame());
  1900. _game.send(DeviceApi.refresh());
  1901. _game.send(DeviceApi.frame());
  1902. }
  1903. });
  1904. }
  1905. private void on_snap_to_grid(GLib.SimpleAction action, GLib.Variant? param)
  1906. {
  1907. _snap_to_grid = !action.get_state().get_boolean();
  1908. send_state();
  1909. _editor.send(DeviceApi.frame());
  1910. action.set_state(new GLib.Variant.boolean(_snap_to_grid));
  1911. }
  1912. private void on_debug_render_world(GLib.SimpleAction action, GLib.Variant? param)
  1913. {
  1914. _debug_render_world = !action.get_state().get_boolean();
  1915. send_state();
  1916. _editor.send(DeviceApi.frame());
  1917. action.set_state(new GLib.Variant.boolean(_debug_render_world));
  1918. }
  1919. private void on_debug_physics_world(GLib.SimpleAction action, GLib.Variant? param)
  1920. {
  1921. _debug_physics_world = !action.get_state().get_boolean();
  1922. send_state();
  1923. _editor.send(DeviceApi.frame());
  1924. action.set_state(new GLib.Variant.boolean(_debug_physics_world));
  1925. }
  1926. private void on_run_game(GLib.SimpleAction action, GLib.Variant? param)
  1927. {
  1928. string icon_name_displayed = _toolbar_run.icon_name;
  1929. stop_game.begin((obj, res) => {
  1930. stop_game.end(res);
  1931. if (icon_name_displayed == "game-run") {
  1932. // Always change icon state regardless of failures
  1933. _toolbar_run.icon_name = "game-stop";
  1934. //
  1935. _game.disconnected.disconnect(on_game_disconnected);
  1936. _game.disconnected.connect(on_game_disconnected_externally);
  1937. start_game.begin(action.name == "test-level" ? StartGame.TEST : StartGame.NORMAL);
  1938. }
  1939. });
  1940. }
  1941. private void on_undo(GLib.SimpleAction action, GLib.Variant? param)
  1942. {
  1943. int id = _database.undo();
  1944. if (id != -1)
  1945. _statusbar.set_temporary_message("Undo: " + ActionNames[id]);
  1946. }
  1947. private void on_redo(GLib.SimpleAction action, GLib.Variant? param)
  1948. {
  1949. int id = _database.redo();
  1950. if (id != -1)
  1951. _statusbar.set_temporary_message("Redo: " + ActionNames[id]);
  1952. }
  1953. private void on_duplicate(GLib.SimpleAction action, GLib.Variant? param)
  1954. {
  1955. _level.duplicate_selected_objects();
  1956. _editor.send(DeviceApi.frame());
  1957. }
  1958. private void on_delete(GLib.SimpleAction action, GLib.Variant? param)
  1959. {
  1960. _level.destroy_selected_objects();
  1961. _editor.send(DeviceApi.frame());
  1962. }
  1963. private void on_manual(GLib.SimpleAction action, GLib.Variant? param)
  1964. {
  1965. try {
  1966. AppInfo.launch_default_for_uri("https://docs.crownengine.org/html/v" + CROWN_VERSION, null);
  1967. }
  1968. catch (Error e) {
  1969. loge(e.message);
  1970. }
  1971. }
  1972. private void on_report_issue(GLib.SimpleAction action, GLib.Variant? param)
  1973. {
  1974. try {
  1975. AppInfo.launch_default_for_uri("https://github.com/crownengine/crown/issues", null);
  1976. }
  1977. catch (Error e) {
  1978. loge(e.message);
  1979. }
  1980. }
  1981. private void on_browse_logs(GLib.SimpleAction action, GLib.Variant? param)
  1982. {
  1983. open_directory(_logs_dir.get_path());
  1984. }
  1985. private void on_changelog(GLib.SimpleAction action, GLib.Variant? param)
  1986. {
  1987. try {
  1988. AppInfo.launch_default_for_uri("https://docs.crownengine.org/html/v" + CROWN_VERSION + "/changelog.html", null);
  1989. }
  1990. catch (Error e) {
  1991. loge(e.message);
  1992. }
  1993. }
  1994. private void on_about(GLib.SimpleAction action, GLib.Variant? param)
  1995. {
  1996. Gtk.AboutDialog dlg = new Gtk.AboutDialog();
  1997. dlg.set_destroy_with_parent(true);
  1998. dlg.set_transient_for(this.active_window);
  1999. dlg.set_modal(true);
  2000. dlg.set_logo_icon_name(CROWN_ICON_NAME);
  2001. dlg.program_name = LEVEL_EDITOR_WINDOW_TITLE;
  2002. dlg.version = CROWN_VERSION;
  2003. dlg.website = "https://www.crownengine.org";
  2004. dlg.copyright = "Copyright (c) 2012-2023 Daniele Bartolini et al.";
  2005. dlg.license_type = GPL_3_0;
  2006. dlg.authors =
  2007. {
  2008. "Daniele Bartolini",
  2009. "Simone Boscaratto",
  2010. "Michele Rossi",
  2011. "Raphael de Vasconcelos Nascimento"
  2012. };
  2013. dlg.artists =
  2014. {
  2015. "Michela Iacchelli - Pepper logo",
  2016. "Giulia Gazzoli - Crown logo"
  2017. };
  2018. dlg.run();
  2019. dlg.destroy();
  2020. }
  2021. private void on_delete_file(GLib.SimpleAction action, GLib.Variant? param)
  2022. {
  2023. if (param == null)
  2024. return;
  2025. string resource_path = param.get_string();
  2026. string? type = Crown.resource_type(resource_path);
  2027. string? name = Crown.resource_name(type, resource_path);
  2028. if (type == null || name == null)
  2029. return;
  2030. if (name == _level._name) {
  2031. int rt = ResponseType.YES;
  2032. if (_database.changed())
  2033. rt = run_level_changed_dialog(this.active_window);
  2034. if (!_database.changed() || rt == ResponseType.YES && save() || rt == ResponseType.NO) {
  2035. new_level();
  2036. send_state();
  2037. _editor.send(DeviceApi.frame());
  2038. _project.delete_resource(type, name);
  2039. }
  2040. } else {
  2041. _project.delete_resource(type, name);
  2042. }
  2043. }
  2044. public void set_autosave_timer(uint minutes)
  2045. {
  2046. if (_save_timer_id > 0)
  2047. GLib.Source.remove(_save_timer_id);
  2048. _save_timer_id = GLib.Timeout.add_seconds(minutes*60, save_timeout);
  2049. }
  2050. public void menu_set_enabled(bool enabled, GLib.ActionEntry[] entries, string[]? whitelist = null)
  2051. {
  2052. for (int ii = 0; ii < entries.length; ++ii) {
  2053. string action_name = entries[ii].name;
  2054. int jj = 0;
  2055. if (whitelist != null) {
  2056. for (; jj < whitelist.length; ++jj) {
  2057. if (action_name == whitelist[jj])
  2058. break;
  2059. }
  2060. }
  2061. if (whitelist == null || whitelist != null && jj == whitelist.length) {
  2062. GLib.SimpleAction sa = this.lookup_action(action_name) as GLib.SimpleAction;
  2063. if (sa != null)
  2064. sa.set_enabled(enabled);
  2065. }
  2066. }
  2067. }
  2068. private void set_conflicting_accels(bool on)
  2069. {
  2070. if (on) {
  2071. this.set_accels_for_action("app.tool(0)", _tool_place_accels);
  2072. this.set_accels_for_action("app.tool(1)", _tool_move_accels);
  2073. this.set_accels_for_action("app.tool(2)", _tool_rotate_accels);
  2074. this.set_accels_for_action("app.tool(3)", _tool_scale_accels);
  2075. this.set_accels_for_action("app.delete", _delete_accels);
  2076. this.set_accels_for_action("app.camera-view(0)", _camera_view_perspective_accels);
  2077. this.set_accels_for_action("app.camera-view(1)", _camera_view_front_accels);
  2078. this.set_accels_for_action("app.camera-view(2)", _camera_view_back_accels);
  2079. this.set_accels_for_action("app.camera-view(3)", _camera_view_right_accels);
  2080. this.set_accels_for_action("app.camera-view(4)", _camera_view_left_accels);
  2081. this.set_accels_for_action("app.camera-view(5)", _camera_view_top_accels);
  2082. this.set_accels_for_action("app.camera-view(6)", _camera_view_bottom_accels);
  2083. } else {
  2084. this.set_accels_for_action("app.tool(0)", {});
  2085. this.set_accels_for_action("app.tool(1)", {});
  2086. this.set_accels_for_action("app.tool(2)", {});
  2087. this.set_accels_for_action("app.tool(3)", {});
  2088. this.set_accels_for_action("app.delete", {});
  2089. this.set_accels_for_action("app.camera-view(0)", {});
  2090. this.set_accels_for_action("app.camera-view(1)", {});
  2091. this.set_accels_for_action("app.camera-view(2)", {});
  2092. this.set_accels_for_action("app.camera-view(3)", {});
  2093. this.set_accels_for_action("app.camera-view(4)", {});
  2094. this.set_accels_for_action("app.camera-view(5)", {});
  2095. this.set_accels_for_action("app.camera-view(6)", {});
  2096. }
  2097. }
  2098. public void entry_any_focus_in(Gtk.Widget widget)
  2099. {
  2100. set_conflicting_accels(false);
  2101. }
  2102. public void entry_any_focus_out(Gtk.Widget widget)
  2103. {
  2104. set_conflicting_accels(true);
  2105. }
  2106. public void show_panel(string name, Gtk.StackTransitionType stt = Gtk.StackTransitionType.NONE)
  2107. {
  2108. _main_stack.set_visible_child_full(name, stt);
  2109. if (name == "main_vbox") {
  2110. // FIXME: save/restore last known window state
  2111. int win_w;
  2112. int win_h;
  2113. this.active_window.get_size(out win_w, out win_h);
  2114. _editor_pane.set_position(210);
  2115. _content_pane.set_position(win_h - 250);
  2116. _inspector_pane.set_position(win_h - 600);
  2117. _main_pane.set_position(win_w - 375);
  2118. menu_set_enabled(true, action_entries_file);
  2119. menu_set_enabled(true, action_entries_edit);
  2120. menu_set_enabled(true, action_entries_create);
  2121. menu_set_enabled(true, action_entries_camera);
  2122. menu_set_enabled(true, action_entries_view);
  2123. menu_set_enabled(true, action_entries_debug);
  2124. menu_set_enabled(true, action_entries_help);
  2125. } else if (name == "panel_welcome"
  2126. || name == "panel_new_project"
  2127. || name == "panel_projects_list"
  2128. ) {
  2129. menu_set_enabled(false, action_entries_file, {"new-project", "open-project", "quit"});
  2130. menu_set_enabled(false, action_entries_edit);
  2131. menu_set_enabled(false, action_entries_create);
  2132. menu_set_enabled(false, action_entries_camera);
  2133. menu_set_enabled(false, action_entries_view);
  2134. menu_set_enabled(false, action_entries_debug);
  2135. menu_set_enabled(true, action_entries_help);
  2136. }
  2137. }
  2138. public void set_placeable(string type, string name)
  2139. {
  2140. _placeable_type = type;
  2141. _placeable_name = name;
  2142. _editor.send_script(LevelEditorApi.set_placeable(type, name));
  2143. }
  2144. public void activate_last_tool_before_place()
  2145. {
  2146. if (_tool_type != ToolType.PLACE)
  2147. return;
  2148. activate_action("tool", new GLib.Variant.int32(_tool_type_prev));
  2149. }
  2150. }
  2151. // Global paths
  2152. public static GLib.File _toolchain_dir;
  2153. public static GLib.File _templates_dir;
  2154. public static GLib.File _config_dir;
  2155. public static GLib.File _logs_dir;
  2156. public static GLib.File _cache_dir;
  2157. public static GLib.File _documents_dir;
  2158. public static GLib.File _log_file;
  2159. public static GLib.File _settings_file;
  2160. public static GLib.File _user_file;
  2161. public static GLib.File _console_history_file;
  2162. public static GLib.FileStream _log_stream;
  2163. public static ConsoleView _console_view;
  2164. public static bool _console_view_valid = false;
  2165. public static string _log_prefix;
  2166. public static void log(string system, string severity, string message)
  2167. {
  2168. GLib.DateTime now = new GLib.DateTime.now_local();
  2169. int now_us = now.get_microsecond();
  2170. string now_str = now.format("%H:%M:%S");
  2171. string plain_text_line = "%s.%06d %.4s %s: %s\n".printf(now_str
  2172. , now_us
  2173. , severity.ascii_up()
  2174. , system
  2175. , message
  2176. );
  2177. if (_log_stream != null) {
  2178. _log_stream.puts(plain_text_line);
  2179. _log_stream.flush();
  2180. }
  2181. if (_console_view_valid) {
  2182. string line = "%s.%06d %s: %s\n".printf(now_str
  2183. , now_us
  2184. , system
  2185. , message
  2186. );
  2187. _console_view.log(severity, line);
  2188. }
  2189. }
  2190. public static void logi(string message)
  2191. {
  2192. log(_log_prefix, "info", message);
  2193. }
  2194. public static void logw(string message)
  2195. {
  2196. log(_log_prefix, "warning", message);
  2197. }
  2198. public static void loge(string message)
  2199. {
  2200. log(_log_prefix, "error", message);
  2201. }
  2202. public void open_directory(string directory)
  2203. {
  2204. #if CROWN_PLATFORM_LINUX
  2205. try {
  2206. GLib.AppInfo.launch_default_for_uri("file://" + directory, null);
  2207. }
  2208. catch (Error e) {
  2209. loge(e.message);
  2210. }
  2211. #else
  2212. GLib.SubprocessLauncher sl = new GLib.SubprocessLauncher(subprocess_flags());
  2213. try {
  2214. sl.spawnv({ "explorer.exe", directory, null });
  2215. }
  2216. catch (Error e) {
  2217. loge(e.message);
  2218. }
  2219. #endif
  2220. }
  2221. public static GLib.SubprocessFlags subprocess_flags()
  2222. {
  2223. GLib.SubprocessFlags flags = SubprocessFlags.NONE;
  2224. #if !CROWN_DEBUG
  2225. flags |= SubprocessFlags.STDOUT_SILENCE | SubprocessFlags.STDERR_SILENCE;
  2226. #endif
  2227. return flags;
  2228. }
  2229. public static bool is_directory_empty(string path)
  2230. {
  2231. GLib.File file = GLib.File.new_for_path(path);
  2232. try {
  2233. FileEnumerator enumerator = file.enumerate_children("standard::*"
  2234. , FileQueryInfoFlags.NOFOLLOW_SYMLINKS
  2235. );
  2236. return enumerator.next_file() == null;
  2237. }
  2238. catch (GLib.Error e) {
  2239. loge(e.message);
  2240. }
  2241. return false;
  2242. }
  2243. private void device_frame_delayed(uint delay_ms, ConsoleClient client)
  2244. {
  2245. // FIXME: find a way to time exactly when it is effective to queue a redraw.
  2246. // See: https://blogs.gnome.org/jnelson/2010/10/13/those-realize-map-widget-signals/
  2247. GLib.Timeout.add_full(GLib.Priority.DEFAULT, delay_ms, () => {
  2248. client.send(DeviceApi.frame());
  2249. return GLib.Source.REMOVE;
  2250. });
  2251. }
  2252. public static int main(string[] args)
  2253. {
  2254. // Redirect GLib logs to internal log*().
  2255. GLib.set_print_handler((msg) => { logi(msg); });
  2256. GLib.set_printerr_handler((msg) => { loge(msg); });
  2257. GLib.Log.set_writer_func((log_level, fields) => {
  2258. foreach (var field in fields) {
  2259. if (field.key == "MESSAGE") {
  2260. switch (log_level) {
  2261. case LEVEL_DEBUG:
  2262. #if CROWN_DEBUG
  2263. logi((string)field.value);
  2264. #endif
  2265. break;
  2266. case LEVEL_INFO:
  2267. case LEVEL_MESSAGE:
  2268. logi((string)field.value);
  2269. break;
  2270. case LEVEL_CRITICAL:
  2271. case LEVEL_WARNING:
  2272. logw((string)field.value);
  2273. break;
  2274. case LEVEL_ERROR:
  2275. loge((string)field.value);
  2276. break;
  2277. default:
  2278. logw((string)field.value);
  2279. break;
  2280. }
  2281. return GLib.LogWriterOutput.HANDLED;
  2282. }
  2283. }
  2284. return GLib.LogWriterOutput.UNHANDLED;
  2285. });
  2286. // Global paths
  2287. _config_dir = GLib.File.new_for_path(GLib.Path.build_filename(GLib.Environment.get_user_config_dir(), "crown"));
  2288. try {
  2289. _config_dir.make_directory();
  2290. } catch (Error e) {
  2291. /* Nobody cares */
  2292. }
  2293. _logs_dir = GLib.File.new_for_path(GLib.Path.build_filename(_config_dir.get_path(), "logs"));
  2294. try {
  2295. _logs_dir.make_directory();
  2296. } catch (Error e) {
  2297. /* Nobody cares */
  2298. }
  2299. _documents_dir = GLib.File.new_for_path(GLib.Environment.get_user_special_dir(GLib.UserDirectory.DOCUMENTS));
  2300. _cache_dir = GLib.File.new_for_path(GLib.Path.build_filename(GLib.Environment.get_user_cache_dir(), "crown"));
  2301. try {
  2302. _cache_dir.make_directory();
  2303. } catch (Error e) {
  2304. /* Nobody cares */
  2305. }
  2306. _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"));
  2307. _log_stream = GLib.FileStream.open(_log_file.get_path(), "a");
  2308. // If args does not contain --child, spawn the launcher.
  2309. int ii;
  2310. for (ii = 0; ii < args.length; ++ii) {
  2311. if (args[ii] == "--child")
  2312. break;
  2313. }
  2314. if (ii == args.length) {
  2315. _log_prefix = "launcher";
  2316. return launcher_main(args);
  2317. }
  2318. _log_prefix = "editor";
  2319. // Remove --child from args for backward compatibility.
  2320. if (args.length > 1)
  2321. args = args[0 : args.length - 1];
  2322. _settings_file = GLib.File.new_for_path(GLib.Path.build_filename(_config_dir.get_path(), "settings.sjson"));
  2323. _user_file = GLib.File.new_for_path(GLib.Path.build_filename(_config_dir.get_path(), "user.sjson"));
  2324. _console_history_file = GLib.File.new_for_path(GLib.Path.build_filename(_cache_dir.get_path(), "console_history.txt"));
  2325. // Connect to SubprocessLauncher service.
  2326. SubprocessLauncher subprocess_launcher;
  2327. try {
  2328. subprocess_launcher = GLib.Bus.get_proxy_sync(GLib.BusType.SESSION
  2329. , "org.crownengine.SubprocessLauncher"
  2330. , "/org/crownengine/subprocess_launcher"
  2331. );
  2332. } catch (IOError e) {
  2333. loge(e.message);
  2334. return 1;
  2335. }
  2336. // Find toolchain path, more desirable paths come first.
  2337. ii = 0;
  2338. string toolchain_paths[] =
  2339. {
  2340. ".",
  2341. "../..",
  2342. "../../../samples"
  2343. };
  2344. for (ii = 0; ii < toolchain_paths.length; ++ii) {
  2345. string path = Path.build_filename(toolchain_paths[ii], "core");
  2346. if (GLib.FileUtils.test(path, FileTest.EXISTS) && GLib.FileUtils.test(path, FileTest.IS_DIR)) {
  2347. _toolchain_dir = File.new_for_path(path).get_parent();
  2348. break;
  2349. }
  2350. }
  2351. if (ii == toolchain_paths.length) {
  2352. loge("Unable to find the toolchain directory");
  2353. return 1;
  2354. }
  2355. // Find templates path, more desirable paths come first.
  2356. string templates_path[] =
  2357. {
  2358. ".",
  2359. "../..",
  2360. "../../.."
  2361. };
  2362. for (ii = 0; ii < templates_path.length; ++ii) {
  2363. string path = Path.build_filename(templates_path[ii], "samples");
  2364. if (GLib.FileUtils.test(path, FileTest.EXISTS) && GLib.FileUtils.test(path, FileTest.IS_DIR)) {
  2365. _templates_dir = File.new_for_path(path);
  2366. break;
  2367. }
  2368. }
  2369. if (ii == templates_path.length) {
  2370. loge("Unable to find the templates directory");
  2371. return 1;
  2372. }
  2373. #if CROWN_PLATFORM_LINUX
  2374. Gdk.set_allowed_backends("x11");
  2375. #endif
  2376. LevelEditorApplication app = new LevelEditorApplication(subprocess_launcher);
  2377. return app.run(args);
  2378. }
  2379. } /* namespace Crown */