2
0

console_view.vala 17 KB

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