2
0

console_view.vala 18 KB

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