find_in_files.cpp 50 KB

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