console_view.vala 18 KB

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