console_view.vala 18 KB

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