1 /*************************************************************************/
2 /* find_in_files.cpp */
3 /*************************************************************************/
4 /* This file is part of: */
5 /* GODOT ENGINE */
6 /* https://godotengine.org */
7 /*************************************************************************/
8 /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
9 /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
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 "find_in_files.h"
32
33 #include "core/os/dir_access.h"
34 #include "core/os/os.h"
35 #include "editor_node.h"
36 #include "editor_scale.h"
37 #include "scene/gui/box_container.h"
38 #include "scene/gui/button.h"
39 #include "scene/gui/check_box.h"
40 #include "scene/gui/file_dialog.h"
41 #include "scene/gui/grid_container.h"
42 #include "scene/gui/label.h"
43 #include "scene/gui/line_edit.h"
44 #include "scene/gui/progress_bar.h"
45 #include "scene/gui/tree.h"
46
47 const char *FindInFiles::SIGNAL_RESULT_FOUND = "result_found";
48 const char *FindInFiles::SIGNAL_FINISHED = "finished";
49
50 // TODO Would be nice in Vector and PoolVectors
51 template <typename T>
pop_back(T & container)52 inline void pop_back(T &container) {
53 container.resize(container.size() - 1);
54 }
55
56 // TODO Copied from TextEdit private, would be nice to extract it in a single place
is_text_char(CharType c)57 static bool is_text_char(CharType c) {
58 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_';
59 }
60
find_next(const String & line,String pattern,int from,bool match_case,bool whole_words,int & out_begin,int & out_end)61 static bool find_next(const String &line, String pattern, int from, bool match_case, bool whole_words, int &out_begin, int &out_end) {
62
63 int end = from;
64
65 while (true) {
66 int begin = match_case ? line.find(pattern, end) : line.findn(pattern, end);
67
68 if (begin == -1)
69 return false;
70
71 end = begin + pattern.length();
72 out_begin = begin;
73 out_end = end;
74
75 if (whole_words) {
76 if (begin > 0 && is_text_char(line[begin - 1])) {
77 continue;
78 }
79 if (end < line.size() && is_text_char(line[end])) {
80 continue;
81 }
82 }
83
84 return true;
85 }
86 }
87
88 //--------------------------------------------------------------------------------
FindInFiles()89 FindInFiles::FindInFiles() {
90 _searching = false;
91 _whole_words = true;
92 _match_case = true;
93 }
94
set_search_text(String p_pattern)95 void FindInFiles::set_search_text(String p_pattern) {
96 _pattern = p_pattern;
97 }
98
set_whole_words(bool p_whole_word)99 void FindInFiles::set_whole_words(bool p_whole_word) {
100 _whole_words = p_whole_word;
101 }
102
set_match_case(bool p_match_case)103 void FindInFiles::set_match_case(bool p_match_case) {
104 _match_case = p_match_case;
105 }
106
set_folder(String folder)107 void FindInFiles::set_folder(String folder) {
108 _root_dir = folder;
109 }
110
set_filter(const Set<String> & exts)111 void FindInFiles::set_filter(const Set<String> &exts) {
112 _extension_filter = exts;
113 }
114
_notification(int p_notification)115 void FindInFiles::_notification(int p_notification) {
116 if (p_notification == NOTIFICATION_PROCESS) {
117 _process();
118 }
119 }
120
start()121 void FindInFiles::start() {
122 if (_pattern == "") {
123 print_verbose("Nothing to search, pattern is empty");
124 emit_signal(SIGNAL_FINISHED);
125 return;
126 }
127 if (_extension_filter.size() == 0) {
128 print_verbose("Nothing to search, filter matches no files");
129 emit_signal(SIGNAL_FINISHED);
130 return;
131 }
132
133 // Init search
134 _current_dir = "";
135 PoolStringArray init_folder;
136 init_folder.append(_root_dir);
137 _folders_stack.clear();
138 _folders_stack.push_back(init_folder);
139
140 _initial_files_count = 0;
141
142 _searching = true;
143 set_process(true);
144 }
145
stop()146 void FindInFiles::stop() {
147 _searching = false;
148 _current_dir = "";
149 set_process(false);
150 }
151
_process()152 void FindInFiles::_process() {
153 // This part can be moved to a thread if needed
154
155 OS &os = *OS::get_singleton();
156 float time_before = os.get_ticks_msec();
157 while (is_processing()) {
158 _iterate();
159 float elapsed = (os.get_ticks_msec() - time_before);
160 if (elapsed > 1000.0 / 120.0)
161 break;
162 }
163 }
164
_iterate()165 void FindInFiles::_iterate() {
166
167 if (_folders_stack.size() != 0) {
168
169 // Scan folders first so we can build a list of files and have progress info later
170
171 PoolStringArray &folders_to_scan = _folders_stack.write[_folders_stack.size() - 1];
172
173 if (folders_to_scan.size() != 0) {
174 // Scan one folder below
175
176 String folder_name = folders_to_scan[folders_to_scan.size() - 1];
177 pop_back(folders_to_scan);
178
179 _current_dir = _current_dir.plus_file(folder_name);
180
181 PoolStringArray sub_dirs;
182 _scan_dir("res://" + _current_dir, sub_dirs);
183
184 _folders_stack.push_back(sub_dirs);
185
186 } else {
187 // Go back one level
188
189 pop_back(_folders_stack);
190 _current_dir = _current_dir.get_base_dir();
191
192 if (_folders_stack.size() == 0) {
193 // All folders scanned
194 _initial_files_count = _files_to_scan.size();
195 }
196 }
197
198 } else if (_files_to_scan.size() != 0) {
199
200 // Then scan files
201
202 String fpath = _files_to_scan[_files_to_scan.size() - 1];
203 pop_back(_files_to_scan);
204 _scan_file(fpath);
205
206 } else {
207 print_verbose("Search complete");
208 set_process(false);
209 _current_dir = "";
210 _searching = false;
211 emit_signal(SIGNAL_FINISHED);
212 }
213 }
214
get_progress() const215 float FindInFiles::get_progress() const {
216 if (_initial_files_count != 0) {
217 return static_cast<float>(_initial_files_count - _files_to_scan.size()) / static_cast<float>(_initial_files_count);
218 }
219 return 0;
220 }
221
_scan_dir(String path,PoolStringArray & out_folders)222 void FindInFiles::_scan_dir(String path, PoolStringArray &out_folders) {
223
224 DirAccessRef dir = DirAccess::open(path);
225 if (!dir) {
226 print_verbose("Cannot open directory! " + path);
227 return;
228 }
229
230 dir->list_dir_begin();
231
232 for (int i = 0; i < 1000; ++i) {
233 String file = dir->get_next();
234
235 if (file == "")
236 break;
237
238 // Ignore special dirs (such as .git and .import)
239 if (file == "." || file == ".." || file.begins_with("."))
240 continue;
241 if (dir->current_is_hidden())
242 continue;
243
244 if (dir->current_is_dir())
245 out_folders.append(file);
246
247 else {
248 String file_ext = file.get_extension();
249 if (_extension_filter.has(file_ext)) {
250 _files_to_scan.push_back(path.plus_file(file));
251 }
252 }
253 }
254 }
255
_scan_file(String fpath)256 void FindInFiles::_scan_file(String fpath) {
257
258 FileAccessRef f = FileAccess::open(fpath, FileAccess::READ);
259 if (!f) {
260 print_verbose(String("Cannot open file ") + fpath);
261 return;
262 }
263
264 int line_number = 0;
265
266 while (!f->eof_reached()) {
267
268 // line number starts at 1
269 ++line_number;
270
271 int begin = 0;
272 int end = 0;
273
274 String line = f->get_line();
275
276 while (find_next(line, _pattern, end, _match_case, _whole_words, begin, end)) {
277 emit_signal(SIGNAL_RESULT_FOUND, fpath, line_number, begin, end, line);
278 }
279 }
280
281 f->close();
282 }
283
_bind_methods()284 void FindInFiles::_bind_methods() {
285
286 ADD_SIGNAL(MethodInfo(SIGNAL_RESULT_FOUND,
287 PropertyInfo(Variant::STRING, "path"),
288 PropertyInfo(Variant::INT, "line_number"),
289 PropertyInfo(Variant::INT, "begin"),
290 PropertyInfo(Variant::INT, "end"),
291 PropertyInfo(Variant::STRING, "text")));
292
293 ADD_SIGNAL(MethodInfo(SIGNAL_FINISHED));
294 }
295
296 //-----------------------------------------------------------------------------
297 const char *FindInFilesDialog::SIGNAL_FIND_REQUESTED = "find_requested";
298 const char *FindInFilesDialog::SIGNAL_REPLACE_REQUESTED = "replace_requested";
299
FindInFilesDialog()300 FindInFilesDialog::FindInFilesDialog() {
301
302 set_custom_minimum_size(Size2(500 * EDSCALE, 0));
303 set_title(TTR("Find in Files"));
304
305 VBoxContainer *vbc = memnew(VBoxContainer);
306 vbc->set_anchor_and_margin(MARGIN_LEFT, ANCHOR_BEGIN, 8 * EDSCALE);
307 vbc->set_anchor_and_margin(MARGIN_TOP, ANCHOR_BEGIN, 8 * EDSCALE);
308 vbc->set_anchor_and_margin(MARGIN_RIGHT, ANCHOR_END, -8 * EDSCALE);
309 vbc->set_anchor_and_margin(MARGIN_BOTTOM, ANCHOR_END, -8 * EDSCALE);
310 add_child(vbc);
311
312 GridContainer *gc = memnew(GridContainer);
313 gc->set_columns(2);
314 vbc->add_child(gc);
315
316 Label *find_label = memnew(Label);
317 find_label->set_text(TTR("Find:"));
318 gc->add_child(find_label);
319
320 _search_text_line_edit = memnew(LineEdit);
321 _search_text_line_edit->set_h_size_flags(SIZE_EXPAND_FILL);
322 _search_text_line_edit->connect("text_changed", this, "_on_search_text_modified");
323 _search_text_line_edit->connect("text_entered", this, "_on_search_text_entered");
324 gc->add_child(_search_text_line_edit);
325
326 gc->add_child(memnew(Control)); // Space to maintain the grid aligned.
327
328 {
329 HBoxContainer *hbc = memnew(HBoxContainer);
330
331 _whole_words_checkbox = memnew(CheckBox);
332 _whole_words_checkbox->set_text(TTR("Whole Words"));
333 hbc->add_child(_whole_words_checkbox);
334
335 _match_case_checkbox = memnew(CheckBox);
336 _match_case_checkbox->set_text(TTR("Match Case"));
337 hbc->add_child(_match_case_checkbox);
338
339 gc->add_child(hbc);
340 }
341
342 Label *folder_label = memnew(Label);
343 folder_label->set_text(TTR("Folder:"));
344 gc->add_child(folder_label);
345
346 {
347 HBoxContainer *hbc = memnew(HBoxContainer);
348
349 Label *prefix_label = memnew(Label);
350 prefix_label->set_text("res://");
351 hbc->add_child(prefix_label);
352
353 _folder_line_edit = memnew(LineEdit);
354 _folder_line_edit->set_h_size_flags(SIZE_EXPAND_FILL);
355 hbc->add_child(_folder_line_edit);
356
357 Button *folder_button = memnew(Button);
358 folder_button->set_text("...");
359 folder_button->connect("pressed", this, "_on_folder_button_pressed");
360 hbc->add_child(folder_button);
361
362 _folder_dialog = memnew(FileDialog);
363 _folder_dialog->set_mode(FileDialog::MODE_OPEN_DIR);
364 _folder_dialog->connect("dir_selected", this, "_on_folder_selected");
365 add_child(_folder_dialog);
366
367 gc->add_child(hbc);
368 }
369
370 Label *filter_label = memnew(Label);
371 filter_label->set_text(TTR("Filters:"));
372 filter_label->set_tooltip(TTR("Include the files with the following extensions. Add or remove them in ProjectSettings."));
373 gc->add_child(filter_label);
374
375 _filters_container = memnew(HBoxContainer);
376 gc->add_child(_filters_container);
377
378 _find_button = add_button(TTR("Find..."), false, "find");
379 _find_button->set_disabled(true);
380
381 _replace_button = add_button(TTR("Replace..."), false, "replace");
382 _replace_button->set_disabled(true);
383
384 Button *cancel_button = get_ok();
385 cancel_button->set_text(TTR("Cancel"));
386 }
387
set_search_text(String text)388 void FindInFilesDialog::set_search_text(String text) {
389 _search_text_line_edit->set_text(text);
390 _on_search_text_modified(text);
391 }
392
get_search_text() const393 String FindInFilesDialog::get_search_text() const {
394 String text = _search_text_line_edit->get_text();
395 return text.strip_edges();
396 }
397
is_match_case() const398 bool FindInFilesDialog::is_match_case() const {
399 return _match_case_checkbox->is_pressed();
400 }
401
is_whole_words() const402 bool FindInFilesDialog::is_whole_words() const {
403 return _whole_words_checkbox->is_pressed();
404 }
405
get_folder() const406 String FindInFilesDialog::get_folder() const {
407 String text = _folder_line_edit->get_text();
408 return text.strip_edges();
409 }
410
get_filter() const411 Set<String> FindInFilesDialog::get_filter() const {
412 // could check the _filters_preferences but it might not have been generated yet.
413 Set<String> filters;
414 for (int i = 0; i < _filters_container->get_child_count(); ++i) {
415 CheckBox *cb = (CheckBox *)_filters_container->get_child(i);
416 if (cb->is_pressed()) {
417 filters.insert(cb->get_text());
418 }
419 }
420 return filters;
421 }
422
_notification(int p_what)423 void FindInFilesDialog::_notification(int p_what) {
424 if (p_what == NOTIFICATION_VISIBILITY_CHANGED) {
425 if (is_visible()) {
426 // Doesn't work more than once if not deferred...
427 _search_text_line_edit->call_deferred("grab_focus");
428 _search_text_line_edit->select_all();
429 // Extensions might have changed in the meantime, we clean them and instance them again.
430 for (int i = 0; i < _filters_container->get_child_count(); i++) {
431 _filters_container->get_child(i)->queue_delete();
432 }
433 Array exts = ProjectSettings::get_singleton()->get("editor/search_in_file_extensions");
434 for (int i = 0; i < exts.size(); ++i) {
435 CheckBox *cb = memnew(CheckBox);
436 cb->set_text(exts[i]);
437 if (!_filters_preferences.has(exts[i])) {
438 _filters_preferences[exts[i]] = true;
439 }
440 cb->set_pressed(_filters_preferences[exts[i]]);
441 _filters_container->add_child(cb);
442 }
443 }
444 }
445 }
446
_on_folder_button_pressed()447 void FindInFilesDialog::_on_folder_button_pressed() {
448 _folder_dialog->popup_centered_ratio();
449 }
450
custom_action(const String & p_action)451 void FindInFilesDialog::custom_action(const String &p_action) {
452 for (int i = 0; i < _filters_container->get_child_count(); ++i) {
453 CheckBox *cb = (CheckBox *)_filters_container->get_child(i);
454 _filters_preferences[cb->get_text()] = cb->is_pressed();
455 }
456 if (p_action == "find") {
457 emit_signal(SIGNAL_FIND_REQUESTED);
458 hide();
459 } else if (p_action == "replace") {
460 emit_signal(SIGNAL_REPLACE_REQUESTED);
461 hide();
462 }
463 }
464
_on_search_text_modified(String text)465 void FindInFilesDialog::_on_search_text_modified(String text) {
466
467 ERR_FAIL_COND(!_find_button);
468 ERR_FAIL_COND(!_replace_button);
469
470 _find_button->set_disabled(get_search_text().empty());
471 _replace_button->set_disabled(get_search_text().empty());
472 }
473
_on_search_text_entered(String text)474 void FindInFilesDialog::_on_search_text_entered(String text) {
475 // This allows to trigger a global search without leaving the keyboard
476 if (!_find_button->is_disabled())
477 custom_action("find");
478 }
479
_on_folder_selected(String path)480 void FindInFilesDialog::_on_folder_selected(String path) {
481 int i = path.find("://");
482 if (i != -1)
483 path = path.right(i + 3);
484 _folder_line_edit->set_text(path);
485 }
486
_bind_methods()487 void FindInFilesDialog::_bind_methods() {
488
489 ClassDB::bind_method("_on_folder_button_pressed", &FindInFilesDialog::_on_folder_button_pressed);
490 ClassDB::bind_method("_on_folder_selected", &FindInFilesDialog::_on_folder_selected);
491 ClassDB::bind_method("_on_search_text_modified", &FindInFilesDialog::_on_search_text_modified);
492 ClassDB::bind_method("_on_search_text_entered", &FindInFilesDialog::_on_search_text_entered);
493
494 ADD_SIGNAL(MethodInfo(SIGNAL_FIND_REQUESTED));
495 ADD_SIGNAL(MethodInfo(SIGNAL_REPLACE_REQUESTED));
496 }
497
498 //-----------------------------------------------------------------------------
499 const char *FindInFilesPanel::SIGNAL_RESULT_SELECTED = "result_selected";
500 const char *FindInFilesPanel::SIGNAL_FILES_MODIFIED = "files_modified";
501
FindInFilesPanel()502 FindInFilesPanel::FindInFilesPanel() {
503
504 _finder = memnew(FindInFiles);
505 _finder->connect(FindInFiles::SIGNAL_RESULT_FOUND, this, "_on_result_found");
506 _finder->connect(FindInFiles::SIGNAL_FINISHED, this, "_on_finished");
507 add_child(_finder);
508
509 VBoxContainer *vbc = memnew(VBoxContainer);
510 vbc->set_anchor_and_margin(MARGIN_LEFT, ANCHOR_BEGIN, 0);
511 vbc->set_anchor_and_margin(MARGIN_TOP, ANCHOR_BEGIN, 0);
512 vbc->set_anchor_and_margin(MARGIN_RIGHT, ANCHOR_END, 0);
513 vbc->set_anchor_and_margin(MARGIN_BOTTOM, ANCHOR_END, 0);
514 add_child(vbc);
515
516 {
517 HBoxContainer *hbc = memnew(HBoxContainer);
518
519 Label *find_label = memnew(Label);
520 find_label->set_text(TTR("Find: "));
521 hbc->add_child(find_label);
522
523 _search_text_label = memnew(Label);
524 _search_text_label->add_font_override("font", EditorNode::get_singleton()->get_gui_base()->get_font("source", "EditorFonts"));
525 hbc->add_child(_search_text_label);
526
527 _progress_bar = memnew(ProgressBar);
528 _progress_bar->set_h_size_flags(SIZE_EXPAND_FILL);
529 _progress_bar->set_v_size_flags(SIZE_SHRINK_CENTER);
530 hbc->add_child(_progress_bar);
531 set_progress_visible(false);
532
533 _status_label = memnew(Label);
534 hbc->add_child(_status_label);
535
536 _refresh_button = memnew(Button);
537 _refresh_button->set_text(TTR("Refresh"));
538 _refresh_button->connect("pressed", this, "_on_refresh_button_clicked");
539 _refresh_button->hide();
540 hbc->add_child(_refresh_button);
541
542 _cancel_button = memnew(Button);
543 _cancel_button->set_text(TTR("Cancel"));
544 _cancel_button->connect("pressed", this, "_on_cancel_button_clicked");
545 _cancel_button->hide();
546 hbc->add_child(_cancel_button);
547
548 vbc->add_child(hbc);
549 }
550
551 _results_display = memnew(Tree);
552 _results_display->add_font_override("font", EditorNode::get_singleton()->get_gui_base()->get_font("source", "EditorFonts"));
553 _results_display->set_v_size_flags(SIZE_EXPAND_FILL);
554 _results_display->connect("item_selected", this, "_on_result_selected");
555 _results_display->connect("item_edited", this, "_on_item_edited");
556 _results_display->set_hide_root(true);
557 _results_display->set_select_mode(Tree::SELECT_ROW);
558 _results_display->set_allow_rmb_select(true);
559 _results_display->create_item(); // Root
560 vbc->add_child(_results_display);
561
562 _with_replace = false;
563
564 {
565 _replace_container = memnew(HBoxContainer);
566
567 Label *replace_label = memnew(Label);
568 replace_label->set_text(TTR("Replace: "));
569 _replace_container->add_child(replace_label);
570
571 _replace_line_edit = memnew(LineEdit);
572 _replace_line_edit->set_h_size_flags(SIZE_EXPAND_FILL);
573 _replace_line_edit->connect("text_changed", this, "_on_replace_text_changed");
574 _replace_container->add_child(_replace_line_edit);
575
576 _replace_all_button = memnew(Button);
577 _replace_all_button->set_text(TTR("Replace all (no undo)"));
578 _replace_all_button->connect("pressed", this, "_on_replace_all_clicked");
579 _replace_container->add_child(_replace_all_button);
580
581 _replace_container->hide();
582
583 vbc->add_child(_replace_container);
584 }
585 }
586
set_with_replace(bool with_replace)587 void FindInFilesPanel::set_with_replace(bool with_replace) {
588
589 _with_replace = with_replace;
590 _replace_container->set_visible(with_replace);
591
592 if (with_replace) {
593 // Results show checkboxes on their left so they can be opted out
594 _results_display->set_columns(2);
595 _results_display->set_column_expand(0, false);
596 _results_display->set_column_min_width(0, 48 * EDSCALE);
597
598 } else {
599 // Results are single-cell items
600 _results_display->set_column_expand(0, true);
601 _results_display->set_columns(1);
602 }
603 }
604
clear()605 void FindInFilesPanel::clear() {
606 _file_items.clear();
607 _result_items.clear();
608 _results_display->clear();
609 _results_display->create_item(); // Root
610 }
611
start_search()612 void FindInFilesPanel::start_search() {
613
614 clear();
615
616 _status_label->set_text(TTR("Searching..."));
617 _search_text_label->set_text(_finder->get_search_text());
618
619 set_process(true);
620 set_progress_visible(true);
621
622 _finder->start();
623
624 update_replace_buttons();
625 _refresh_button->hide();
626 _cancel_button->show();
627 }
628
stop_search()629 void FindInFilesPanel::stop_search() {
630
631 _finder->stop();
632
633 _status_label->set_text("");
634 update_replace_buttons();
635 set_progress_visible(false);
636 _refresh_button->show();
637 _cancel_button->hide();
638 }
639
_notification(int p_what)640 void FindInFilesPanel::_notification(int p_what) {
641 if (p_what == NOTIFICATION_PROCESS) {
642 _progress_bar->set_as_ratio(_finder->get_progress());
643 }
644 }
645
_on_result_found(String fpath,int line_number,int begin,int end,String text)646 void FindInFilesPanel::_on_result_found(String fpath, int line_number, int begin, int end, String text) {
647
648 TreeItem *file_item;
649 Map<String, TreeItem *>::Element *E = _file_items.find(fpath);
650
651 if (E == NULL) {
652 file_item = _results_display->create_item();
653 file_item->set_text(0, fpath);
654 file_item->set_metadata(0, fpath);
655
656 // The width of this column is restrained to checkboxes, but that doesn't make sense for the parent items,
657 // so we override their width so they can expand to full width
658 file_item->set_expand_right(0, true);
659
660 _file_items[fpath] = file_item;
661
662 } else {
663 file_item = E->value();
664 }
665
666 int text_index = _with_replace ? 1 : 0;
667
668 TreeItem *item = _results_display->create_item(file_item);
669
670 // Do this first because it resets properties of the cell...
671 item->set_cell_mode(text_index, TreeItem::CELL_MODE_CUSTOM);
672
673 // Trim result item line
674 int old_text_size = text.size();
675 text = text.strip_edges(true, false);
676 int chars_removed = old_text_size - text.size();
677 String start = vformat("%3s: ", line_number);
678
679 item->set_text(text_index, start + text);
680 item->set_custom_draw(text_index, this, "_draw_result_text");
681
682 Result r;
683 r.line_number = line_number;
684 r.begin = begin;
685 r.end = end;
686 r.begin_trimmed = begin - chars_removed + start.size() - 1;
687 _result_items[item] = r;
688
689 if (_with_replace) {
690 item->set_cell_mode(0, TreeItem::CELL_MODE_CHECK);
691 item->set_checked(0, true);
692 item->set_editable(0, true);
693 }
694 }
695
draw_result_text(Object * item_obj,Rect2 rect)696 void FindInFilesPanel::draw_result_text(Object *item_obj, Rect2 rect) {
697
698 TreeItem *item = Object::cast_to<TreeItem>(item_obj);
699 if (!item)
700 return;
701
702 Map<TreeItem *, Result>::Element *E = _result_items.find(item);
703 if (!E)
704 return;
705 Result r = E->value();
706 String item_text = item->get_text(_with_replace ? 1 : 0);
707 Ref<Font> font = _results_display->get_font("font");
708
709 Rect2 match_rect = rect;
710 match_rect.position.x += font->get_string_size(item_text.left(r.begin_trimmed)).x;
711 match_rect.size.x = font->get_string_size(_search_text_label->get_text()).x;
712 match_rect.position.y += 1 * EDSCALE;
713 match_rect.size.y -= 2 * EDSCALE;
714
715 _results_display->draw_rect(match_rect, Color(0, 0, 0, 0.5));
716 // Text is drawn by Tree already
717 }
718
_on_item_edited()719 void FindInFilesPanel::_on_item_edited() {
720
721 TreeItem *item = _results_display->get_selected();
722
723 if (item->is_checked(0)) {
724 item->set_custom_color(1, _results_display->get_color("font_color"));
725
726 } else {
727 // Grey out
728 Color color = _results_display->get_color("font_color");
729 color.a /= 2.0;
730 item->set_custom_color(1, color);
731 }
732 }
733
_on_finished()734 void FindInFilesPanel::_on_finished() {
735
736 _status_label->set_text(TTR("Search complete"));
737 update_replace_buttons();
738 set_progress_visible(false);
739 _refresh_button->show();
740 _cancel_button->hide();
741 }
742
_on_refresh_button_clicked()743 void FindInFilesPanel::_on_refresh_button_clicked() {
744 start_search();
745 }
746
_on_cancel_button_clicked()747 void FindInFilesPanel::_on_cancel_button_clicked() {
748 stop_search();
749 }
750
_on_result_selected()751 void FindInFilesPanel::_on_result_selected() {
752
753 TreeItem *item = _results_display->get_selected();
754 Map<TreeItem *, Result>::Element *E = _result_items.find(item);
755
756 if (E == NULL)
757 return;
758 Result r = E->value();
759
760 TreeItem *file_item = item->get_parent();
761 String fpath = file_item->get_metadata(0);
762
763 emit_signal(SIGNAL_RESULT_SELECTED, fpath, r.line_number, r.begin, r.end);
764 }
765
_on_replace_text_changed(String text)766 void FindInFilesPanel::_on_replace_text_changed(String text) {
767 update_replace_buttons();
768 }
769
_on_replace_all_clicked()770 void FindInFilesPanel::_on_replace_all_clicked() {
771
772 String replace_text = get_replace_text();
773
774 PoolStringArray modified_files;
775
776 for (Map<String, TreeItem *>::Element *E = _file_items.front(); E; E = E->next()) {
777
778 TreeItem *file_item = E->value();
779 String fpath = file_item->get_metadata(0);
780
781 Vector<Result> locations;
782 for (TreeItem *item = file_item->get_children(); item; item = item->get_next()) {
783
784 if (!item->is_checked(0))
785 continue;
786
787 Map<TreeItem *, Result>::Element *F = _result_items.find(item);
788 ERR_FAIL_COND(F == NULL);
789 locations.push_back(F->value());
790 }
791
792 if (locations.size() != 0) {
793 // Results are sorted by file, so we can batch replaces
794 apply_replaces_in_file(fpath, locations, replace_text);
795 modified_files.append(fpath);
796 }
797 }
798
799 // Hide replace bar so we can't trigger the action twice without doing a new search
800 _replace_container->hide();
801
802 emit_signal(SIGNAL_FILES_MODIFIED, modified_files);
803 }
804
805 // Same as get_line, but preserves line ending characters
806 class ConservativeGetLine {
807 public:
get_line(FileAccess * f)808 String get_line(FileAccess *f) {
809
810 _line_buffer.clear();
811
812 CharType c = f->get_8();
813
814 while (!f->eof_reached()) {
815
816 if (c == '\n') {
817 _line_buffer.push_back(c);
818 _line_buffer.push_back(0);
819 return String::utf8(_line_buffer.ptr());
820
821 } else if (c == '\0') {
822 _line_buffer.push_back(c);
823 return String::utf8(_line_buffer.ptr());
824
825 } else if (c != '\r') {
826 _line_buffer.push_back(c);
827 }
828
829 c = f->get_8();
830 }
831
832 _line_buffer.push_back(0);
833 return String::utf8(_line_buffer.ptr());
834 }
835
836 private:
837 Vector<char> _line_buffer;
838 };
839
apply_replaces_in_file(String fpath,const Vector<Result> & locations,String new_text)840 void FindInFilesPanel::apply_replaces_in_file(String fpath, const Vector<Result> &locations, String new_text) {
841
842 // If the file is already open, I assume the editor will reload it.
843 // If there are unsaved changes, the user will be asked on focus,
844 // however that means either losing changes or losing replaces.
845
846 FileAccessRef f = FileAccess::open(fpath, FileAccess::READ);
847 ERR_FAIL_COND_MSG(!f, "Cannot open file from path '" + fpath + "'.");
848
849 String buffer;
850 int current_line = 1;
851
852 ConservativeGetLine conservative;
853
854 String line = conservative.get_line(f);
855 String search_text = _finder->get_search_text();
856
857 int offset = 0;
858
859 for (int i = 0; i < locations.size(); ++i) {
860
861 int repl_line_number = locations[i].line_number;
862
863 while (current_line < repl_line_number) {
864 buffer += line;
865 line = conservative.get_line(f);
866 ++current_line;
867 offset = 0;
868 }
869
870 int repl_begin = locations[i].begin + offset;
871 int repl_end = locations[i].end + offset;
872
873 int _;
874 if (!find_next(line, search_text, repl_begin, _finder->is_match_case(), _finder->is_whole_words(), _, _)) {
875 // Make sure the replace is still valid in case the file was tampered with.
876 print_verbose(String("Occurrence no longer matches, replace will be ignored in {0}: line {1}, col {2}").format(varray(fpath, repl_line_number, repl_begin)));
877 continue;
878 }
879
880 line = line.left(repl_begin) + new_text + line.right(repl_end);
881 // keep an offset in case there are successive replaces in the same line
882 offset += new_text.length() - (repl_end - repl_begin);
883 }
884
885 buffer += line;
886
887 while (!f->eof_reached()) {
888 buffer += conservative.get_line(f);
889 }
890
891 // Now the modified contents are in the buffer, rewrite the file with our changes
892
893 Error err = f->reopen(fpath, FileAccess::WRITE);
894 ERR_FAIL_COND_MSG(err != OK, "Cannot create file in path '" + fpath + "'.");
895
896 f->store_string(buffer);
897
898 f->close();
899 }
900
get_replace_text()901 String FindInFilesPanel::get_replace_text() {
902 return _replace_line_edit->get_text().strip_edges();
903 }
904
update_replace_buttons()905 void FindInFilesPanel::update_replace_buttons() {
906
907 bool disabled = _finder->is_searching();
908
909 _replace_all_button->set_disabled(disabled);
910 }
911
set_progress_visible(bool visible)912 void FindInFilesPanel::set_progress_visible(bool visible) {
913 _progress_bar->set_self_modulate(Color(1, 1, 1, visible ? 1 : 0));
914 }
915
_bind_methods()916 void FindInFilesPanel::_bind_methods() {
917
918 ClassDB::bind_method("_on_result_found", &FindInFilesPanel::_on_result_found);
919 ClassDB::bind_method("_on_item_edited", &FindInFilesPanel::_on_item_edited);
920 ClassDB::bind_method("_on_finished", &FindInFilesPanel::_on_finished);
921 ClassDB::bind_method("_on_refresh_button_clicked", &FindInFilesPanel::_on_refresh_button_clicked);
922 ClassDB::bind_method("_on_cancel_button_clicked", &FindInFilesPanel::_on_cancel_button_clicked);
923 ClassDB::bind_method("_on_result_selected", &FindInFilesPanel::_on_result_selected);
924 ClassDB::bind_method("_on_replace_text_changed", &FindInFilesPanel::_on_replace_text_changed);
925 ClassDB::bind_method("_on_replace_all_clicked", &FindInFilesPanel::_on_replace_all_clicked);
926 ClassDB::bind_method("_draw_result_text", &FindInFilesPanel::draw_result_text);
927
928 ADD_SIGNAL(MethodInfo(SIGNAL_RESULT_SELECTED,
929 PropertyInfo(Variant::STRING, "path"),
930 PropertyInfo(Variant::INT, "line_number"),
931 PropertyInfo(Variant::INT, "begin"),
932 PropertyInfo(Variant::INT, "end")));
933
934 ADD_SIGNAL(MethodInfo(SIGNAL_FILES_MODIFIED, PropertyInfo(Variant::STRING, "paths")));
935 }
936