console_view.vala 17 KB

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