Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/editor/script/find_in_files.cpp
9903 views
1
/**************************************************************************/
2
/* find_in_files.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 "find_in_files.h"
32
33
#include "core/config/project_settings.h"
34
#include "core/io/dir_access.h"
35
#include "core/os/os.h"
36
#include "editor/editor_node.h"
37
#include "editor/editor_string_names.h"
38
#include "editor/themes/editor_scale.h"
39
#include "scene/gui/box_container.h"
40
#include "scene/gui/button.h"
41
#include "scene/gui/check_box.h"
42
#include "scene/gui/file_dialog.h"
43
#include "scene/gui/grid_container.h"
44
#include "scene/gui/label.h"
45
#include "scene/gui/line_edit.h"
46
#include "scene/gui/progress_bar.h"
47
#include "scene/gui/tree.h"
48
49
const char *FindInFiles::SIGNAL_RESULT_FOUND = "result_found";
50
51
// TODO: Would be nice in Vector and Vectors.
52
template <typename T>
53
inline void pop_back(T &container) {
54
container.resize(container.size() - 1);
55
}
56
57
static bool find_next(const String &line, const String &pattern, int from, bool match_case, bool whole_words, int &out_begin, int &out_end) {
58
int end = from;
59
60
while (true) {
61
int begin = match_case ? line.find(pattern, end) : line.findn(pattern, end);
62
63
if (begin == -1) {
64
return false;
65
}
66
67
end = begin + pattern.length();
68
out_begin = begin;
69
out_end = end;
70
71
if (whole_words) {
72
if (begin > 0 && (is_ascii_identifier_char(line[begin - 1]))) {
73
continue;
74
}
75
if (end < line.size() && (is_ascii_identifier_char(line[end]))) {
76
continue;
77
}
78
}
79
80
return true;
81
}
82
}
83
84
//--------------------------------------------------------------------------------
85
86
void FindInFiles::set_search_text(const String &p_pattern) {
87
_pattern = p_pattern;
88
}
89
90
void FindInFiles::set_whole_words(bool p_whole_word) {
91
_whole_words = p_whole_word;
92
}
93
94
void FindInFiles::set_match_case(bool p_match_case) {
95
_match_case = p_match_case;
96
}
97
98
void FindInFiles::set_folder(const String &folder) {
99
_root_dir = folder;
100
}
101
102
void FindInFiles::set_filter(const HashSet<String> &exts) {
103
_extension_filter = exts;
104
}
105
106
void FindInFiles::set_includes(const HashSet<String> &p_include_wildcards) {
107
_include_wildcards = p_include_wildcards;
108
}
109
110
void FindInFiles::set_excludes(const HashSet<String> &p_exclude_wildcards) {
111
_exclude_wildcards = p_exclude_wildcards;
112
}
113
114
void FindInFiles::_notification(int p_what) {
115
switch (p_what) {
116
case NOTIFICATION_PROCESS: {
117
_process();
118
} break;
119
}
120
}
121
122
void FindInFiles::start() {
123
if (_pattern.is_empty()) {
124
print_verbose("Nothing to search, pattern is empty");
125
emit_signal(SceneStringName(finished));
126
return;
127
}
128
if (_extension_filter.is_empty()) {
129
print_verbose("Nothing to search, filter matches no files");
130
emit_signal(SceneStringName(finished));
131
return;
132
}
133
134
// Init search.
135
_current_dir = "";
136
PackedStringArray init_folder;
137
init_folder.push_back(_root_dir);
138
_folders_stack.clear();
139
_folders_stack.push_back(init_folder);
140
141
_initial_files_count = 0;
142
143
_searching = true;
144
set_process(true);
145
}
146
147
void FindInFiles::stop() {
148
_searching = false;
149
_current_dir = "";
150
set_process(false);
151
}
152
153
void FindInFiles::_process() {
154
// This part can be moved to a thread if needed.
155
156
OS &os = *OS::get_singleton();
157
uint64_t time_before = os.get_ticks_msec();
158
while (is_processing()) {
159
_iterate();
160
uint64_t elapsed = (os.get_ticks_msec() - time_before);
161
if (elapsed > 8) { // Process again after waiting 8 ticks.
162
break;
163
}
164
}
165
}
166
167
void FindInFiles::_iterate() {
168
if (_folders_stack.size() != 0) {
169
// Scan folders first so we can build a list of files and have progress info later.
170
171
PackedStringArray &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.path_join(folder_name);
180
181
PackedStringArray sub_dirs;
182
PackedStringArray files_to_scan;
183
_scan_dir("res://" + _current_dir, sub_dirs, files_to_scan);
184
185
_folders_stack.push_back(sub_dirs);
186
_files_to_scan.append_array(files_to_scan);
187
188
} else {
189
// Go back one level.
190
191
pop_back(_folders_stack);
192
_current_dir = _current_dir.get_base_dir();
193
194
if (_folders_stack.is_empty()) {
195
// All folders scanned.
196
_initial_files_count = _files_to_scan.size();
197
}
198
}
199
200
} else if (_files_to_scan.size() != 0) {
201
// Then scan files.
202
203
String fpath = _files_to_scan[_files_to_scan.size() - 1];
204
pop_back(_files_to_scan);
205
_scan_file(fpath);
206
207
} else {
208
print_verbose("Search complete");
209
set_process(false);
210
_current_dir = "";
211
_searching = false;
212
emit_signal(SceneStringName(finished));
213
}
214
}
215
216
float FindInFiles::get_progress() const {
217
if (_initial_files_count != 0) {
218
return static_cast<float>(_initial_files_count - _files_to_scan.size()) / static_cast<float>(_initial_files_count);
219
}
220
return 0;
221
}
222
223
void FindInFiles::_scan_dir(const String &path, PackedStringArray &out_folders, PackedStringArray &out_files_to_scan) {
224
Ref<DirAccess> dir = DirAccess::open(path);
225
if (dir.is_null()) {
226
print_verbose("Cannot open directory! " + path);
227
return;
228
}
229
230
dir->list_dir_begin();
231
232
// Limit to 100,000 iterations to avoid an infinite loop just in case
233
// (this technically limits results to 100,000 files per folder).
234
for (int i = 0; i < 100'000; ++i) {
235
String file = dir->get_next();
236
237
if (file.is_empty()) {
238
break;
239
}
240
241
// If there is a .gdignore file in the directory, clear all the files/folders
242
// to be searched on this path and skip searching the directory.
243
if (file == ".gdignore") {
244
out_folders.clear();
245
out_files_to_scan.clear();
246
break;
247
}
248
249
// Ignore special directories (such as those beginning with . and the project data directory).
250
String project_data_dir_name = ProjectSettings::get_singleton()->get_project_data_dir_name();
251
if (file.begins_with(".") || file == project_data_dir_name) {
252
continue;
253
}
254
if (dir->current_is_hidden()) {
255
continue;
256
}
257
258
if (dir->current_is_dir()) {
259
out_folders.push_back(file);
260
261
} else {
262
String file_ext = file.get_extension();
263
if (_extension_filter.has(file_ext)) {
264
String file_path = path.path_join(file);
265
bool case_sensitive = dir->is_case_sensitive(path);
266
267
if (!_exclude_wildcards.is_empty() && _is_file_matched(_exclude_wildcards, file_path, case_sensitive)) {
268
continue;
269
}
270
271
if (_include_wildcards.is_empty() || _is_file_matched(_include_wildcards, file_path, case_sensitive)) {
272
out_files_to_scan.push_back(file_path);
273
}
274
}
275
}
276
}
277
}
278
279
void FindInFiles::_scan_file(const String &fpath) {
280
Ref<FileAccess> f = FileAccess::open(fpath, FileAccess::READ);
281
if (f.is_null()) {
282
print_verbose(String("Cannot open file ") + fpath);
283
return;
284
}
285
286
int line_number = 0;
287
288
while (!f->eof_reached()) {
289
// Line number starts at 1.
290
++line_number;
291
292
int begin = 0;
293
int end = 0;
294
295
String line = f->get_line();
296
297
while (find_next(line, _pattern, end, _match_case, _whole_words, begin, end)) {
298
emit_signal(SNAME(SIGNAL_RESULT_FOUND), fpath, line_number, begin, end, line);
299
}
300
}
301
}
302
303
bool FindInFiles::_is_file_matched(const HashSet<String> &p_wildcards, const String &p_file_path, bool p_case_sensitive) const {
304
const String file_path = "/" + p_file_path.replace_char('\\', '/') + "/";
305
306
for (const String &wildcard : p_wildcards) {
307
if (p_case_sensitive && file_path.match(wildcard)) {
308
return true;
309
} else if (!p_case_sensitive && file_path.matchn(wildcard)) {
310
return true;
311
}
312
}
313
return false;
314
}
315
316
void FindInFiles::_bind_methods() {
317
ADD_SIGNAL(MethodInfo(SIGNAL_RESULT_FOUND,
318
PropertyInfo(Variant::STRING, "path"),
319
PropertyInfo(Variant::INT, "line_number"),
320
PropertyInfo(Variant::INT, "begin"),
321
PropertyInfo(Variant::INT, "end"),
322
PropertyInfo(Variant::STRING, "text")));
323
324
ADD_SIGNAL(MethodInfo("finished"));
325
}
326
327
//-----------------------------------------------------------------------------
328
const char *FindInFilesDialog::SIGNAL_FIND_REQUESTED = "find_requested";
329
const char *FindInFilesDialog::SIGNAL_REPLACE_REQUESTED = "replace_requested";
330
331
FindInFilesDialog::FindInFilesDialog() {
332
set_min_size(Size2(500 * EDSCALE, 0));
333
set_title(TTRC("Find in Files"));
334
335
VBoxContainer *vbc = memnew(VBoxContainer);
336
vbc->set_anchor_and_offset(SIDE_LEFT, Control::ANCHOR_BEGIN, 8 * EDSCALE);
337
vbc->set_anchor_and_offset(SIDE_TOP, Control::ANCHOR_BEGIN, 8 * EDSCALE);
338
vbc->set_anchor_and_offset(SIDE_RIGHT, Control::ANCHOR_END, -8 * EDSCALE);
339
vbc->set_anchor_and_offset(SIDE_BOTTOM, Control::ANCHOR_END, -8 * EDSCALE);
340
add_child(vbc);
341
342
GridContainer *gc = memnew(GridContainer);
343
gc->set_columns(2);
344
vbc->add_child(gc);
345
346
Label *find_label = memnew(Label);
347
find_label->set_text(TTRC("Find:"));
348
gc->add_child(find_label);
349
350
_search_text_line_edit = memnew(LineEdit);
351
_search_text_line_edit->set_h_size_flags(Control::SIZE_EXPAND_FILL);
352
_search_text_line_edit->set_accessibility_name(TTRC("Find:"));
353
_search_text_line_edit->connect(SceneStringName(text_changed), callable_mp(this, &FindInFilesDialog::_on_search_text_modified));
354
_search_text_line_edit->connect(SceneStringName(text_submitted), callable_mp(this, &FindInFilesDialog::_on_search_text_submitted));
355
gc->add_child(_search_text_line_edit);
356
357
_replace_label = memnew(Label);
358
_replace_label->set_text(TTRC("Replace:"));
359
_replace_label->hide();
360
gc->add_child(_replace_label);
361
362
_replace_text_line_edit = memnew(LineEdit);
363
_replace_text_line_edit->set_h_size_flags(Control::SIZE_EXPAND_FILL);
364
_replace_text_line_edit->set_accessibility_name(TTRC("Replace:"));
365
_replace_text_line_edit->connect(SceneStringName(text_submitted), callable_mp(this, &FindInFilesDialog::_on_replace_text_submitted));
366
_replace_text_line_edit->hide();
367
gc->add_child(_replace_text_line_edit);
368
369
gc->add_child(memnew(Control)); // Space to maintain the grid alignment.
370
371
{
372
HBoxContainer *hbc = memnew(HBoxContainer);
373
374
_whole_words_checkbox = memnew(CheckBox);
375
_whole_words_checkbox->set_text(TTRC("Whole Words"));
376
hbc->add_child(_whole_words_checkbox);
377
378
_match_case_checkbox = memnew(CheckBox);
379
_match_case_checkbox->set_text(TTRC("Match Case"));
380
hbc->add_child(_match_case_checkbox);
381
382
gc->add_child(hbc);
383
}
384
385
Label *folder_label = memnew(Label);
386
folder_label->set_text(TTRC("Folder:"));
387
gc->add_child(folder_label);
388
389
{
390
HBoxContainer *hbc = memnew(HBoxContainer);
391
392
Label *prefix_label = memnew(Label);
393
prefix_label->set_text("res://");
394
prefix_label->set_auto_translate_mode(AUTO_TRANSLATE_MODE_DISABLED);
395
hbc->add_child(prefix_label);
396
397
_folder_line_edit = memnew(LineEdit);
398
_folder_line_edit->set_h_size_flags(Control::SIZE_EXPAND_FILL);
399
_folder_line_edit->connect(SceneStringName(text_submitted), callable_mp(this, &FindInFilesDialog::_on_search_text_submitted));
400
_folder_line_edit->set_accessibility_name(TTRC("Folder:"));
401
hbc->add_child(_folder_line_edit);
402
403
Button *folder_button = memnew(Button);
404
folder_button->set_accessibility_name(TTRC("Select Folder"));
405
folder_button->set_text("...");
406
folder_button->connect(SceneStringName(pressed), callable_mp(this, &FindInFilesDialog::_on_folder_button_pressed));
407
hbc->add_child(folder_button);
408
409
_folder_dialog = memnew(FileDialog);
410
_folder_dialog->set_file_mode(FileDialog::FILE_MODE_OPEN_DIR);
411
_folder_dialog->connect("dir_selected", callable_mp(this, &FindInFilesDialog::_on_folder_selected));
412
add_child(_folder_dialog);
413
414
gc->add_child(hbc);
415
}
416
417
Label *includes_label = memnew(Label);
418
includes_label->set_text(TTRC("Includes:"));
419
includes_label->set_tooltip_text(TTRC("Include the files with the following expressions. Use \",\" to separate."));
420
includes_label->set_mouse_filter(Control::MOUSE_FILTER_PASS);
421
gc->add_child(includes_label);
422
423
_includes_line_edit = memnew(LineEdit);
424
_includes_line_edit->set_h_size_flags(Control::SIZE_EXPAND_FILL);
425
_includes_line_edit->set_placeholder(TTRC("example: scripts,scenes/*/test.gd"));
426
_includes_line_edit->set_accessibility_name(TTRC("Includes:"));
427
_includes_line_edit->connect(SceneStringName(text_submitted), callable_mp(this, &FindInFilesDialog::_on_search_text_submitted));
428
gc->add_child(_includes_line_edit);
429
430
Label *excludes_label = memnew(Label);
431
excludes_label->set_text(TTRC("Excludes:"));
432
excludes_label->set_tooltip_text(TTRC("Exclude the files with the following expressions. Use \",\" to separate."));
433
excludes_label->set_mouse_filter(Control::MOUSE_FILTER_PASS);
434
gc->add_child(excludes_label);
435
436
_excludes_line_edit = memnew(LineEdit);
437
_excludes_line_edit->set_h_size_flags(Control::SIZE_EXPAND_FILL);
438
_excludes_line_edit->set_placeholder(TTRC("example: res://addons,scenes/test/*.gd"));
439
_excludes_line_edit->set_accessibility_name(TTRC("Excludes:"));
440
_excludes_line_edit->connect(SceneStringName(text_submitted), callable_mp(this, &FindInFilesDialog::_on_search_text_submitted));
441
gc->add_child(_excludes_line_edit);
442
443
Label *filter_label = memnew(Label);
444
filter_label->set_text(TTRC("Filters:"));
445
filter_label->set_tooltip_text(TTRC("Include the files with the following extensions. Add or remove them in ProjectSettings."));
446
filter_label->set_mouse_filter(Control::MOUSE_FILTER_PASS);
447
gc->add_child(filter_label);
448
449
_filters_container = memnew(HBoxContainer);
450
gc->add_child(_filters_container);
451
452
_find_button = add_button(TTRC("Find..."), false, "find");
453
_find_button->set_disabled(true);
454
455
_replace_button = add_button(TTRC("Replace..."), false, "replace");
456
_replace_button->set_disabled(true);
457
458
Button *cancel_button = get_ok_button();
459
cancel_button->set_text(TTRC("Cancel"));
460
461
_mode = SEARCH_MODE;
462
}
463
464
void FindInFilesDialog::set_search_text(const String &text) {
465
if (_mode == SEARCH_MODE) {
466
if (!text.is_empty()) {
467
_search_text_line_edit->set_text(text);
468
_on_search_text_modified(text);
469
}
470
callable_mp((Control *)_search_text_line_edit, &Control::grab_focus).call_deferred();
471
_search_text_line_edit->select_all();
472
} else if (_mode == REPLACE_MODE) {
473
if (!text.is_empty()) {
474
_search_text_line_edit->set_text(text);
475
callable_mp((Control *)_replace_text_line_edit, &Control::grab_focus).call_deferred();
476
_replace_text_line_edit->select_all();
477
_on_search_text_modified(text);
478
} else {
479
callable_mp((Control *)_search_text_line_edit, &Control::grab_focus).call_deferred();
480
_search_text_line_edit->select_all();
481
}
482
}
483
}
484
485
void FindInFilesDialog::set_replace_text(const String &text) {
486
_replace_text_line_edit->set_text(text);
487
}
488
489
void FindInFilesDialog::set_find_in_files_mode(FindInFilesMode p_mode) {
490
if (_mode == p_mode) {
491
return;
492
}
493
494
_mode = p_mode;
495
496
if (p_mode == SEARCH_MODE) {
497
set_title(TTRC("Find in Files"));
498
_replace_label->hide();
499
_replace_text_line_edit->hide();
500
} else if (p_mode == REPLACE_MODE) {
501
set_title(TTRC("Replace in Files"));
502
_replace_label->show();
503
_replace_text_line_edit->show();
504
}
505
506
// Recalculate the dialog size after hiding child controls.
507
set_size(Size2(get_size().x, 0));
508
}
509
510
String FindInFilesDialog::get_search_text() const {
511
return _search_text_line_edit->get_text();
512
}
513
514
String FindInFilesDialog::get_replace_text() const {
515
return _replace_text_line_edit->get_text();
516
}
517
518
bool FindInFilesDialog::is_match_case() const {
519
return _match_case_checkbox->is_pressed();
520
}
521
522
bool FindInFilesDialog::is_whole_words() const {
523
return _whole_words_checkbox->is_pressed();
524
}
525
526
String FindInFilesDialog::get_folder() const {
527
String text = _folder_line_edit->get_text();
528
return text.strip_edges();
529
}
530
531
HashSet<String> FindInFilesDialog::get_filter() const {
532
// Could check the _filters_preferences but it might not have been generated yet.
533
HashSet<String> filters;
534
for (int i = 0; i < _filters_container->get_child_count(); ++i) {
535
CheckBox *cb = static_cast<CheckBox *>(_filters_container->get_child(i));
536
if (cb->is_pressed()) {
537
filters.insert(cb->get_text());
538
}
539
}
540
return filters;
541
}
542
543
HashSet<String> FindInFilesDialog::get_includes() const {
544
HashSet<String> includes;
545
String text = _includes_line_edit->get_text();
546
547
if (text.is_empty()) {
548
return includes;
549
}
550
551
PackedStringArray wildcards = text.split(",", false);
552
for (const String &wildcard : wildcards) {
553
includes.insert(validate_filter_wildcard(wildcard));
554
}
555
return includes;
556
}
557
558
HashSet<String> FindInFilesDialog::get_excludes() const {
559
HashSet<String> excludes;
560
String text = _excludes_line_edit->get_text();
561
562
if (text.is_empty()) {
563
return excludes;
564
}
565
566
PackedStringArray wildcards = text.split(",", false);
567
for (const String &wildcard : wildcards) {
568
excludes.insert(validate_filter_wildcard(wildcard));
569
}
570
return excludes;
571
}
572
573
void FindInFilesDialog::_notification(int p_what) {
574
switch (p_what) {
575
case NOTIFICATION_VISIBILITY_CHANGED: {
576
if (is_visible()) {
577
// Extensions might have changed in the meantime, we clean them and instance them again.
578
for (int i = 0; i < _filters_container->get_child_count(); i++) {
579
_filters_container->get_child(i)->queue_free();
580
}
581
Array exts = GLOBAL_GET("editor/script/search_in_file_extensions");
582
for (int i = 0; i < exts.size(); ++i) {
583
CheckBox *cb = memnew(CheckBox);
584
cb->set_text(exts[i]);
585
if (!_filters_preferences.has(exts[i])) {
586
_filters_preferences[exts[i]] = true;
587
}
588
cb->set_pressed(_filters_preferences[exts[i]]);
589
_filters_container->add_child(cb);
590
}
591
}
592
} break;
593
}
594
}
595
596
void FindInFilesDialog::_on_folder_button_pressed() {
597
_folder_dialog->popup_file_dialog();
598
}
599
600
void FindInFilesDialog::custom_action(const String &p_action) {
601
for (int i = 0; i < _filters_container->get_child_count(); ++i) {
602
CheckBox *cb = static_cast<CheckBox *>(_filters_container->get_child(i));
603
_filters_preferences[cb->get_text()] = cb->is_pressed();
604
}
605
606
if (p_action == "find") {
607
emit_signal(SNAME(SIGNAL_FIND_REQUESTED));
608
hide();
609
} else if (p_action == "replace") {
610
emit_signal(SNAME(SIGNAL_REPLACE_REQUESTED));
611
hide();
612
}
613
}
614
615
void FindInFilesDialog::_on_search_text_modified(const String &text) {
616
ERR_FAIL_NULL(_find_button);
617
ERR_FAIL_NULL(_replace_button);
618
619
_find_button->set_disabled(get_search_text().is_empty());
620
_replace_button->set_disabled(get_search_text().is_empty());
621
}
622
623
void FindInFilesDialog::_on_search_text_submitted(const String &text) {
624
// This allows to trigger a global search without leaving the keyboard.
625
if (!_find_button->is_disabled()) {
626
if (_mode == SEARCH_MODE) {
627
custom_action("find");
628
}
629
}
630
631
if (!_replace_button->is_disabled()) {
632
if (_mode == REPLACE_MODE) {
633
custom_action("replace");
634
}
635
}
636
}
637
638
void FindInFilesDialog::_on_replace_text_submitted(const String &text) {
639
// This allows to trigger a global search without leaving the keyboard.
640
if (!_replace_button->is_disabled()) {
641
if (_mode == REPLACE_MODE) {
642
custom_action("replace");
643
}
644
}
645
}
646
647
void FindInFilesDialog::_on_folder_selected(String path) {
648
int i = path.find("://");
649
if (i != -1) {
650
path = path.substr(i + 3);
651
}
652
_folder_line_edit->set_text(path);
653
}
654
655
String FindInFilesDialog::validate_filter_wildcard(const String &p_expression) const {
656
String ret = p_expression.replace_char('\\', '/');
657
if (ret.begins_with("./")) {
658
// Relative to the project root.
659
ret = "res://" + ret.trim_prefix("./");
660
}
661
662
if (ret.begins_with(".")) {
663
// To match extension.
664
ret = "*" + ret;
665
}
666
667
if (!ret.begins_with("*")) {
668
ret = "*/" + ret.trim_prefix("/");
669
}
670
671
if (!ret.ends_with("*")) {
672
ret = ret.trim_suffix("/") + "/*";
673
}
674
675
return ret;
676
}
677
678
void FindInFilesDialog::_bind_methods() {
679
ADD_SIGNAL(MethodInfo(SIGNAL_FIND_REQUESTED));
680
ADD_SIGNAL(MethodInfo(SIGNAL_REPLACE_REQUESTED));
681
}
682
683
//-----------------------------------------------------------------------------
684
const char *FindInFilesPanel::SIGNAL_RESULT_SELECTED = "result_selected";
685
const char *FindInFilesPanel::SIGNAL_FILES_MODIFIED = "files_modified";
686
const char *FindInFilesPanel::SIGNAL_CLOSE_BUTTON_CLICKED = "close_button_clicked";
687
688
FindInFilesPanel::FindInFilesPanel() {
689
_finder = memnew(FindInFiles);
690
_finder->connect(FindInFiles::SIGNAL_RESULT_FOUND, callable_mp(this, &FindInFilesPanel::_on_result_found));
691
_finder->connect(SceneStringName(finished), callable_mp(this, &FindInFilesPanel::_on_finished));
692
add_child(_finder);
693
694
VBoxContainer *vbc = memnew(VBoxContainer);
695
vbc->set_anchor_and_offset(SIDE_LEFT, ANCHOR_BEGIN, 0);
696
vbc->set_anchor_and_offset(SIDE_TOP, ANCHOR_BEGIN, 0);
697
vbc->set_anchor_and_offset(SIDE_RIGHT, ANCHOR_END, 0);
698
vbc->set_anchor_and_offset(SIDE_BOTTOM, ANCHOR_END, 0);
699
add_child(vbc);
700
701
{
702
HBoxContainer *hbc = memnew(HBoxContainer);
703
704
Label *find_label = memnew(Label);
705
find_label->set_text(TTRC("Find:"));
706
hbc->add_child(find_label);
707
708
_search_text_label = memnew(Label);
709
_search_text_label->set_text_overrun_behavior(TextServer::OVERRUN_TRIM_ELLIPSIS);
710
_search_text_label->set_h_size_flags(Control::SIZE_EXPAND_FILL);
711
_search_text_label->set_focus_mode(FOCUS_ACCESSIBILITY);
712
_search_text_label->set_mouse_filter(Control::MOUSE_FILTER_PASS);
713
_search_text_label->set_auto_translate_mode(AUTO_TRANSLATE_MODE_DISABLED);
714
hbc->add_child(_search_text_label);
715
716
_progress_bar = memnew(ProgressBar);
717
_progress_bar->set_h_size_flags(SIZE_EXPAND_FILL);
718
_progress_bar->set_v_size_flags(SIZE_SHRINK_CENTER);
719
_progress_bar->set_stretch_ratio(2.0);
720
_progress_bar->set_visible(false);
721
hbc->add_child(_progress_bar);
722
723
_status_label = memnew(Label);
724
_status_label->set_focus_mode(FOCUS_ACCESSIBILITY);
725
hbc->add_child(_status_label);
726
727
_refresh_button = memnew(Button);
728
_refresh_button->set_text(TTRC("Refresh"));
729
_refresh_button->connect(SceneStringName(pressed), callable_mp(this, &FindInFilesPanel::_on_refresh_button_clicked));
730
_refresh_button->hide();
731
hbc->add_child(_refresh_button);
732
733
_cancel_button = memnew(Button);
734
_cancel_button->set_text(TTRC("Cancel"));
735
_cancel_button->connect(SceneStringName(pressed), callable_mp(this, &FindInFilesPanel::_on_cancel_button_clicked));
736
_cancel_button->hide();
737
hbc->add_child(_cancel_button);
738
739
_close_button = memnew(Button);
740
_close_button->set_text(TTRC("Close"));
741
_close_button->connect(SceneStringName(pressed), callable_mp(this, &FindInFilesPanel::_on_close_button_clicked));
742
hbc->add_child(_close_button);
743
744
vbc->add_child(hbc);
745
}
746
747
_results_display = memnew(Tree);
748
_results_display->set_accessibility_name(TTRC("Search Results"));
749
_results_display->set_auto_translate_mode(AUTO_TRANSLATE_MODE_DISABLED);
750
_results_display->set_v_size_flags(SIZE_EXPAND_FILL);
751
_results_display->connect(SceneStringName(item_selected), callable_mp(this, &FindInFilesPanel::_on_result_selected));
752
_results_display->connect("item_edited", callable_mp(this, &FindInFilesPanel::_on_item_edited));
753
_results_display->connect("button_clicked", callable_mp(this, &FindInFilesPanel::_on_button_clicked));
754
_results_display->set_hide_root(true);
755
_results_display->set_select_mode(Tree::SELECT_ROW);
756
_results_display->set_allow_rmb_select(true);
757
_results_display->set_allow_reselect(true);
758
_results_display->add_theme_constant_override("inner_item_margin_left", 0);
759
_results_display->add_theme_constant_override("inner_item_margin_right", 0);
760
_results_display->create_item(); // Root
761
vbc->add_child(_results_display);
762
763
{
764
_replace_container = memnew(HBoxContainer);
765
766
Label *replace_label = memnew(Label);
767
replace_label->set_text(TTRC("Replace:"));
768
_replace_container->add_child(replace_label);
769
770
_replace_line_edit = memnew(LineEdit);
771
_replace_line_edit->set_accessibility_name(TTRC("Replace:"));
772
_replace_line_edit->set_h_size_flags(SIZE_EXPAND_FILL);
773
_replace_line_edit->connect(SceneStringName(text_changed), callable_mp(this, &FindInFilesPanel::_on_replace_text_changed));
774
_replace_container->add_child(_replace_line_edit);
775
776
_replace_all_button = memnew(Button);
777
_replace_all_button->set_text(TTRC("Replace all (no undo)"));
778
_replace_all_button->connect(SceneStringName(pressed), callable_mp(this, &FindInFilesPanel::_on_replace_all_clicked));
779
_replace_container->add_child(_replace_all_button);
780
781
_replace_container->hide();
782
783
vbc->add_child(_replace_container);
784
}
785
}
786
787
void FindInFilesPanel::set_with_replace(bool with_replace) {
788
_with_replace = with_replace;
789
_replace_container->set_visible(with_replace);
790
791
if (with_replace) {
792
// Results show checkboxes on their left so they can be opted out.
793
_results_display->set_columns(2);
794
_results_display->set_column_expand(0, false);
795
_results_display->set_column_custom_minimum_width(0, 48 * EDSCALE);
796
} else {
797
// Results are single-cell items.
798
_results_display->set_column_expand(0, true);
799
_results_display->set_columns(1);
800
}
801
}
802
803
void FindInFilesPanel::set_replace_text(const String &text) {
804
_replace_line_edit->set_text(text);
805
}
806
807
void FindInFilesPanel::clear() {
808
_file_items.clear();
809
_result_items.clear();
810
_results_display->clear();
811
_results_display->create_item(); // Root
812
}
813
814
void FindInFilesPanel::start_search() {
815
clear();
816
817
_status_label->set_text(TTRC("Searching..."));
818
_search_text_label->set_text(_finder->get_search_text());
819
_search_text_label->set_tooltip_text(_finder->get_search_text());
820
821
int label_min_width = _search_text_label->get_minimum_size().x + _search_text_label->get_character_bounds(0).size.x;
822
_search_text_label->set_custom_minimum_size(Size2(label_min_width, 0));
823
824
set_process(true);
825
_progress_bar->set_visible(true);
826
827
_finder->start();
828
829
update_replace_buttons();
830
_refresh_button->hide();
831
_cancel_button->show();
832
}
833
834
void FindInFilesPanel::stop_search() {
835
_finder->stop();
836
837
_status_label->set_text("");
838
update_replace_buttons();
839
_progress_bar->set_visible(false);
840
_refresh_button->show();
841
_cancel_button->hide();
842
}
843
844
void FindInFilesPanel::_notification(int p_what) {
845
switch (p_what) {
846
case NOTIFICATION_THEME_CHANGED: {
847
_search_text_label->add_theme_font_override(SceneStringName(font), get_theme_font(SNAME("source"), EditorStringName(EditorFonts)));
848
_search_text_label->add_theme_font_size_override(SceneStringName(font_size), get_theme_font_size(SNAME("source_size"), EditorStringName(EditorFonts)));
849
_results_display->add_theme_font_override(SceneStringName(font), get_theme_font(SNAME("source"), EditorStringName(EditorFonts)));
850
_results_display->add_theme_font_size_override(SceneStringName(font_size), get_theme_font_size(SNAME("source_size"), EditorStringName(EditorFonts)));
851
852
// Rebuild search tree.
853
if (!_finder->get_search_text().is_empty()) {
854
start_search();
855
}
856
} break;
857
case NOTIFICATION_TRANSLATION_CHANGED: {
858
update_matches_text();
859
860
TreeItem *file_item = _results_display->get_root()->get_first_child();
861
while (file_item) {
862
file_item->set_button_tooltip_text(0, 0, TTR("Remove result"));
863
864
TreeItem *result_item = file_item->get_first_child();
865
while (result_item) {
866
result_item->set_button_tooltip_text(_with_replace ? 1 : 0, 0, TTR("Remove result"));
867
result_item = result_item->get_next();
868
}
869
870
file_item = file_item->get_next();
871
}
872
} break;
873
case NOTIFICATION_PROCESS: {
874
_progress_bar->set_as_ratio(_finder->get_progress());
875
} break;
876
}
877
}
878
879
void FindInFilesPanel::_on_result_found(const String &fpath, int line_number, int begin, int end, String text) {
880
TreeItem *file_item;
881
Ref<Texture2D> remove_texture = get_editor_theme_icon(SNAME("Close"));
882
883
HashMap<String, TreeItem *>::Iterator E = _file_items.find(fpath);
884
if (!E) {
885
file_item = _results_display->create_item();
886
file_item->set_text(0, fpath);
887
file_item->set_metadata(0, fpath);
888
file_item->add_button(0, remove_texture, 0, false, TTR("Remove result"));
889
890
// The width of this column is restrained to checkboxes,
891
// but that doesn't make sense for the parent items,
892
// so we override their width so they can expand to full width.
893
file_item->set_expand_right(0, true);
894
895
_file_items[fpath] = file_item;
896
} else {
897
file_item = E->value;
898
}
899
900
Color file_item_color = _results_display->get_theme_color(SceneStringName(font_color)) * Color(1, 1, 1, 0.67);
901
file_item->set_custom_color(0, file_item_color);
902
file_item->set_selectable(0, false);
903
904
int text_index = _with_replace ? 1 : 0;
905
906
TreeItem *item = _results_display->create_item(file_item);
907
908
// Do this first because it resets properties of the cell...
909
item->set_cell_mode(text_index, TreeItem::CELL_MODE_CUSTOM);
910
911
// Trim result item line.
912
int old_text_size = text.size();
913
text = text.strip_edges(true, false);
914
int chars_removed = old_text_size - text.size();
915
String start = vformat("%3s: ", line_number);
916
917
item->set_text(text_index, start + text);
918
item->set_custom_draw_callback(text_index, callable_mp(this, &FindInFilesPanel::draw_result_text));
919
920
Result r;
921
r.line_number = line_number;
922
r.begin = begin;
923
r.end = end;
924
r.begin_trimmed = begin - chars_removed + start.size() - 1;
925
_result_items[item] = r;
926
927
if (_with_replace) {
928
item->set_cell_mode(0, TreeItem::CELL_MODE_CHECK);
929
item->set_checked(0, true);
930
item->set_editable(0, true);
931
item->add_button(1, remove_texture, 0, false, TTR("Remove result"));
932
} else {
933
item->add_button(0, remove_texture, 0, false, TTR("Remove result"));
934
}
935
}
936
937
void FindInFilesPanel::draw_result_text(Object *item_obj, Rect2 rect) {
938
TreeItem *item = Object::cast_to<TreeItem>(item_obj);
939
if (!item) {
940
return;
941
}
942
943
HashMap<TreeItem *, Result>::Iterator E = _result_items.find(item);
944
if (!E) {
945
return;
946
}
947
Result r = E->value;
948
String item_text = item->get_text(_with_replace ? 1 : 0);
949
Ref<Font> font = _results_display->get_theme_font(SceneStringName(font));
950
int font_size = _results_display->get_theme_font_size(SceneStringName(font_size));
951
952
Rect2 match_rect = rect;
953
match_rect.position.x += font->get_string_size(item_text.left(r.begin_trimmed), HORIZONTAL_ALIGNMENT_LEFT, -1, font_size).x - 1;
954
match_rect.size.x = font->get_string_size(_search_text_label->get_text(), HORIZONTAL_ALIGNMENT_LEFT, -1, font_size).x + 1;
955
match_rect.position.y += 1 * EDSCALE;
956
match_rect.size.y -= 2 * EDSCALE;
957
958
_results_display->draw_rect(match_rect, get_theme_color(SNAME("accent_color"), EditorStringName(Editor)) * Color(1, 1, 1, 0.33), false, 2.0);
959
_results_display->draw_rect(match_rect, get_theme_color(SNAME("accent_color"), EditorStringName(Editor)) * Color(1, 1, 1, 0.17), true);
960
961
// Text is drawn by Tree already.
962
}
963
964
void FindInFilesPanel::_on_item_edited() {
965
TreeItem *item = _results_display->get_selected();
966
967
// Change opacity to half if checkbox is checked, otherwise full.
968
Color use_color = _results_display->get_theme_color(SceneStringName(font_color));
969
if (!item->is_checked(0)) {
970
use_color.a *= 0.5;
971
}
972
item->set_custom_color(1, use_color);
973
}
974
975
void FindInFilesPanel::_on_finished() {
976
update_matches_text();
977
update_replace_buttons();
978
_progress_bar->set_visible(false);
979
_refresh_button->show();
980
_cancel_button->hide();
981
}
982
983
void FindInFilesPanel::_on_refresh_button_clicked() {
984
start_search();
985
}
986
987
void FindInFilesPanel::_on_cancel_button_clicked() {
988
stop_search();
989
}
990
991
void FindInFilesPanel::_on_close_button_clicked() {
992
emit_signal(SNAME(SIGNAL_CLOSE_BUTTON_CLICKED));
993
}
994
995
void FindInFilesPanel::_on_result_selected() {
996
TreeItem *item = _results_display->get_selected();
997
HashMap<TreeItem *, Result>::Iterator E = _result_items.find(item);
998
999
if (!E) {
1000
return;
1001
}
1002
Result r = E->value;
1003
1004
TreeItem *file_item = item->get_parent();
1005
String fpath = file_item->get_metadata(0);
1006
1007
emit_signal(SNAME(SIGNAL_RESULT_SELECTED), fpath, r.line_number, r.begin, r.end);
1008
}
1009
1010
void FindInFilesPanel::_on_replace_text_changed(const String &text) {
1011
update_replace_buttons();
1012
}
1013
1014
void FindInFilesPanel::_on_replace_all_clicked() {
1015
String replace_text = get_replace_text();
1016
1017
PackedStringArray modified_files;
1018
1019
for (KeyValue<String, TreeItem *> &E : _file_items) {
1020
TreeItem *file_item = E.value;
1021
String fpath = file_item->get_metadata(0);
1022
1023
Vector<Result> locations;
1024
for (TreeItem *item = file_item->get_first_child(); item; item = item->get_next()) {
1025
if (!item->is_checked(0)) {
1026
continue;
1027
}
1028
1029
HashMap<TreeItem *, Result>::Iterator F = _result_items.find(item);
1030
ERR_FAIL_COND(!F);
1031
locations.push_back(F->value);
1032
}
1033
1034
if (locations.size() != 0) {
1035
// Results are sorted by file, so we can batch replaces.
1036
apply_replaces_in_file(fpath, locations, replace_text);
1037
modified_files.push_back(fpath);
1038
}
1039
}
1040
1041
// Hide replace bar so we can't trigger the action twice without doing a new search.
1042
_replace_container->hide();
1043
1044
emit_signal(SNAME(SIGNAL_FILES_MODIFIED), modified_files);
1045
}
1046
1047
void FindInFilesPanel::_on_button_clicked(TreeItem *p_item, int p_column, int p_id, int p_mouse_button_index) {
1048
const String file_path = p_item->get_text(0);
1049
1050
_result_items.erase(p_item);
1051
if (_file_items.find(file_path)) {
1052
TreeItem *file_result = _file_items.get(file_path);
1053
int match_count = file_result->get_child_count();
1054
1055
for (int i = 0; i < match_count; i++) {
1056
TreeItem *child_item = file_result->get_child(i);
1057
_result_items.erase(child_item);
1058
}
1059
1060
file_result->clear_children();
1061
_file_items.erase(file_path);
1062
}
1063
1064
TreeItem *item_parent = p_item->get_parent();
1065
if (item_parent && item_parent->get_child_count() < 2) {
1066
_file_items.erase(item_parent->get_text(0));
1067
get_tree()->queue_delete(item_parent);
1068
}
1069
get_tree()->queue_delete(p_item);
1070
update_matches_text();
1071
}
1072
1073
// Same as get_line, but preserves line ending characters.
1074
class ConservativeGetLine {
1075
public:
1076
String get_line(Ref<FileAccess> f) {
1077
_line_buffer.clear();
1078
1079
char32_t c = f->get_8();
1080
1081
while (!f->eof_reached()) {
1082
if (c == '\n') {
1083
_line_buffer.push_back(c);
1084
_line_buffer.push_back(0);
1085
return String::utf8(_line_buffer.ptr());
1086
1087
} else if (c == '\0') {
1088
_line_buffer.push_back(c);
1089
return String::utf8(_line_buffer.ptr());
1090
1091
} else if (c != '\r') {
1092
_line_buffer.push_back(c);
1093
}
1094
1095
c = f->get_8();
1096
}
1097
1098
_line_buffer.push_back(0);
1099
return String::utf8(_line_buffer.ptr());
1100
}
1101
1102
private:
1103
Vector<char> _line_buffer;
1104
};
1105
1106
void FindInFilesPanel::apply_replaces_in_file(const String &fpath, const Vector<Result> &locations, const String &new_text) {
1107
// If the file is already open, I assume the editor will reload it.
1108
// If there are unsaved changes, the user will be asked on focus,
1109
// however that means either losing changes or losing replaces.
1110
1111
Ref<FileAccess> f = FileAccess::open(fpath, FileAccess::READ);
1112
ERR_FAIL_COND_MSG(f.is_null(), "Cannot open file from path '" + fpath + "'.");
1113
1114
String buffer;
1115
int current_line = 1;
1116
1117
ConservativeGetLine conservative;
1118
1119
String line = conservative.get_line(f);
1120
String search_text = _finder->get_search_text();
1121
1122
int offset = 0;
1123
1124
for (int i = 0; i < locations.size(); ++i) {
1125
int repl_line_number = locations[i].line_number;
1126
1127
while (current_line < repl_line_number) {
1128
buffer += line;
1129
line = conservative.get_line(f);
1130
++current_line;
1131
offset = 0;
1132
}
1133
1134
int repl_begin = locations[i].begin + offset;
1135
int repl_end = locations[i].end + offset;
1136
1137
int _;
1138
if (!find_next(line, search_text, repl_begin, _finder->is_match_case(), _finder->is_whole_words(), _, _)) {
1139
// Make sure the replace is still valid in case the file was tampered with.
1140
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)));
1141
continue;
1142
}
1143
1144
line = line.left(repl_begin) + new_text + line.substr(repl_end);
1145
// Keep an offset in case there are successive replaces in the same line.
1146
offset += new_text.length() - (repl_end - repl_begin);
1147
}
1148
1149
buffer += line;
1150
1151
while (!f->eof_reached()) {
1152
buffer += conservative.get_line(f);
1153
}
1154
1155
// Now the modified contents are in the buffer, rewrite the file with our changes.
1156
1157
Error err = f->reopen(fpath, FileAccess::WRITE);
1158
ERR_FAIL_COND_MSG(err != OK, "Cannot create file in path '" + fpath + "'.");
1159
1160
f->store_string(buffer);
1161
}
1162
1163
String FindInFilesPanel::get_replace_text() {
1164
return _replace_line_edit->get_text();
1165
}
1166
1167
void FindInFilesPanel::update_replace_buttons() {
1168
bool disabled = _finder->is_searching();
1169
1170
_replace_all_button->set_disabled(disabled);
1171
}
1172
1173
void FindInFilesPanel::update_matches_text() {
1174
String results_text;
1175
int result_count = _result_items.size();
1176
int file_count = _file_items.size();
1177
1178
if (result_count == 1 && file_count == 1) {
1179
results_text = vformat(TTR("%d match in %d file"), result_count, file_count);
1180
} else if (result_count != 1 && file_count == 1) {
1181
results_text = vformat(TTR("%d matches in %d file"), result_count, file_count);
1182
} else {
1183
results_text = vformat(TTR("%d matches in %d files"), result_count, file_count);
1184
}
1185
1186
_status_label->set_text(results_text);
1187
}
1188
1189
void FindInFilesPanel::_bind_methods() {
1190
ClassDB::bind_method("_on_result_found", &FindInFilesPanel::_on_result_found);
1191
ClassDB::bind_method("_on_finished", &FindInFilesPanel::_on_finished);
1192
1193
ADD_SIGNAL(MethodInfo(SIGNAL_RESULT_SELECTED,
1194
PropertyInfo(Variant::STRING, "path"),
1195
PropertyInfo(Variant::INT, "line_number"),
1196
PropertyInfo(Variant::INT, "begin"),
1197
PropertyInfo(Variant::INT, "end")));
1198
1199
ADD_SIGNAL(MethodInfo(SIGNAL_FILES_MODIFIED, PropertyInfo(Variant::STRING, "paths")));
1200
1201
ADD_SIGNAL(MethodInfo(SIGNAL_CLOSE_BUTTON_CLICKED));
1202
}
1203
1204