console_view.vala 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  1. /*
  2. * Copyright (c) 2012-2024 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. menu.show_all();
  249. menu.popup_at_pointer(ev);
  250. return Gdk.EVENT_STOP;
  251. }
  252. }
  253. }
  254. }
  255. return Gdk.EVENT_PROPAGATE;
  256. }
  257. private bool on_button_released(Gdk.EventButton ev)
  258. {
  259. if (ev.button == Gdk.BUTTON_PRIMARY) {
  260. // Do not handle click if some text is selected.
  261. Gtk.TextIter dummy_iter;
  262. if (_text_view.buffer.get_selection_bounds(out dummy_iter, out dummy_iter))
  263. return Gdk.EVENT_PROPAGATE;
  264. int buffer_x;
  265. int buffer_y;
  266. _text_view.window_to_buffer_coords(Gtk.TextWindowType.WIDGET
  267. , (int)ev.x
  268. , (int)ev.y
  269. , out buffer_x
  270. , out buffer_y
  271. );
  272. Gtk.TextIter iter;
  273. if (_text_view.get_iter_at_location(out iter, buffer_x, buffer_y)) {
  274. // Check whether the text under the mouse pointer has a link tag.
  275. GLib.SList<unowned TextTag> tags = iter.get_tags();
  276. foreach (var item in tags) {
  277. string item_data;
  278. if ((item_data = item.get_data<string>("uri")) != null) {
  279. if (item_data.has_prefix("resource_id:")) {
  280. GLib.Application.get_default().activate_action("open-resource", new GLib.Variant.string(item_data[12 : item_data.length]));
  281. } else if (item_data.has_prefix("file:")) {
  282. open_directory(item_data[5 : item_data.length]);
  283. } else {
  284. try {
  285. GLib.AppInfo.launch_default_for_uri(item_data, null);
  286. } catch (GLib.Error e) {
  287. loge(e.message);
  288. }
  289. }
  290. }
  291. }
  292. }
  293. }
  294. return Gdk.EVENT_PROPAGATE;
  295. }
  296. private bool on_motion_notify(Gdk.EventMotion ev)
  297. {
  298. bool hovering = false;
  299. int buffer_x;
  300. int buffer_y;
  301. _text_view.window_to_buffer_coords(TextWindowType.WIDGET
  302. , (int)ev.x
  303. , (int)ev.y
  304. , out buffer_x
  305. , out buffer_y
  306. );
  307. Gtk.TextIter iter;
  308. if (_text_view.get_iter_at_location(out iter, buffer_x, buffer_y)) {
  309. // Check whether the text under the mouse pointer has a link tag.
  310. GLib.SList<unowned TextTag> tags = iter.get_tags();
  311. foreach (var item in tags) {
  312. if (item.get_data<string>("uri") != null)
  313. hovering = true;
  314. }
  315. }
  316. if (_cursor_is_hovering_link != hovering) {
  317. _cursor_is_hovering_link = hovering;
  318. if (_cursor_is_hovering_link)
  319. _text_view.get_window(Gtk.TextWindowType.TEXT).set_cursor(_pointer_cursor);
  320. else
  321. _text_view.get_window(Gtk.TextWindowType.TEXT).set_cursor(_text_cursor);
  322. }
  323. return Gdk.EVENT_PROPAGATE;
  324. }
  325. public void log(string time, string severity, string message)
  326. {
  327. Gtk.TextBuffer buffer = _text_view.buffer;
  328. // Limit number of lines recorded.
  329. int max_lines = (int)_preferences_dialog._console_max_lines.value;
  330. if (buffer.get_line_count() - 1 >= max_lines) {
  331. Gtk.TextIter start_of_first_line;
  332. buffer.get_iter_at_line(out start_of_first_line, 0);
  333. Gtk.TextIter end_of_first_line = start_of_first_line;
  334. start_of_first_line.forward_line();
  335. buffer.delete(ref start_of_first_line, ref end_of_first_line);
  336. }
  337. Gtk.TextIter end_iter;
  338. buffer.get_end_iter(out end_iter);
  339. // Avoid showing duplicated messages. Insert a little counter
  340. // at the end of each line occurring twice or more.
  341. if (_last_message.text == message) {
  342. // Replace the current time with the latest one.
  343. Gtk.TextIter time_start;
  344. Gtk.TextIter time_end;
  345. buffer.get_iter_at_mark(out time_start, _time_mark);
  346. time_end = time_start;
  347. time_end.forward_chars(time.length);
  348. buffer.delete(ref time_start, ref time_end);
  349. buffer.get_iter_at_mark(out time_start, _time_mark);
  350. buffer.insert_with_tags(ref time_start
  351. , time
  352. , time.length
  353. , buffer.tag_table.lookup("time")
  354. , null
  355. );
  356. if (_last_message.num_repetitions == 0) {
  357. // Create a new anchor at the end of the line.
  358. buffer.get_end_iter(out end_iter);
  359. end_iter.backward_char();
  360. _last_message.anchor = buffer.create_child_anchor(end_iter);
  361. _text_view.add_child_at_anchor(new CounterLabel(), _last_message.anchor);
  362. scroll_to_bottom();
  363. }
  364. ++_last_message.num_repetitions;
  365. const int MAX_REPETITIONS = 1000;
  366. if (_last_message.num_repetitions < MAX_REPETITIONS) {
  367. List<unowned Widget> widgets = _last_message.anchor.get_widgets();
  368. unowned var label_widget = widgets.first();
  369. var cl = (CounterLabel)label_widget.data;
  370. if (_last_message.num_repetitions == MAX_REPETITIONS - 1)
  371. cl.set_markup("%d+".printf(_last_message.num_repetitions));
  372. else
  373. cl.set_markup("%d".printf(_last_message.num_repetitions + 1));
  374. }
  375. return;
  376. } else {
  377. _last_message.text = message;
  378. _last_message.num_repetitions = 0;
  379. }
  380. buffer.move_mark(_time_mark, end_iter);
  381. buffer.insert_with_tags(ref end_iter
  382. , time
  383. , time.length
  384. , buffer.tag_table.lookup("time")
  385. , null
  386. );
  387. // Replace all IDs with corresponding human-readable names.
  388. int id_index = 0;
  389. do {
  390. // Search for occurrences of the ID string.
  391. int id_index_orig = id_index;
  392. if ((id_index = message.index_of("#ID(", id_index_orig)) != -1) {
  393. // If an occurrenct is found, insert the preceding text as usual.
  394. string line_chunk = message.substring(id_index_orig, id_index - id_index_orig);
  395. buffer.insert_with_tags(ref end_iter
  396. , line_chunk
  397. , line_chunk.length
  398. , buffer.tag_table.lookup(severity)
  399. , null
  400. );
  401. // Try to extract the resource ID from #ID() argument.
  402. int id_closing_parentheses = message.index_of(")", id_index + 4);
  403. if (id_closing_parentheses == -1) {
  404. // Syntax error, insert the whole line as-is.
  405. buffer.insert_with_tags(ref end_iter
  406. , message.substring(id_index)
  407. , -1
  408. , buffer.tag_table.lookup(severity)
  409. , null
  410. );
  411. break;
  412. }
  413. // Convert the resource ID to human-readable resource name.
  414. string resource_name;
  415. string resource_id = message.substring(id_index + 4, id_closing_parentheses - (id_index + 4));
  416. _project.resource_id_to_name(out resource_name, resource_id);
  417. // Create a tag for link.
  418. Gtk.TextTag link = null;
  419. link = buffer.create_tag(null, "underline", Pango.Underline.SINGLE, null);
  420. link.set_data("uri", "resource_id:%s".printf(resource_name));
  421. buffer.insert_with_tags(ref end_iter
  422. , resource_name
  423. , -1
  424. , buffer.tag_table.lookup(severity)
  425. , link
  426. , null
  427. );
  428. id_index += 4 + resource_id.length;
  429. continue;
  430. } else if ((id_index = message.index_of("#FILE(", id_index_orig)) != -1) {
  431. // If an occurrenct is found, insert the preceding text as usual.
  432. string line_chunk = message.substring(id_index_orig, id_index - id_index_orig);
  433. buffer.insert_with_tags(ref end_iter
  434. , line_chunk
  435. , line_chunk.length
  436. , buffer.tag_table.lookup(severity)
  437. , null
  438. );
  439. // Try to extract the path from #FILE() argument.
  440. int id_closing_parentheses = message.index_of(")", id_index + 6);
  441. if (id_closing_parentheses == -1) {
  442. // Syntax error, insert the whole line as-is.
  443. buffer.insert_with_tags(ref end_iter
  444. , message.substring(id_index)
  445. , -1
  446. , buffer.tag_table.lookup(severity)
  447. , null
  448. );
  449. break;
  450. }
  451. string file_path = message.substring(id_index + 6, id_closing_parentheses - (id_index + 6));
  452. // Create a tag for link.
  453. Gtk.TextTag link = null;
  454. link = buffer.create_tag(null, "underline", Pango.Underline.SINGLE, null);
  455. link.set_data("uri", "file:%s".printf(file_path));
  456. buffer.insert_with_tags(ref end_iter
  457. , file_path
  458. , -1
  459. , buffer.tag_table.lookup(severity)
  460. , link
  461. , null
  462. );
  463. id_index += 6 + file_path.length;
  464. continue;
  465. } else {
  466. buffer.insert_with_tags(ref end_iter
  467. , message.substring(id_index_orig)
  468. , -1
  469. , buffer.tag_table.lookup(severity)
  470. , null
  471. );
  472. }
  473. } while (id_index++ >= 0);
  474. scroll_to_bottom();
  475. }
  476. private void scroll_to_bottom()
  477. {
  478. // Line height is computed in an idle handler, wait a bit before scrolling to bottom.
  479. // See: https://valadoc.org/gtk+-3.0/Gtk.TextView.scroll_to_iter.html
  480. GLib.Idle.add(() => {
  481. Gtk.TextIter end_iter;
  482. _text_view.buffer.get_end_iter(out end_iter);
  483. // Scroll to bottom.
  484. // See: gtk3-demo "Automatic Scrolling".
  485. end_iter.set_line_offset(0);
  486. _text_view.buffer.move_mark(_scroll_mark, end_iter);
  487. _text_view.scroll_mark_onscreen(_scroll_mark);
  488. return GLib.Source.REMOVE;
  489. });
  490. }
  491. private void update_style()
  492. {
  493. Gtk.TextBuffer tb = _text_view.buffer;
  494. Gtk.TextTag tag_warning = tb.tag_table.lookup("warning");
  495. Gtk.TextTag tag_error = tb.tag_table.lookup("error");
  496. Gtk.TextTag tag_info = tb.tag_table.lookup("info");
  497. Gtk.TextTag tag_time = tb.tag_table.lookup("time");
  498. Gdk.RGBA col;
  499. get_style_context().lookup_color("warning_color", out col);
  500. tag_warning.foreground_rgba = col;
  501. get_style_context().lookup_color("error_color", out col);
  502. tag_error.foreground_rgba = col;
  503. get_style_context().lookup_color("theme_fg_color", out col);
  504. tag_info.foreground_rgba = col;
  505. get_style_context().lookup_color("success_color", out col);
  506. tag_time.foreground_rgba = col;
  507. }
  508. }
  509. } /* namespace Crown */