1/**************************************************************************/
2/* editor_log.cpp */
3/**************************************************************************/
4/* This file is part of: */
5/* GODOT ENGINE */
6/* https://godotengine.org */
7/**************************************************************************/
8/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
10/* */
11/* Permission is hereby granted, free of charge, to any person obtaining */
12/* a copy of this software and associated documentation files (the */
13/* "Software"), to deal in the Software without restriction, including */
14/* without limitation the rights to use, copy, modify, merge, publish, */
15/* distribute, sublicense, and/or sell copies of the Software, and to */
16/* permit persons to whom the Software is furnished to do so, subject to */
17/* the following conditions: */
18/* */
19/* The above copyright notice and this permission notice shall be */
20/* included in all copies or substantial portions of the Software. */
21/* */
22/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
23/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
24/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
25/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
26/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
27/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
28/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
29/**************************************************************************/
30
31#include "editor_log.h"
32
33#include "core/object/undo_redo.h"
34#include "core/os/keyboard.h"
35#include "core/version.h"
36#include "editor/editor_node.h"
37#include "editor/editor_paths.h"
38#include "editor/editor_scale.h"
39#include "editor/editor_settings.h"
40#include "editor/editor_string_names.h"
41#include "scene/gui/center_container.h"
42#include "scene/gui/separator.h"
43#include "scene/resources/font.h"
44
45void EditorLog::_error_handler(void *p_self, const char *p_func, const char *p_file, int p_line, const char *p_error, const char *p_errorexp, bool p_editor_notify, ErrorHandlerType p_type) {
46 EditorLog *self = static_cast<EditorLog *>(p_self);
47
48 String err_str;
49 if (p_errorexp && p_errorexp[0]) {
50 err_str = String::utf8(p_errorexp);
51 } else {
52 err_str = String::utf8(p_file) + ":" + itos(p_line) + " - " + String::utf8(p_error);
53 }
54
55 if (p_editor_notify) {
56 err_str += " (User)";
57 }
58
59 MessageType message_type = p_type == ERR_HANDLER_WARNING ? MSG_TYPE_WARNING : MSG_TYPE_ERROR;
60
61 if (self->current != Thread::get_caller_id()) {
62 callable_mp(self, &EditorLog::add_message).bind(err_str, message_type).call_deferred();
63 } else {
64 self->add_message(err_str, message_type);
65 }
66}
67
68void EditorLog::_update_theme() {
69 const Ref<Font> normal_font = get_theme_font(SNAME("output_source"), EditorStringName(EditorFonts));
70 if (normal_font.is_valid()) {
71 log->add_theme_font_override("normal_font", normal_font);
72 }
73
74 const Ref<Font> bold_font = get_theme_font(SNAME("output_source_bold"), EditorStringName(EditorFonts));
75 if (bold_font.is_valid()) {
76 log->add_theme_font_override("bold_font", bold_font);
77 }
78
79 const Ref<Font> italics_font = get_theme_font(SNAME("output_source_italic"), EditorStringName(EditorFonts));
80 if (italics_font.is_valid()) {
81 log->add_theme_font_override("italics_font", italics_font);
82 }
83
84 const Ref<Font> bold_italics_font = get_theme_font(SNAME("output_source_bold_italic"), EditorStringName(EditorFonts));
85 if (bold_italics_font.is_valid()) {
86 log->add_theme_font_override("bold_italics_font", bold_italics_font);
87 }
88
89 const Ref<Font> mono_font = get_theme_font(SNAME("output_source_mono"), EditorStringName(EditorFonts));
90 if (mono_font.is_valid()) {
91 log->add_theme_font_override("mono_font", mono_font);
92 }
93
94 // Disable padding for highlighted background/foreground to prevent highlights from overlapping on close lines.
95 // This also better matches terminal output, which does not use any form of padding.
96 log->add_theme_constant_override("text_highlight_h_padding", 0);
97 log->add_theme_constant_override("text_highlight_v_padding", 0);
98
99 const int font_size = get_theme_font_size(SNAME("output_source_size"), EditorStringName(EditorFonts));
100 log->add_theme_font_size_override("normal_font_size", font_size);
101 log->add_theme_font_size_override("bold_font_size", font_size);
102 log->add_theme_font_size_override("italics_font_size", font_size);
103 log->add_theme_font_size_override("mono_font_size", font_size);
104
105 type_filter_map[MSG_TYPE_STD]->toggle_button->set_icon(get_editor_theme_icon(SNAME("Popup")));
106 type_filter_map[MSG_TYPE_ERROR]->toggle_button->set_icon(get_editor_theme_icon(SNAME("StatusError")));
107 type_filter_map[MSG_TYPE_WARNING]->toggle_button->set_icon(get_editor_theme_icon(SNAME("StatusWarning")));
108 type_filter_map[MSG_TYPE_EDITOR]->toggle_button->set_icon(get_editor_theme_icon(SNAME("Edit")));
109
110 type_filter_map[MSG_TYPE_STD]->toggle_button->set_theme_type_variation("EditorLogFilterButton");
111 type_filter_map[MSG_TYPE_ERROR]->toggle_button->set_theme_type_variation("EditorLogFilterButton");
112 type_filter_map[MSG_TYPE_WARNING]->toggle_button->set_theme_type_variation("EditorLogFilterButton");
113 type_filter_map[MSG_TYPE_EDITOR]->toggle_button->set_theme_type_variation("EditorLogFilterButton");
114
115 clear_button->set_icon(get_editor_theme_icon(SNAME("Clear")));
116 copy_button->set_icon(get_editor_theme_icon(SNAME("ActionCopy")));
117 collapse_button->set_icon(get_editor_theme_icon(SNAME("CombineLines")));
118 show_search_button->set_icon(get_editor_theme_icon(SNAME("Search")));
119 search_box->set_right_icon(get_editor_theme_icon(SNAME("Search")));
120
121 theme_cache.error_color = get_theme_color(SNAME("error_color"), EditorStringName(Editor));
122 theme_cache.error_icon = get_editor_theme_icon(SNAME("Error"));
123 theme_cache.warning_color = get_theme_color(SNAME("warning_color"), EditorStringName(Editor));
124 theme_cache.warning_icon = get_editor_theme_icon(SNAME("Warning"));
125 theme_cache.message_color = get_theme_color(SNAME("font_color"), EditorStringName(Editor)) * Color(1, 1, 1, 0.6);
126}
127
128void EditorLog::_notification(int p_what) {
129 switch (p_what) {
130 case NOTIFICATION_ENTER_TREE: {
131 _update_theme();
132 _load_state();
133 } break;
134
135 case NOTIFICATION_THEME_CHANGED: {
136 _update_theme();
137 _rebuild_log();
138 } break;
139 }
140}
141
142void EditorLog::_set_collapse(bool p_collapse) {
143 collapse = p_collapse;
144 _start_state_save_timer();
145 _rebuild_log();
146}
147
148void EditorLog::_start_state_save_timer() {
149 if (!is_loading_state) {
150 save_state_timer->start();
151 }
152}
153
154void EditorLog::_save_state() {
155 Ref<ConfigFile> config;
156 config.instantiate();
157 // Load and amend existing config if it exists.
158 config->load(EditorPaths::get_singleton()->get_project_settings_dir().path_join("editor_layout.cfg"));
159
160 const String section = "editor_log";
161 for (const KeyValue<MessageType, LogFilter *> &E : type_filter_map) {
162 config->set_value(section, "log_filter_" + itos(E.key), E.value->is_active());
163 }
164
165 config->set_value(section, "collapse", collapse);
166 config->set_value(section, "show_search", search_box->is_visible());
167
168 config->save(EditorPaths::get_singleton()->get_project_settings_dir().path_join("editor_layout.cfg"));
169}
170
171void EditorLog::_load_state() {
172 is_loading_state = true;
173
174 Ref<ConfigFile> config;
175 config.instantiate();
176 config->load(EditorPaths::get_singleton()->get_project_settings_dir().path_join("editor_layout.cfg"));
177
178 // Run the below code even if config->load returns an error, since we want the defaults to be set even if the file does not exist yet.
179 const String section = "editor_log";
180 for (const KeyValue<MessageType, LogFilter *> &E : type_filter_map) {
181 E.value->set_active(config->get_value(section, "log_filter_" + itos(E.key), true));
182 }
183
184 collapse = config->get_value(section, "collapse", false);
185 collapse_button->set_pressed(collapse);
186 bool show_search = config->get_value(section, "show_search", true);
187 search_box->set_visible(show_search);
188 show_search_button->set_pressed(show_search);
189
190 is_loading_state = false;
191}
192
193void EditorLog::_clear_request() {
194 log->clear();
195 messages.clear();
196 _reset_message_counts();
197 tool_button->set_icon(Ref<Texture2D>());
198}
199
200void EditorLog::_copy_request() {
201 String text = log->get_selected_text();
202
203 if (text.is_empty()) {
204 text = log->get_parsed_text();
205 }
206
207 if (!text.is_empty()) {
208 DisplayServer::get_singleton()->clipboard_set(text);
209 }
210}
211
212void EditorLog::clear() {
213 _clear_request();
214}
215
216void EditorLog::_process_message(const String &p_msg, MessageType p_type, bool p_clear) {
217 if (messages.size() > 0 && messages[messages.size() - 1].text == p_msg && messages[messages.size() - 1].type == p_type) {
218 // If previous message is the same as the new one, increase previous count rather than adding another
219 // instance to the messages list.
220 LogMessage &previous = messages.write[messages.size() - 1];
221 previous.count++;
222
223 _add_log_line(previous, collapse);
224 } else {
225 // Different message to the previous one received.
226 LogMessage message(p_msg, p_type, p_clear);
227 _add_log_line(message);
228 messages.push_back(message);
229 }
230
231 type_filter_map[p_type]->set_message_count(type_filter_map[p_type]->get_message_count() + 1);
232}
233
234void EditorLog::add_message(const String &p_msg, MessageType p_type) {
235 // Make text split by new lines their own message.
236 // See #41321 for reasoning. At time of writing, multiple print()'s in running projects
237 // get grouped together and sent to the editor log as one message. This can mess with the
238 // search functionality (see the comments on the PR above for more details). This behavior
239 // also matches that of other IDE's.
240 Vector<String> lines = p_msg.split("\n", true);
241 int line_count = lines.size();
242
243 for (int i = 0; i < line_count; i++) {
244 _process_message(lines[i], p_type, i == line_count - 1);
245 }
246}
247
248void EditorLog::set_tool_button(Button *p_tool_button) {
249 tool_button = p_tool_button;
250}
251
252void EditorLog::register_undo_redo(UndoRedo *p_undo_redo) {
253 p_undo_redo->set_commit_notify_callback(_undo_redo_cbk, this);
254}
255
256void EditorLog::_undo_redo_cbk(void *p_self, const String &p_name) {
257 EditorLog *self = static_cast<EditorLog *>(p_self);
258 self->add_message(p_name, EditorLog::MSG_TYPE_EDITOR);
259}
260
261void EditorLog::_rebuild_log() {
262 log->clear();
263
264 for (int msg_idx = 0; msg_idx < messages.size(); msg_idx++) {
265 LogMessage msg = messages[msg_idx];
266
267 if (collapse) {
268 // If collapsing, only log one instance of the message.
269 _add_log_line(msg);
270 } else {
271 // If not collapsing, log each instance on a line.
272 for (int i = 0; i < msg.count; i++) {
273 _add_log_line(msg);
274 }
275 }
276 }
277}
278
279void EditorLog::_add_log_line(LogMessage &p_message, bool p_replace_previous) {
280 if (!is_inside_tree()) {
281 // The log will be built all at once when it enters the tree and has its theme items.
282 return;
283 }
284
285 if (unlikely(log->is_updating())) {
286 // The new message arrived during log RTL text processing/redraw (invalid BiDi control characters / font error), ignore it to avoid RTL data corruption.
287 return;
288 }
289
290 // Only add the message to the log if it passes the filters.
291 bool filter_active = type_filter_map[p_message.type]->is_active();
292 String search_text = search_box->get_text();
293 bool search_match = search_text.is_empty() || p_message.text.findn(search_text) > -1;
294
295 if (!filter_active || !search_match) {
296 return;
297 }
298
299 if (p_replace_previous) {
300 // Remove last line if replacing, as it will be replace by the next added line.
301 // Why "- 2"? RichTextLabel is weird. When you add a line with add_newline(), it also adds an element to the list of lines which is null/blank,
302 // but it still counts as a line. So if you remove the last line (count - 1) you are actually removing nothing...
303 log->remove_paragraph(log->get_paragraph_count() - 2);
304 }
305
306 switch (p_message.type) {
307 case MSG_TYPE_STD: {
308 } break;
309 case MSG_TYPE_STD_RICH: {
310 } break;
311 case MSG_TYPE_ERROR: {
312 log->push_color(theme_cache.error_color);
313 Ref<Texture2D> icon = theme_cache.error_icon;
314 log->add_image(icon);
315 log->add_text(" ");
316 tool_button->set_icon(icon);
317 } break;
318 case MSG_TYPE_WARNING: {
319 log->push_color(theme_cache.warning_color);
320 Ref<Texture2D> icon = theme_cache.warning_icon;
321 log->add_image(icon);
322 log->add_text(" ");
323 tool_button->set_icon(icon);
324 } break;
325 case MSG_TYPE_EDITOR: {
326 // Distinguish editor messages from messages printed by the project
327 log->push_color(theme_cache.message_color);
328 } break;
329 }
330
331 // If collapsing, add the count of this message in bold at the start of the line.
332 if (collapse && p_message.count > 1) {
333 log->push_bold();
334 log->add_text(vformat("(%s) ", itos(p_message.count)));
335 log->pop();
336 }
337
338 if (p_message.type == MSG_TYPE_STD_RICH) {
339 log->append_text(p_message.text);
340 } else {
341 log->add_text(p_message.text);
342 }
343 if (p_message.clear || p_message.type != MSG_TYPE_STD_RICH) {
344 log->pop_all(); // Pop all unclosed tags.
345 }
346 log->add_newline();
347
348 if (p_replace_previous) {
349 // Force sync last line update (skip if number of unprocessed log messages is too large to avoid editor lag).
350 if (log->get_pending_paragraphs() < 100) {
351 while (!log->is_ready()) {
352 ::OS::get_singleton()->delay_usec(1);
353 }
354 }
355 }
356}
357
358void EditorLog::_set_filter_active(bool p_active, MessageType p_message_type) {
359 type_filter_map[p_message_type]->set_active(p_active);
360 _start_state_save_timer();
361 _rebuild_log();
362}
363
364void EditorLog::_set_search_visible(bool p_visible) {
365 search_box->set_visible(p_visible);
366 if (p_visible) {
367 search_box->grab_focus();
368 }
369 _start_state_save_timer();
370}
371
372void EditorLog::_search_changed(const String &p_text) {
373 _rebuild_log();
374}
375
376void EditorLog::_reset_message_counts() {
377 for (const KeyValue<MessageType, LogFilter *> &E : type_filter_map) {
378 E.value->set_message_count(0);
379 }
380}
381
382EditorLog::EditorLog() {
383 save_state_timer = memnew(Timer);
384 save_state_timer->set_wait_time(2);
385 save_state_timer->set_one_shot(true);
386 save_state_timer->connect("timeout", callable_mp(this, &EditorLog::_save_state));
387 add_child(save_state_timer);
388
389 HBoxContainer *hb = this;
390
391 VBoxContainer *vb_left = memnew(VBoxContainer);
392 vb_left->set_custom_minimum_size(Size2(0, 180) * EDSCALE);
393 vb_left->set_v_size_flags(SIZE_EXPAND_FILL);
394 vb_left->set_h_size_flags(SIZE_EXPAND_FILL);
395 hb->add_child(vb_left);
396
397 // Log - Rich Text Label.
398 log = memnew(RichTextLabel);
399 log->set_threaded(true);
400 log->set_use_bbcode(true);
401 log->set_scroll_follow(true);
402 log->set_selection_enabled(true);
403 log->set_context_menu_enabled(true);
404 log->set_focus_mode(FOCUS_CLICK);
405 log->set_v_size_flags(SIZE_EXPAND_FILL);
406 log->set_h_size_flags(SIZE_EXPAND_FILL);
407 log->set_deselect_on_focus_loss_enabled(false);
408 vb_left->add_child(log);
409
410 // Search box
411 search_box = memnew(LineEdit);
412 search_box->set_h_size_flags(Control::SIZE_EXPAND_FILL);
413 search_box->set_placeholder(TTR("Filter Messages"));
414 search_box->set_clear_button_enabled(true);
415 search_box->set_visible(true);
416 search_box->connect("text_changed", callable_mp(this, &EditorLog::_search_changed));
417 vb_left->add_child(search_box);
418
419 VBoxContainer *vb_right = memnew(VBoxContainer);
420 hb->add_child(vb_right);
421
422 // Tools grid
423 HBoxContainer *hb_tools = memnew(HBoxContainer);
424 hb_tools->set_h_size_flags(SIZE_SHRINK_CENTER);
425 vb_right->add_child(hb_tools);
426
427 // Clear.
428 clear_button = memnew(Button);
429 clear_button->set_flat(true);
430 clear_button->set_focus_mode(FOCUS_NONE);
431 clear_button->set_shortcut(ED_SHORTCUT("editor/clear_output", TTR("Clear Output"), KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT | Key::K));
432 clear_button->set_shortcut_context(this);
433 clear_button->connect("pressed", callable_mp(this, &EditorLog::_clear_request));
434 hb_tools->add_child(clear_button);
435
436 // Copy.
437 copy_button = memnew(Button);
438 copy_button->set_flat(true);
439 copy_button->set_focus_mode(FOCUS_NONE);
440 copy_button->set_shortcut(ED_SHORTCUT("editor/copy_output", TTR("Copy Selection"), KeyModifierMask::CMD_OR_CTRL | Key::C));
441 copy_button->set_shortcut_context(this);
442 copy_button->connect("pressed", callable_mp(this, &EditorLog::_copy_request));
443 hb_tools->add_child(copy_button);
444
445 // A second hbox to make a 2x2 grid of buttons.
446 HBoxContainer *hb_tools2 = memnew(HBoxContainer);
447 hb_tools2->set_h_size_flags(SIZE_SHRINK_CENTER);
448 vb_right->add_child(hb_tools2);
449
450 // Collapse.
451 collapse_button = memnew(Button);
452 collapse_button->set_flat(true);
453 collapse_button->set_focus_mode(FOCUS_NONE);
454 collapse_button->set_tooltip_text(TTR("Collapse duplicate messages into one log entry. Shows number of occurrences."));
455 collapse_button->set_toggle_mode(true);
456 collapse_button->set_pressed(false);
457 collapse_button->connect("toggled", callable_mp(this, &EditorLog::_set_collapse));
458 hb_tools2->add_child(collapse_button);
459
460 // Show Search.
461 show_search_button = memnew(Button);
462 show_search_button->set_flat(true);
463 show_search_button->set_focus_mode(FOCUS_NONE);
464 show_search_button->set_toggle_mode(true);
465 show_search_button->set_pressed(true);
466 show_search_button->set_shortcut(ED_SHORTCUT("editor/open_search", TTR("Focus Search/Filter Bar"), KeyModifierMask::CMD_OR_CTRL | Key::F));
467 show_search_button->set_shortcut_context(this);
468 show_search_button->connect("toggled", callable_mp(this, &EditorLog::_set_search_visible));
469 hb_tools2->add_child(show_search_button);
470
471 // Message Type Filters.
472 vb_right->add_child(memnew(HSeparator));
473
474 LogFilter *std_filter = memnew(LogFilter(MSG_TYPE_STD));
475 std_filter->initialize_button(TTR("Toggle visibility of standard output messages."), callable_mp(this, &EditorLog::_set_filter_active));
476 vb_right->add_child(std_filter->toggle_button);
477 type_filter_map.insert(MSG_TYPE_STD, std_filter);
478 type_filter_map.insert(MSG_TYPE_STD_RICH, std_filter);
479
480 LogFilter *error_filter = memnew(LogFilter(MSG_TYPE_ERROR));
481 error_filter->initialize_button(TTR("Toggle visibility of errors."), callable_mp(this, &EditorLog::_set_filter_active));
482 vb_right->add_child(error_filter->toggle_button);
483 type_filter_map.insert(MSG_TYPE_ERROR, error_filter);
484
485 LogFilter *warning_filter = memnew(LogFilter(MSG_TYPE_WARNING));
486 warning_filter->initialize_button(TTR("Toggle visibility of warnings."), callable_mp(this, &EditorLog::_set_filter_active));
487 vb_right->add_child(warning_filter->toggle_button);
488 type_filter_map.insert(MSG_TYPE_WARNING, warning_filter);
489
490 LogFilter *editor_filter = memnew(LogFilter(MSG_TYPE_EDITOR));
491 editor_filter->initialize_button(TTR("Toggle visibility of editor messages."), callable_mp(this, &EditorLog::_set_filter_active));
492 vb_right->add_child(editor_filter->toggle_button);
493 type_filter_map.insert(MSG_TYPE_EDITOR, editor_filter);
494
495 add_message(VERSION_FULL_NAME " (c) 2007-present Juan Linietsky, Ariel Manzur & Godot Contributors.");
496
497 eh.errfunc = _error_handler;
498 eh.userdata = this;
499 add_error_handler(&eh);
500
501 current = Thread::get_caller_id();
502}
503
504void EditorLog::deinit() {
505 remove_error_handler(&eh);
506}
507
508EditorLog::~EditorLog() {
509 for (const KeyValue<MessageType, LogFilter *> &E : type_filter_map) {
510 // MSG_TYPE_STD_RICH is connected to the std_filter button, so we do this
511 // to avoid it from being deleted twice, causing a crash on closing.
512 if (E.key != MSG_TYPE_STD_RICH) {
513 memdelete(E.value);
514 }
515 }
516}
517