console_view.vala 18 KB

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