console_view.vala 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. /*
  2. * Copyright (c) 2012-2025 Daniele Bartolini et al.
  3. * SPDX-License-Identifier: GPL-3.0-or-later
  4. */
  5. namespace Crown
  6. {
  7. public class CounterLabel : Gtk.Label
  8. {
  9. public CounterLabel()
  10. {
  11. this.get_style_context().add_class("counter-label");
  12. this.set_visible(true);
  13. }
  14. protected override void get_preferred_height(out int minimum_height, out int natural_height)
  15. {
  16. // FIXME: Find a proper way to position/size labels inside Gtk.TextView.
  17. // Make Gtk.Label think it only needs 16px vertical to show its text.
  18. minimum_height = 1;
  19. natural_height = 16;
  20. }
  21. }
  22. public class EntryHistory
  23. {
  24. public uint _capacity;
  25. public uint _size;
  26. public uint _index;
  27. public string[] _data;
  28. // Creates a new history with room for capacity records.
  29. public EntryHistory(uint capacity)
  30. {
  31. _capacity = capacity;
  32. _size = 0;
  33. _index = 0;
  34. _data = new string[capacity];
  35. }
  36. // Push a new string into the history.
  37. public void push(string text)
  38. {
  39. // Add command to history
  40. _data[_index] = text;
  41. _index = (_index + 1) % _capacity;
  42. if (_size < _capacity)
  43. ++_size;
  44. }
  45. public void clear()
  46. {
  47. _size = 0;
  48. _index = 0;
  49. }
  50. // Returns the element at @a distance slots from the current index.
  51. // Distance must be in the [1; _size] range.
  52. public string element(uint distance)
  53. {
  54. if (distance < 1 || distance > _size)
  55. return "ERROR";
  56. if (_index >= distance)
  57. return _data[_index - distance];
  58. else
  59. return _data[_capacity - (distance - _index)];
  60. }
  61. public void save(string path)
  62. {
  63. FileStream fs = FileStream.open(path, "wb");
  64. if (fs == null)
  65. return;
  66. uint first_entry = _index + (_capacity - _size);
  67. for (uint ii = 0; ii < _size; ++ii)
  68. fs.printf("%s\n", _data[(first_entry + ii) % _capacity]);
  69. }
  70. public void load(string path)
  71. {
  72. FileStream fs = FileStream.open(path, "rb");
  73. if (fs == null)
  74. return;
  75. string? line = null;
  76. while ((line = fs.read_line()) != null)
  77. push(line);
  78. }
  79. }
  80. public class ConsoleView : Gtk.Box
  81. {
  82. public struct LastMsg
  83. {
  84. string text;
  85. int num_repetitions;
  86. Gtk.TextChildAnchor anchor;
  87. }
  88. // Data
  89. public EntryHistory _entry_history;
  90. public uint _distance;
  91. public Project _project;
  92. public PreferencesDialog _preferences_dialog;
  93. public LastMsg _last_message;
  94. // Widgets
  95. public Gdk.Cursor _text_cursor;
  96. public Gdk.Cursor _pointer_cursor;
  97. public bool _cursor_is_hovering_link;
  98. public Gtk.TextView _text_view;
  99. public Gtk.GestureMultiPress _text_view_gesture_click;
  100. public Gtk.EventControllerMotion _text_view_controller_motion;
  101. public Gtk.Overlay _text_view_overlay;
  102. public Gtk.ScrolledWindow _scrolled_window;
  103. public InputString _entry;
  104. public Gtk.EventControllerKey _entry_controller_key;
  105. public Gtk.Box _entry_hbox;
  106. public Gtk.TextMark _scroll_mark;
  107. public Gtk.TextMark _time_mark;
  108. public ConsoleView(Project project, Gtk.ComboBoxText combo, PreferencesDialog preferences_dialog)
  109. {
  110. Object(orientation: Gtk.Orientation.VERTICAL, spacing: 0);
  111. // Data
  112. _entry_history = new EntryHistory(256);
  113. _distance = 0;
  114. _project = project;
  115. _preferences_dialog = preferences_dialog;
  116. // Widgets
  117. _text_cursor = new Gdk.Cursor.from_name(this.get_display(), "text");
  118. _pointer_cursor = new Gdk.Cursor.from_name(this.get_display(), "pointer");
  119. _cursor_is_hovering_link = false;
  120. _text_view = new Gtk.TextView();
  121. _text_view.editable = false;
  122. _text_view.can_focus = true;
  123. Gtk.Button clear_button = new Gtk.Button.from_icon_name("edit-clear");
  124. clear_button.margin_top = 8;
  125. clear_button.margin_end = 16;
  126. clear_button.valign = Gtk.Align.START;
  127. clear_button.halign = Gtk.Align.END;
  128. clear_button.clicked.connect(() => {
  129. reset();
  130. });
  131. // Create tags for color-formatted text.
  132. Gtk.TextBuffer tb = _text_view.buffer;
  133. tb.tag_table.add(new Gtk.TextTag("info"));
  134. tb.tag_table.add(new Gtk.TextTag("warning"));
  135. tb.tag_table.add(new Gtk.TextTag("error"));
  136. tb.tag_table.add(new Gtk.TextTag("time"));
  137. this.style_updated.connect(update_style);
  138. update_style();
  139. Gtk.TextIter end_iter;
  140. tb.get_end_iter(out end_iter);
  141. _scroll_mark = tb.create_mark("scroll", end_iter, true);
  142. _time_mark = tb.create_mark("time", end_iter, true);
  143. _scrolled_window = new Gtk.ScrolledWindow(null, null);
  144. _scrolled_window.vscrollbar_policy = Gtk.PolicyType.ALWAYS;
  145. _scrolled_window.add(_text_view);
  146. _text_view_overlay = new Gtk.Overlay();
  147. _text_view_overlay.add(_scrolled_window);
  148. _text_view_overlay.add_overlay(clear_button);
  149. _entry = new InputString();
  150. _entry.activate.connect(on_entry_activated);
  151. _entry_controller_key = new Gtk.EventControllerKey(_entry);
  152. _entry_controller_key.key_pressed.connect(on_entry_key_pressed);
  153. _entry_hbox = new Gtk.Box(Gtk.Orientation.HORIZONTAL, 0);
  154. _entry_hbox.pack_start(combo, false, false);
  155. _entry_hbox.pack_start(_entry, true, true);
  156. Gtk.Box hbox = new Gtk.Box(Gtk.Orientation.HORIZONTAL, 0);
  157. hbox.pack_start(_entry_hbox, true, true, 0);
  158. this.pack_start(_text_view_overlay, true, true, 0);
  159. this.pack_start(hbox, false, true, 0);
  160. this.destroy.connect(on_destroy);
  161. _text_view_gesture_click = new Gtk.GestureMultiPress(_text_view);
  162. _text_view_gesture_click.set_button(0);
  163. _text_view_gesture_click.set_propagation_phase(Gtk.PropagationPhase.CAPTURE);
  164. _text_view_gesture_click.pressed.connect(on_button_pressed);
  165. _text_view_gesture_click.released.connect(on_button_released);
  166. _text_view_controller_motion = new Gtk.EventControllerMotion(_text_view);
  167. _text_view_controller_motion.motion.connect(on_motion_notify);
  168. this.get_style_context().add_class("console-view");
  169. _console_view_valid = true;
  170. }
  171. public void reset()
  172. {
  173. _text_view.buffer.set_text("");
  174. _last_message = LastMsg()
  175. {
  176. text = "",
  177. num_repetitions = 0,
  178. anchor = null
  179. };
  180. }
  181. private void on_entry_activated()
  182. {
  183. string text = _entry.text;
  184. text = text.strip();
  185. if (text.length > 0) {
  186. _entry_history.push(text);
  187. _distance = 0;
  188. var app = (LevelEditorApplication)GLib.Application.get_default();
  189. RuntimeInstance? runtime = app.current_selected_runtime();
  190. if (text[0] == ':') {
  191. string[] args = text[1 : text.length].split(" ");
  192. if (args.length > 0) {
  193. if (runtime != null) {
  194. runtime.send(DeviceApi.command(args));
  195. runtime.send(DeviceApi.frame());
  196. }
  197. }
  198. } else {
  199. if (runtime != null) {
  200. logi("> %s".printf(text));
  201. runtime.send_script(text);
  202. runtime.send(DeviceApi.frame());
  203. }
  204. }
  205. }
  206. _entry.text = "";
  207. }
  208. private bool on_entry_key_pressed(uint keyval, uint keycode, Gdk.ModifierType state)
  209. {
  210. if (keyval == Gdk.Key.Down) {
  211. if (_distance > 1) {
  212. --_distance;
  213. _entry.text = _entry_history.element(_distance);
  214. } else {
  215. _entry.text = "";
  216. }
  217. _entry.set_position(_entry.text.length);
  218. return Gdk.EVENT_STOP;
  219. } else if (keyval == Gdk.Key.Up) {
  220. if (_distance < _entry_history._size) {
  221. ++_distance;
  222. _entry.text = _entry_history.element(_distance);
  223. }
  224. _entry.set_position(_entry.text.length);
  225. return Gdk.EVENT_STOP;
  226. }
  227. return Gdk.EVENT_PROPAGATE;
  228. }
  229. private void on_destroy()
  230. {
  231. _console_view_valid = false;
  232. }
  233. private void on_button_pressed(int n_press, double x, double y)
  234. {
  235. uint button = _text_view_gesture_click.get_current_button();
  236. if (button == Gdk.BUTTON_SECONDARY) {
  237. // Do not handle click if some text is selected.
  238. Gtk.TextIter dummy_iter;
  239. if (_text_view.buffer.get_selection_bounds(out dummy_iter, out dummy_iter))
  240. return;
  241. int buffer_x;
  242. int buffer_y;
  243. _text_view.window_to_buffer_coords(Gtk.TextWindowType.WIDGET
  244. , (int)x
  245. , (int)y
  246. , out buffer_x
  247. , out buffer_y
  248. );
  249. Gtk.TextIter iter;
  250. if (_text_view.get_iter_at_location(out iter, buffer_x, buffer_y)) {
  251. // Check whether the text under the mouse pointer has a link tag.
  252. GLib.SList<unowned Gtk.TextTag> tags = iter.get_tags();
  253. foreach (var item in tags) {
  254. string item_data;
  255. if ((item_data = item.get_data<string>("uri")) == null)
  256. continue;
  257. if (item_data.has_prefix("resource_id:")) {
  258. GLib.Menu menu_model = new GLib.Menu();
  259. GLib.MenuItem mi;
  260. string resource_path = item_data[12 : item_data.length];
  261. string? resource_type = ResourceId.type(resource_path);
  262. string? resource_name = ResourceId.name(resource_path);
  263. if (resource_type != null && resource_name != null) {
  264. mi = new GLib.MenuItem("Reveal in Project Browser", null);
  265. mi.set_action_and_target_value("app.reveal-resource", new GLib.Variant.tuple({ resource_type, resource_name }));
  266. menu_model.append_item(mi);
  267. }
  268. mi = new GLib.MenuItem("Open Containing Folder...", null);
  269. mi.set_action_and_target_value("app.open-containing", new GLib.Variant.string(resource_path));
  270. menu_model.append_item(mi);
  271. Gtk.Popover menu = new Gtk.Popover.from_model(null, menu_model);
  272. menu.set_relative_to(_text_view);
  273. menu.set_pointing_to({ (int)x, (int)y, 1, 1 });
  274. menu.set_position(Gtk.PositionType.BOTTOM);
  275. menu.popup();
  276. _text_view_gesture_click.set_state(Gtk.EventSequenceState.CLAIMED);
  277. return;
  278. }
  279. }
  280. }
  281. }
  282. }
  283. private void on_button_released(int n_press, double x, double y)
  284. {
  285. uint button = _text_view_gesture_click.get_current_button();
  286. if (button == Gdk.BUTTON_PRIMARY) {
  287. // Do not handle click if some text is selected.
  288. Gtk.TextIter dummy_iter;
  289. if (_text_view.buffer.get_selection_bounds(out dummy_iter, out dummy_iter))
  290. return;
  291. int buffer_x;
  292. int buffer_y;
  293. _text_view.window_to_buffer_coords(Gtk.TextWindowType.WIDGET
  294. , (int)x
  295. , (int)y
  296. , out buffer_x
  297. , out buffer_y
  298. );
  299. Gtk.TextIter iter;
  300. if (_text_view.get_iter_at_location(out iter, buffer_x, buffer_y)) {
  301. // Check whether the text under the mouse pointer has a link tag.
  302. GLib.SList<unowned Gtk.TextTag> tags = iter.get_tags();
  303. foreach (var item in tags) {
  304. string item_data;
  305. if ((item_data = item.get_data<string>("uri")) != null) {
  306. if (item_data.has_prefix("resource_id:")) {
  307. GLib.Application.get_default().activate_action("open-resource", new GLib.Variant.string(item_data[12 : item_data.length]));
  308. } else if (item_data.has_prefix("file:")) {
  309. open_directory(item_data[5 : item_data.length]);
  310. } else {
  311. try {
  312. GLib.AppInfo.launch_default_for_uri(item_data, null);
  313. } catch (GLib.Error e) {
  314. loge(e.message);
  315. }
  316. }
  317. }
  318. }
  319. }
  320. }
  321. }
  322. private void on_motion_notify(double x, double y)
  323. {
  324. bool hovering = false;
  325. int buffer_x;
  326. int buffer_y;
  327. _text_view.window_to_buffer_coords(Gtk.TextWindowType.WIDGET
  328. , (int)x
  329. , (int)y
  330. , out buffer_x
  331. , out buffer_y
  332. );
  333. Gtk.TextIter iter;
  334. if (_text_view.get_iter_at_location(out iter, buffer_x, buffer_y)) {
  335. // Check whether the text under the mouse pointer has a link tag.
  336. GLib.SList<unowned Gtk.TextTag> tags = iter.get_tags();
  337. foreach (var item in tags) {
  338. if (item.get_data<string>("uri") != null)
  339. hovering = true;
  340. }
  341. }
  342. if (_cursor_is_hovering_link != hovering) {
  343. _cursor_is_hovering_link = hovering;
  344. if (_cursor_is_hovering_link)
  345. _text_view.get_window(Gtk.TextWindowType.TEXT).set_cursor(_pointer_cursor);
  346. else
  347. _text_view.get_window(Gtk.TextWindowType.TEXT).set_cursor(_text_cursor);
  348. }
  349. }
  350. public void log(string time, string severity, string message)
  351. {
  352. Gtk.TextBuffer buffer = _text_view.buffer;
  353. // Limit number of lines recorded.
  354. int max_lines = (int)_preferences_dialog._console_max_lines.value;
  355. if (buffer.get_line_count() - 1 >= max_lines) {
  356. Gtk.TextIter start_of_first_line;
  357. buffer.get_iter_at_line(out start_of_first_line, 0);
  358. Gtk.TextIter end_of_first_line = start_of_first_line;
  359. start_of_first_line.forward_line();
  360. buffer.delete(ref start_of_first_line, ref end_of_first_line);
  361. }
  362. Gtk.TextIter end_iter;
  363. buffer.get_end_iter(out end_iter);
  364. // Avoid showing duplicated messages. Insert a little counter
  365. // at the end of each line occurring twice or more.
  366. if (_last_message.text == message) {
  367. // Replace the current time with the latest one.
  368. Gtk.TextIter time_start;
  369. Gtk.TextIter time_end;
  370. buffer.get_iter_at_mark(out time_start, _time_mark);
  371. time_end = time_start;
  372. time_end.forward_chars(time.length);
  373. buffer.delete(ref time_start, ref time_end);
  374. buffer.get_iter_at_mark(out time_start, _time_mark);
  375. buffer.insert_with_tags(ref time_start
  376. , time
  377. , time.length
  378. , buffer.tag_table.lookup("time")
  379. , null
  380. );
  381. if (_last_message.num_repetitions == 0) {
  382. // Create a new anchor at the end of the line.
  383. buffer.get_end_iter(out end_iter);
  384. end_iter.backward_char();
  385. _last_message.anchor = buffer.create_child_anchor(end_iter);
  386. _text_view.add_child_at_anchor(new CounterLabel(), _last_message.anchor);
  387. scroll_to_bottom();
  388. }
  389. ++_last_message.num_repetitions;
  390. const int MAX_REPETITIONS = 1000;
  391. if (_last_message.num_repetitions < MAX_REPETITIONS) {
  392. List<unowned Gtk.Widget> widgets = _last_message.anchor.get_widgets();
  393. unowned var label_widget = widgets.first();
  394. var cl = (CounterLabel)label_widget.data;
  395. if (_last_message.num_repetitions == MAX_REPETITIONS - 1)
  396. cl.set_markup("%d+".printf(_last_message.num_repetitions));
  397. else
  398. cl.set_markup("%d".printf(_last_message.num_repetitions + 1));
  399. }
  400. return;
  401. } else {
  402. _last_message.text = message;
  403. _last_message.num_repetitions = 0;
  404. }
  405. buffer.move_mark(_time_mark, end_iter);
  406. buffer.insert_with_tags(ref end_iter
  407. , time
  408. , time.length
  409. , buffer.tag_table.lookup("time")
  410. , null
  411. );
  412. // Replace all IDs with corresponding human-readable names.
  413. int id_index = 0;
  414. do {
  415. // Search for occurrences of the ID string.
  416. int id_index_orig = id_index;
  417. if ((id_index = message.index_of("#ID(", id_index_orig)) != -1) {
  418. // If an occurrenct is found, insert the preceding text as usual.
  419. string line_chunk = message.substring(id_index_orig, id_index - id_index_orig);
  420. buffer.insert_with_tags(ref end_iter
  421. , line_chunk
  422. , line_chunk.length
  423. , buffer.tag_table.lookup(severity)
  424. , null
  425. );
  426. // Try to extract the resource ID from #ID() argument.
  427. int id_closing_parentheses = message.index_of(")", id_index + 4);
  428. if (id_closing_parentheses == -1) {
  429. // Syntax error, insert the whole line as-is.
  430. buffer.insert_with_tags(ref end_iter
  431. , message.substring(id_index)
  432. , -1
  433. , buffer.tag_table.lookup(severity)
  434. , null
  435. );
  436. break;
  437. }
  438. // Convert the resource ID to human-readable resource name.
  439. string resource_name;
  440. string resource_id = message.substring(id_index + 4, id_closing_parentheses - (id_index + 4));
  441. _project.resource_id_to_name(out resource_name, resource_id);
  442. // Create a tag for link.
  443. Gtk.TextTag link = null;
  444. link = buffer.create_tag(null, "underline", Pango.Underline.SINGLE, null);
  445. link.set_data("uri", "resource_id:%s".printf(resource_name));
  446. buffer.insert_with_tags(ref end_iter
  447. , resource_name
  448. , -1
  449. , buffer.tag_table.lookup(severity)
  450. , link
  451. , null
  452. );
  453. id_index += 4 + resource_id.length;
  454. continue;
  455. } else if ((id_index = message.index_of("#FILE(", id_index_orig)) != -1) {
  456. // If an occurrenct is found, insert the preceding text as usual.
  457. string line_chunk = message.substring(id_index_orig, id_index - id_index_orig);
  458. buffer.insert_with_tags(ref end_iter
  459. , line_chunk
  460. , line_chunk.length
  461. , buffer.tag_table.lookup(severity)
  462. , null
  463. );
  464. // Try to extract the path from #FILE() argument.
  465. int id_closing_parentheses = message.index_of(")", id_index + 6);
  466. if (id_closing_parentheses == -1) {
  467. // Syntax error, insert the whole line as-is.
  468. buffer.insert_with_tags(ref end_iter
  469. , message.substring(id_index)
  470. , -1
  471. , buffer.tag_table.lookup(severity)
  472. , null
  473. );
  474. break;
  475. }
  476. string file_path = message.substring(id_index + 6, id_closing_parentheses - (id_index + 6));
  477. // Create a tag for link.
  478. Gtk.TextTag link = null;
  479. link = buffer.create_tag(null, "underline", Pango.Underline.SINGLE, null);
  480. link.set_data("uri", "file:%s".printf(file_path));
  481. buffer.insert_with_tags(ref end_iter
  482. , file_path
  483. , -1
  484. , buffer.tag_table.lookup(severity)
  485. , link
  486. , null
  487. );
  488. id_index += 6 + file_path.length;
  489. continue;
  490. } else {
  491. buffer.insert_with_tags(ref end_iter
  492. , message.substring(id_index_orig)
  493. , -1
  494. , buffer.tag_table.lookup(severity)
  495. , null
  496. );
  497. }
  498. } while (id_index++ >= 0);
  499. scroll_to_bottom();
  500. }
  501. private void scroll_to_bottom()
  502. {
  503. // Line height is computed in an idle handler, wait a bit before scrolling to bottom.
  504. // See: https://valadoc.org/gtk+-3.0/Gtk.TextView.scroll_to_iter.html
  505. GLib.Idle.add(() => {
  506. Gtk.TextIter end_iter;
  507. _text_view.buffer.get_end_iter(out end_iter);
  508. // Scroll to bottom.
  509. // See: gtk3-demo "Automatic Scrolling".
  510. end_iter.set_line_offset(0);
  511. _text_view.buffer.move_mark(_scroll_mark, end_iter);
  512. _text_view.scroll_mark_onscreen(_scroll_mark);
  513. return GLib.Source.REMOVE;
  514. });
  515. }
  516. private void update_style()
  517. {
  518. Gtk.TextBuffer tb = _text_view.buffer;
  519. Gtk.TextTag tag_warning = tb.tag_table.lookup("warning");
  520. Gtk.TextTag tag_error = tb.tag_table.lookup("error");
  521. Gtk.TextTag tag_info = tb.tag_table.lookup("info");
  522. Gtk.TextTag tag_time = tb.tag_table.lookup("time");
  523. Gdk.RGBA col;
  524. get_style_context().lookup_color("warning_color", out col);
  525. tag_warning.foreground_rgba = col;
  526. get_style_context().lookup_color("error_color", out col);
  527. tag_error.foreground_rgba = col;
  528. get_style_context().lookup_color("theme_fg_color", out col);
  529. tag_info.foreground_rgba = col;
  530. get_style_context().lookup_color("success_color", out col);
  531. tag_time.foreground_rgba = col;
  532. }
  533. }
  534. } /* namespace Crown */