find_in_files.cpp 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063
  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/themes/editor_scale.h"
  37. #include "scene/gui/box_container.h"
  38. #include "scene/gui/button.h"
  39. #include "scene/gui/check_box.h"
  40. #include "scene/gui/file_dialog.h"
  41. #include "scene/gui/grid_container.h"
  42. #include "scene/gui/label.h"
  43. #include "scene/gui/line_edit.h"
  44. #include "scene/gui/progress_bar.h"
  45. #include "scene/gui/tree.h"
  46. const char *FindInFiles::SIGNAL_RESULT_FOUND = "result_found";
  47. // TODO: Would be nice in Vector and Vectors.
  48. template <typename T>
  49. inline void pop_back(T &container) {
  50. container.resize(container.size() - 1);
  51. }
  52. static bool find_next(const String &line, const String &pattern, int from, bool match_case, bool whole_words, int &out_begin, int &out_end) {
  53. int end = from;
  54. while (true) {
  55. int begin = match_case ? line.find(pattern, end) : line.findn(pattern, end);
  56. if (begin == -1) {
  57. return false;
  58. }
  59. end = begin + pattern.length();
  60. out_begin = begin;
  61. out_end = end;
  62. if (whole_words) {
  63. if (begin > 0 && (is_ascii_identifier_char(line[begin - 1]))) {
  64. continue;
  65. }
  66. if (end < line.size() && (is_ascii_identifier_char(line[end]))) {
  67. continue;
  68. }
  69. }
  70. return true;
  71. }
  72. }
  73. //--------------------------------------------------------------------------------
  74. void FindInFiles::set_search_text(const String &p_pattern) {
  75. _pattern = p_pattern;
  76. }
  77. void FindInFiles::set_whole_words(bool p_whole_word) {
  78. _whole_words = p_whole_word;
  79. }
  80. void FindInFiles::set_match_case(bool p_match_case) {
  81. _match_case = p_match_case;
  82. }
  83. void FindInFiles::set_folder(const String &folder) {
  84. _root_dir = folder;
  85. }
  86. void FindInFiles::set_filter(const HashSet<String> &exts) {
  87. _extension_filter = exts;
  88. }
  89. void FindInFiles::_notification(int p_what) {
  90. switch (p_what) {
  91. case NOTIFICATION_PROCESS: {
  92. _process();
  93. } break;
  94. }
  95. }
  96. void FindInFiles::start() {
  97. if (_pattern.is_empty()) {
  98. print_verbose("Nothing to search, pattern is empty");
  99. emit_signal(SceneStringName(finished));
  100. return;
  101. }
  102. if (_extension_filter.size() == 0) {
  103. print_verbose("Nothing to search, filter matches no files");
  104. emit_signal(SceneStringName(finished));
  105. return;
  106. }
  107. // Init search.
  108. _current_dir = "";
  109. PackedStringArray init_folder;
  110. init_folder.push_back(_root_dir);
  111. _folders_stack.clear();
  112. _folders_stack.push_back(init_folder);
  113. _initial_files_count = 0;
  114. _searching = true;
  115. set_process(true);
  116. }
  117. void FindInFiles::stop() {
  118. _searching = false;
  119. _current_dir = "";
  120. set_process(false);
  121. }
  122. void FindInFiles::_process() {
  123. // This part can be moved to a thread if needed.
  124. OS &os = *OS::get_singleton();
  125. uint64_t time_before = os.get_ticks_msec();
  126. while (is_processing()) {
  127. _iterate();
  128. uint64_t elapsed = (os.get_ticks_msec() - time_before);
  129. if (elapsed > 8) { // Process again after waiting 8 ticks.
  130. break;
  131. }
  132. }
  133. }
  134. void FindInFiles::_iterate() {
  135. if (_folders_stack.size() != 0) {
  136. // Scan folders first so we can build a list of files and have progress info later.
  137. PackedStringArray &folders_to_scan = _folders_stack.write[_folders_stack.size() - 1];
  138. if (folders_to_scan.size() != 0) {
  139. // Scan one folder below.
  140. String folder_name = folders_to_scan[folders_to_scan.size() - 1];
  141. pop_back(folders_to_scan);
  142. _current_dir = _current_dir.path_join(folder_name);
  143. PackedStringArray sub_dirs;
  144. PackedStringArray files_to_scan;
  145. _scan_dir("res://" + _current_dir, sub_dirs, files_to_scan);
  146. _folders_stack.push_back(sub_dirs);
  147. _files_to_scan.append_array(files_to_scan);
  148. } else {
  149. // Go back one level.
  150. pop_back(_folders_stack);
  151. _current_dir = _current_dir.get_base_dir();
  152. if (_folders_stack.size() == 0) {
  153. // All folders scanned.
  154. _initial_files_count = _files_to_scan.size();
  155. }
  156. }
  157. } else if (_files_to_scan.size() != 0) {
  158. // Then scan files.
  159. String fpath = _files_to_scan[_files_to_scan.size() - 1];
  160. pop_back(_files_to_scan);
  161. _scan_file(fpath);
  162. } else {
  163. print_verbose("Search complete");
  164. set_process(false);
  165. _current_dir = "";
  166. _searching = false;
  167. emit_signal(SceneStringName(finished));
  168. }
  169. }
  170. float FindInFiles::get_progress() const {
  171. if (_initial_files_count != 0) {
  172. return static_cast<float>(_initial_files_count - _files_to_scan.size()) / static_cast<float>(_initial_files_count);
  173. }
  174. return 0;
  175. }
  176. void FindInFiles::_scan_dir(const String &path, PackedStringArray &out_folders, PackedStringArray &out_files_to_scan) {
  177. Ref<DirAccess> dir = DirAccess::open(path);
  178. if (dir.is_null()) {
  179. print_verbose("Cannot open directory! " + path);
  180. return;
  181. }
  182. dir->list_dir_begin();
  183. // Limit to 100,000 iterations to avoid an infinite loop just in case
  184. // (this technically limits results to 100,000 files per folder).
  185. for (int i = 0; i < 100'000; ++i) {
  186. String file = dir->get_next();
  187. if (file.is_empty()) {
  188. break;
  189. }
  190. // If there is a .gdignore file in the directory, clear all the files/folders
  191. // to be searched on this path and skip searching the directory.
  192. if (file == ".gdignore") {
  193. out_folders.clear();
  194. out_files_to_scan.clear();
  195. break;
  196. }
  197. // Ignore special directories (such as those beginning with . and the project data directory).
  198. String project_data_dir_name = ProjectSettings::get_singleton()->get_project_data_dir_name();
  199. if (file.begins_with(".") || file == project_data_dir_name) {
  200. continue;
  201. }
  202. if (dir->current_is_hidden()) {
  203. continue;
  204. }
  205. if (dir->current_is_dir()) {
  206. out_folders.push_back(file);
  207. } else {
  208. String file_ext = file.get_extension();
  209. if (_extension_filter.has(file_ext)) {
  210. out_files_to_scan.push_back(path.path_join(file));
  211. }
  212. }
  213. }
  214. }
  215. void FindInFiles::_scan_file(const String &fpath) {
  216. Ref<FileAccess> f = FileAccess::open(fpath, FileAccess::READ);
  217. if (f.is_null()) {
  218. print_verbose(String("Cannot open file ") + fpath);
  219. return;
  220. }
  221. int line_number = 0;
  222. while (!f->eof_reached()) {
  223. // Line number starts at 1.
  224. ++line_number;
  225. int begin = 0;
  226. int end = 0;
  227. String line = f->get_line();
  228. while (find_next(line, _pattern, end, _match_case, _whole_words, begin, end)) {
  229. emit_signal(SNAME(SIGNAL_RESULT_FOUND), fpath, line_number, begin, end, line);
  230. }
  231. }
  232. }
  233. void FindInFiles::_bind_methods() {
  234. ADD_SIGNAL(MethodInfo(SIGNAL_RESULT_FOUND,
  235. PropertyInfo(Variant::STRING, "path"),
  236. PropertyInfo(Variant::INT, "line_number"),
  237. PropertyInfo(Variant::INT, "begin"),
  238. PropertyInfo(Variant::INT, "end"),
  239. PropertyInfo(Variant::STRING, "text")));
  240. ADD_SIGNAL(MethodInfo("finished"));
  241. }
  242. //-----------------------------------------------------------------------------
  243. const char *FindInFilesDialog::SIGNAL_FIND_REQUESTED = "find_requested";
  244. const char *FindInFilesDialog::SIGNAL_REPLACE_REQUESTED = "replace_requested";
  245. FindInFilesDialog::FindInFilesDialog() {
  246. set_min_size(Size2(500 * EDSCALE, 0));
  247. set_title(TTR("Find in Files"));
  248. VBoxContainer *vbc = memnew(VBoxContainer);
  249. vbc->set_anchor_and_offset(SIDE_LEFT, Control::ANCHOR_BEGIN, 8 * EDSCALE);
  250. vbc->set_anchor_and_offset(SIDE_TOP, Control::ANCHOR_BEGIN, 8 * EDSCALE);
  251. vbc->set_anchor_and_offset(SIDE_RIGHT, Control::ANCHOR_END, -8 * EDSCALE);
  252. vbc->set_anchor_and_offset(SIDE_BOTTOM, Control::ANCHOR_END, -8 * EDSCALE);
  253. add_child(vbc);
  254. GridContainer *gc = memnew(GridContainer);
  255. gc->set_columns(2);
  256. vbc->add_child(gc);
  257. Label *find_label = memnew(Label);
  258. find_label->set_text(TTR("Find:"));
  259. gc->add_child(find_label);
  260. _search_text_line_edit = memnew(LineEdit);
  261. _search_text_line_edit->set_h_size_flags(Control::SIZE_EXPAND_FILL);
  262. _search_text_line_edit->connect(SceneStringName(text_changed), callable_mp(this, &FindInFilesDialog::_on_search_text_modified));
  263. _search_text_line_edit->connect(SceneStringName(text_submitted), callable_mp(this, &FindInFilesDialog::_on_search_text_submitted));
  264. gc->add_child(_search_text_line_edit);
  265. _replace_label = memnew(Label);
  266. _replace_label->set_text(TTR("Replace:"));
  267. _replace_label->hide();
  268. gc->add_child(_replace_label);
  269. _replace_text_line_edit = memnew(LineEdit);
  270. _replace_text_line_edit->set_h_size_flags(Control::SIZE_EXPAND_FILL);
  271. _replace_text_line_edit->connect(SceneStringName(text_submitted), callable_mp(this, &FindInFilesDialog::_on_replace_text_submitted));
  272. _replace_text_line_edit->hide();
  273. gc->add_child(_replace_text_line_edit);
  274. gc->add_child(memnew(Control)); // Space to maintain the grid alignment.
  275. {
  276. HBoxContainer *hbc = memnew(HBoxContainer);
  277. _whole_words_checkbox = memnew(CheckBox);
  278. _whole_words_checkbox->set_text(TTR("Whole Words"));
  279. hbc->add_child(_whole_words_checkbox);
  280. _match_case_checkbox = memnew(CheckBox);
  281. _match_case_checkbox->set_text(TTR("Match Case"));
  282. hbc->add_child(_match_case_checkbox);
  283. gc->add_child(hbc);
  284. }
  285. Label *folder_label = memnew(Label);
  286. folder_label->set_text(TTR("Folder:"));
  287. gc->add_child(folder_label);
  288. {
  289. HBoxContainer *hbc = memnew(HBoxContainer);
  290. Label *prefix_label = memnew(Label);
  291. prefix_label->set_text("res://");
  292. hbc->add_child(prefix_label);
  293. _folder_line_edit = memnew(LineEdit);
  294. _folder_line_edit->set_h_size_flags(Control::SIZE_EXPAND_FILL);
  295. hbc->add_child(_folder_line_edit);
  296. Button *folder_button = memnew(Button);
  297. folder_button->set_text("...");
  298. folder_button->connect(SceneStringName(pressed), callable_mp(this, &FindInFilesDialog::_on_folder_button_pressed));
  299. hbc->add_child(folder_button);
  300. _folder_dialog = memnew(FileDialog);
  301. _folder_dialog->set_file_mode(FileDialog::FILE_MODE_OPEN_DIR);
  302. _folder_dialog->connect("dir_selected", callable_mp(this, &FindInFilesDialog::_on_folder_selected));
  303. add_child(_folder_dialog);
  304. gc->add_child(hbc);
  305. }
  306. Label *filter_label = memnew(Label);
  307. filter_label->set_text(TTR("Filters:"));
  308. filter_label->set_tooltip_text(TTR("Include the files with the following extensions. Add or remove them in ProjectSettings."));
  309. gc->add_child(filter_label);
  310. _filters_container = memnew(HBoxContainer);
  311. gc->add_child(_filters_container);
  312. _find_button = add_button(TTR("Find..."), false, "find");
  313. _find_button->set_disabled(true);
  314. _replace_button = add_button(TTR("Replace..."), false, "replace");
  315. _replace_button->set_disabled(true);
  316. Button *cancel_button = get_ok_button();
  317. cancel_button->set_text(TTR("Cancel"));
  318. _mode = SEARCH_MODE;
  319. }
  320. void FindInFilesDialog::set_search_text(const String &text) {
  321. if (_mode == SEARCH_MODE) {
  322. if (!text.is_empty()) {
  323. _search_text_line_edit->set_text(text);
  324. _on_search_text_modified(text);
  325. }
  326. callable_mp((Control *)_search_text_line_edit, &Control::grab_focus).call_deferred();
  327. _search_text_line_edit->select_all();
  328. } else if (_mode == REPLACE_MODE) {
  329. if (!text.is_empty()) {
  330. _search_text_line_edit->set_text(text);
  331. callable_mp((Control *)_replace_text_line_edit, &Control::grab_focus).call_deferred();
  332. _replace_text_line_edit->select_all();
  333. _on_search_text_modified(text);
  334. } else {
  335. callable_mp((Control *)_search_text_line_edit, &Control::grab_focus).call_deferred();
  336. _search_text_line_edit->select_all();
  337. }
  338. }
  339. }
  340. void FindInFilesDialog::set_replace_text(const String &text) {
  341. _replace_text_line_edit->set_text(text);
  342. }
  343. void FindInFilesDialog::set_find_in_files_mode(FindInFilesMode p_mode) {
  344. if (_mode == p_mode) {
  345. return;
  346. }
  347. _mode = p_mode;
  348. if (p_mode == SEARCH_MODE) {
  349. set_title(TTR("Find in Files"));
  350. _replace_label->hide();
  351. _replace_text_line_edit->hide();
  352. } else if (p_mode == REPLACE_MODE) {
  353. set_title(TTR("Replace in Files"));
  354. _replace_label->show();
  355. _replace_text_line_edit->show();
  356. }
  357. // Recalculate the dialog size after hiding child controls.
  358. set_size(Size2(get_size().x, 0));
  359. }
  360. String FindInFilesDialog::get_search_text() const {
  361. return _search_text_line_edit->get_text();
  362. }
  363. String FindInFilesDialog::get_replace_text() const {
  364. return _replace_text_line_edit->get_text();
  365. }
  366. bool FindInFilesDialog::is_match_case() const {
  367. return _match_case_checkbox->is_pressed();
  368. }
  369. bool FindInFilesDialog::is_whole_words() const {
  370. return _whole_words_checkbox->is_pressed();
  371. }
  372. String FindInFilesDialog::get_folder() const {
  373. String text = _folder_line_edit->get_text();
  374. return text.strip_edges();
  375. }
  376. HashSet<String> FindInFilesDialog::get_filter() const {
  377. // Could check the _filters_preferences but it might not have been generated yet.
  378. HashSet<String> filters;
  379. for (int i = 0; i < _filters_container->get_child_count(); ++i) {
  380. CheckBox *cb = static_cast<CheckBox *>(_filters_container->get_child(i));
  381. if (cb->is_pressed()) {
  382. filters.insert(cb->get_text());
  383. }
  384. }
  385. return filters;
  386. }
  387. void FindInFilesDialog::_notification(int p_what) {
  388. switch (p_what) {
  389. case NOTIFICATION_VISIBILITY_CHANGED: {
  390. if (is_visible()) {
  391. // Extensions might have changed in the meantime, we clean them and instance them again.
  392. for (int i = 0; i < _filters_container->get_child_count(); i++) {
  393. _filters_container->get_child(i)->queue_free();
  394. }
  395. Array exts = GLOBAL_GET("editor/script/search_in_file_extensions");
  396. for (int i = 0; i < exts.size(); ++i) {
  397. CheckBox *cb = memnew(CheckBox);
  398. cb->set_text(exts[i]);
  399. if (!_filters_preferences.has(exts[i])) {
  400. _filters_preferences[exts[i]] = true;
  401. }
  402. cb->set_pressed(_filters_preferences[exts[i]]);
  403. _filters_container->add_child(cb);
  404. }
  405. }
  406. } break;
  407. }
  408. }
  409. void FindInFilesDialog::_on_folder_button_pressed() {
  410. _folder_dialog->popup_file_dialog();
  411. }
  412. void FindInFilesDialog::custom_action(const String &p_action) {
  413. for (int i = 0; i < _filters_container->get_child_count(); ++i) {
  414. CheckBox *cb = static_cast<CheckBox *>(_filters_container->get_child(i));
  415. _filters_preferences[cb->get_text()] = cb->is_pressed();
  416. }
  417. if (p_action == "find") {
  418. emit_signal(SNAME(SIGNAL_FIND_REQUESTED));
  419. hide();
  420. } else if (p_action == "replace") {
  421. emit_signal(SNAME(SIGNAL_REPLACE_REQUESTED));
  422. hide();
  423. }
  424. }
  425. void FindInFilesDialog::_on_search_text_modified(const String &text) {
  426. ERR_FAIL_NULL(_find_button);
  427. ERR_FAIL_NULL(_replace_button);
  428. _find_button->set_disabled(get_search_text().is_empty());
  429. _replace_button->set_disabled(get_search_text().is_empty());
  430. }
  431. void FindInFilesDialog::_on_search_text_submitted(const String &text) {
  432. // This allows to trigger a global search without leaving the keyboard.
  433. if (!_find_button->is_disabled()) {
  434. if (_mode == SEARCH_MODE) {
  435. custom_action("find");
  436. }
  437. }
  438. if (!_replace_button->is_disabled()) {
  439. if (_mode == REPLACE_MODE) {
  440. custom_action("replace");
  441. }
  442. }
  443. }
  444. void FindInFilesDialog::_on_replace_text_submitted(const String &text) {
  445. // This allows to trigger a global search without leaving the keyboard.
  446. if (!_replace_button->is_disabled()) {
  447. if (_mode == REPLACE_MODE) {
  448. custom_action("replace");
  449. }
  450. }
  451. }
  452. void FindInFilesDialog::_on_folder_selected(String path) {
  453. int i = path.find("://");
  454. if (i != -1) {
  455. path = path.substr(i + 3);
  456. }
  457. _folder_line_edit->set_text(path);
  458. }
  459. void FindInFilesDialog::_bind_methods() {
  460. ADD_SIGNAL(MethodInfo(SIGNAL_FIND_REQUESTED));
  461. ADD_SIGNAL(MethodInfo(SIGNAL_REPLACE_REQUESTED));
  462. }
  463. //-----------------------------------------------------------------------------
  464. const char *FindInFilesPanel::SIGNAL_RESULT_SELECTED = "result_selected";
  465. const char *FindInFilesPanel::SIGNAL_FILES_MODIFIED = "files_modified";
  466. const char *FindInFilesPanel::SIGNAL_CLOSE_BUTTON_CLICKED = "close_button_clicked";
  467. FindInFilesPanel::FindInFilesPanel() {
  468. _finder = memnew(FindInFiles);
  469. _finder->connect(FindInFiles::SIGNAL_RESULT_FOUND, callable_mp(this, &FindInFilesPanel::_on_result_found));
  470. _finder->connect(SceneStringName(finished), callable_mp(this, &FindInFilesPanel::_on_finished));
  471. add_child(_finder);
  472. VBoxContainer *vbc = memnew(VBoxContainer);
  473. vbc->set_anchor_and_offset(SIDE_LEFT, ANCHOR_BEGIN, 0);
  474. vbc->set_anchor_and_offset(SIDE_TOP, ANCHOR_BEGIN, 0);
  475. vbc->set_anchor_and_offset(SIDE_RIGHT, ANCHOR_END, 0);
  476. vbc->set_anchor_and_offset(SIDE_BOTTOM, ANCHOR_END, 0);
  477. add_child(vbc);
  478. {
  479. HBoxContainer *hbc = memnew(HBoxContainer);
  480. Label *find_label = memnew(Label);
  481. find_label->set_text(TTR("Find:"));
  482. hbc->add_child(find_label);
  483. _search_text_label = memnew(Label);
  484. hbc->add_child(_search_text_label);
  485. _progress_bar = memnew(ProgressBar);
  486. _progress_bar->set_h_size_flags(SIZE_EXPAND_FILL);
  487. _progress_bar->set_v_size_flags(SIZE_SHRINK_CENTER);
  488. hbc->add_child(_progress_bar);
  489. set_progress_visible(false);
  490. _status_label = memnew(Label);
  491. hbc->add_child(_status_label);
  492. _refresh_button = memnew(Button);
  493. _refresh_button->set_text(TTR("Refresh"));
  494. _refresh_button->connect(SceneStringName(pressed), callable_mp(this, &FindInFilesPanel::_on_refresh_button_clicked));
  495. _refresh_button->hide();
  496. hbc->add_child(_refresh_button);
  497. _cancel_button = memnew(Button);
  498. _cancel_button->set_text(TTR("Cancel"));
  499. _cancel_button->connect(SceneStringName(pressed), callable_mp(this, &FindInFilesPanel::_on_cancel_button_clicked));
  500. _cancel_button->hide();
  501. hbc->add_child(_cancel_button);
  502. _close_button = memnew(Button);
  503. _close_button->set_text(TTR("Close"));
  504. _close_button->connect(SceneStringName(pressed), callable_mp(this, &FindInFilesPanel::_on_close_button_clicked));
  505. hbc->add_child(_close_button);
  506. vbc->add_child(hbc);
  507. }
  508. _results_display = memnew(Tree);
  509. _results_display->set_auto_translate_mode(AUTO_TRANSLATE_MODE_DISABLED);
  510. _results_display->set_v_size_flags(SIZE_EXPAND_FILL);
  511. _results_display->connect(SceneStringName(item_selected), callable_mp(this, &FindInFilesPanel::_on_result_selected));
  512. _results_display->connect("item_edited", callable_mp(this, &FindInFilesPanel::_on_item_edited));
  513. _results_display->connect("button_clicked", callable_mp(this, &FindInFilesPanel::_on_button_clicked));
  514. _results_display->set_hide_root(true);
  515. _results_display->set_select_mode(Tree::SELECT_ROW);
  516. _results_display->set_allow_rmb_select(true);
  517. _results_display->set_allow_reselect(true);
  518. _results_display->add_theme_constant_override("inner_item_margin_left", 0);
  519. _results_display->add_theme_constant_override("inner_item_margin_right", 0);
  520. _results_display->create_item(); // Root
  521. vbc->add_child(_results_display);
  522. {
  523. _replace_container = memnew(HBoxContainer);
  524. Label *replace_label = memnew(Label);
  525. replace_label->set_text(TTR("Replace:"));
  526. _replace_container->add_child(replace_label);
  527. _replace_line_edit = memnew(LineEdit);
  528. _replace_line_edit->set_h_size_flags(SIZE_EXPAND_FILL);
  529. _replace_line_edit->connect(SceneStringName(text_changed), callable_mp(this, &FindInFilesPanel::_on_replace_text_changed));
  530. _replace_container->add_child(_replace_line_edit);
  531. _replace_all_button = memnew(Button);
  532. _replace_all_button->set_text(TTR("Replace all (no undo)"));
  533. _replace_all_button->connect(SceneStringName(pressed), callable_mp(this, &FindInFilesPanel::_on_replace_all_clicked));
  534. _replace_container->add_child(_replace_all_button);
  535. _replace_container->hide();
  536. vbc->add_child(_replace_container);
  537. }
  538. }
  539. void FindInFilesPanel::set_with_replace(bool with_replace) {
  540. _with_replace = with_replace;
  541. _replace_container->set_visible(with_replace);
  542. if (with_replace) {
  543. // Results show checkboxes on their left so they can be opted out.
  544. _results_display->set_columns(2);
  545. _results_display->set_column_expand(0, false);
  546. _results_display->set_column_custom_minimum_width(0, 48 * EDSCALE);
  547. } else {
  548. // Results are single-cell items.
  549. _results_display->set_column_expand(0, true);
  550. _results_display->set_columns(1);
  551. }
  552. }
  553. void FindInFilesPanel::set_replace_text(const String &text) {
  554. _replace_line_edit->set_text(text);
  555. }
  556. void FindInFilesPanel::clear() {
  557. _file_items.clear();
  558. _result_items.clear();
  559. _results_display->clear();
  560. _results_display->create_item(); // Root
  561. }
  562. void FindInFilesPanel::start_search() {
  563. clear();
  564. _status_label->set_text(TTR("Searching..."));
  565. _search_text_label->set_text(_finder->get_search_text());
  566. set_process(true);
  567. set_progress_visible(true);
  568. _finder->start();
  569. update_replace_buttons();
  570. _refresh_button->hide();
  571. _cancel_button->show();
  572. }
  573. void FindInFilesPanel::stop_search() {
  574. _finder->stop();
  575. _status_label->set_text("");
  576. update_replace_buttons();
  577. set_progress_visible(false);
  578. _refresh_button->show();
  579. _cancel_button->hide();
  580. }
  581. void FindInFilesPanel::_notification(int p_what) {
  582. switch (p_what) {
  583. case NOTIFICATION_THEME_CHANGED: {
  584. _search_text_label->add_theme_font_override(SceneStringName(font), get_theme_font(SNAME("source"), EditorStringName(EditorFonts)));
  585. _search_text_label->add_theme_font_size_override(SceneStringName(font_size), get_theme_font_size(SNAME("source_size"), EditorStringName(EditorFonts)));
  586. _results_display->add_theme_font_override(SceneStringName(font), get_theme_font(SNAME("source"), EditorStringName(EditorFonts)));
  587. _results_display->add_theme_font_size_override(SceneStringName(font_size), get_theme_font_size(SNAME("source_size"), EditorStringName(EditorFonts)));
  588. // Rebuild search tree.
  589. if (!_finder->get_search_text().is_empty()) {
  590. start_search();
  591. }
  592. } break;
  593. case NOTIFICATION_PROCESS: {
  594. _progress_bar->set_as_ratio(_finder->get_progress());
  595. } break;
  596. }
  597. }
  598. void FindInFilesPanel::_on_result_found(const String &fpath, int line_number, int begin, int end, String text) {
  599. TreeItem *file_item;
  600. Ref<Texture2D> remove_texture = get_editor_theme_icon(SNAME("Close"));
  601. HashMap<String, TreeItem *>::Iterator E = _file_items.find(fpath);
  602. if (!E) {
  603. file_item = _results_display->create_item();
  604. file_item->set_text(0, fpath);
  605. file_item->set_metadata(0, fpath);
  606. file_item->add_button(0, remove_texture, -1, false, TTR("Remove result"));
  607. // The width of this column is restrained to checkboxes,
  608. // but that doesn't make sense for the parent items,
  609. // so we override their width so they can expand to full width.
  610. file_item->set_expand_right(0, true);
  611. _file_items[fpath] = file_item;
  612. } else {
  613. file_item = E->value;
  614. }
  615. Color file_item_color = _results_display->get_theme_color(SceneStringName(font_color)) * Color(1, 1, 1, 0.67);
  616. file_item->set_custom_color(0, file_item_color);
  617. file_item->set_selectable(0, false);
  618. int text_index = _with_replace ? 1 : 0;
  619. TreeItem *item = _results_display->create_item(file_item);
  620. // Do this first because it resets properties of the cell...
  621. item->set_cell_mode(text_index, TreeItem::CELL_MODE_CUSTOM);
  622. // Trim result item line.
  623. int old_text_size = text.size();
  624. text = text.strip_edges(true, false);
  625. int chars_removed = old_text_size - text.size();
  626. String start = vformat("%3s: ", line_number);
  627. item->set_text(text_index, start + text);
  628. item->set_custom_draw_callback(text_index, callable_mp(this, &FindInFilesPanel::draw_result_text));
  629. Result r;
  630. r.line_number = line_number;
  631. r.begin = begin;
  632. r.end = end;
  633. r.begin_trimmed = begin - chars_removed + start.size() - 1;
  634. _result_items[item] = r;
  635. if (_with_replace) {
  636. item->set_cell_mode(0, TreeItem::CELL_MODE_CHECK);
  637. item->set_checked(0, true);
  638. item->set_editable(0, true);
  639. item->add_button(1, remove_texture, -1, false, TTR("Remove result"));
  640. } else {
  641. item->add_button(0, remove_texture, -1, false, TTR("Remove result"));
  642. }
  643. }
  644. void FindInFilesPanel::draw_result_text(Object *item_obj, Rect2 rect) {
  645. TreeItem *item = Object::cast_to<TreeItem>(item_obj);
  646. if (!item) {
  647. return;
  648. }
  649. HashMap<TreeItem *, Result>::Iterator E = _result_items.find(item);
  650. if (!E) {
  651. return;
  652. }
  653. Result r = E->value;
  654. String item_text = item->get_text(_with_replace ? 1 : 0);
  655. Ref<Font> font = _results_display->get_theme_font(SceneStringName(font));
  656. int font_size = _results_display->get_theme_font_size(SceneStringName(font_size));
  657. Rect2 match_rect = rect;
  658. match_rect.position.x += font->get_string_size(item_text.left(r.begin_trimmed), HORIZONTAL_ALIGNMENT_LEFT, -1, font_size).x - 1;
  659. match_rect.size.x = font->get_string_size(_search_text_label->get_text(), HORIZONTAL_ALIGNMENT_LEFT, -1, font_size).x + 1;
  660. match_rect.position.y += 1 * EDSCALE;
  661. match_rect.size.y -= 2 * EDSCALE;
  662. _results_display->draw_rect(match_rect, get_theme_color(SNAME("accent_color"), EditorStringName(Editor)) * Color(1, 1, 1, 0.33), false, 2.0);
  663. _results_display->draw_rect(match_rect, get_theme_color(SNAME("accent_color"), EditorStringName(Editor)) * Color(1, 1, 1, 0.17), true);
  664. // Text is drawn by Tree already.
  665. }
  666. void FindInFilesPanel::_on_item_edited() {
  667. TreeItem *item = _results_display->get_selected();
  668. // Change opacity to half if checkbox is checked, otherwise full.
  669. Color use_color = _results_display->get_theme_color(SceneStringName(font_color));
  670. if (!item->is_checked(0)) {
  671. use_color.a *= 0.5;
  672. }
  673. item->set_custom_color(1, use_color);
  674. }
  675. void FindInFilesPanel::_on_finished() {
  676. update_matches_text();
  677. update_replace_buttons();
  678. set_progress_visible(false);
  679. _refresh_button->show();
  680. _cancel_button->hide();
  681. }
  682. void FindInFilesPanel::_on_refresh_button_clicked() {
  683. start_search();
  684. }
  685. void FindInFilesPanel::_on_cancel_button_clicked() {
  686. stop_search();
  687. }
  688. void FindInFilesPanel::_on_close_button_clicked() {
  689. emit_signal(SNAME(SIGNAL_CLOSE_BUTTON_CLICKED));
  690. }
  691. void FindInFilesPanel::_on_result_selected() {
  692. TreeItem *item = _results_display->get_selected();
  693. HashMap<TreeItem *, Result>::Iterator E = _result_items.find(item);
  694. if (!E) {
  695. return;
  696. }
  697. Result r = E->value;
  698. TreeItem *file_item = item->get_parent();
  699. String fpath = file_item->get_metadata(0);
  700. emit_signal(SNAME(SIGNAL_RESULT_SELECTED), fpath, r.line_number, r.begin, r.end);
  701. }
  702. void FindInFilesPanel::_on_replace_text_changed(const String &text) {
  703. update_replace_buttons();
  704. }
  705. void FindInFilesPanel::_on_replace_all_clicked() {
  706. String replace_text = get_replace_text();
  707. PackedStringArray modified_files;
  708. for (KeyValue<String, TreeItem *> &E : _file_items) {
  709. TreeItem *file_item = E.value;
  710. String fpath = file_item->get_metadata(0);
  711. Vector<Result> locations;
  712. for (TreeItem *item = file_item->get_first_child(); item; item = item->get_next()) {
  713. if (!item->is_checked(0)) {
  714. continue;
  715. }
  716. HashMap<TreeItem *, Result>::Iterator F = _result_items.find(item);
  717. ERR_FAIL_COND(!F);
  718. locations.push_back(F->value);
  719. }
  720. if (locations.size() != 0) {
  721. // Results are sorted by file, so we can batch replaces.
  722. apply_replaces_in_file(fpath, locations, replace_text);
  723. modified_files.push_back(fpath);
  724. }
  725. }
  726. // Hide replace bar so we can't trigger the action twice without doing a new search.
  727. _replace_container->hide();
  728. emit_signal(SNAME(SIGNAL_FILES_MODIFIED), modified_files);
  729. }
  730. void FindInFilesPanel::_on_button_clicked(TreeItem *p_item, int p_column, int p_id, int p_mouse_button_index) {
  731. const String file_path = p_item->get_text(0);
  732. _result_items.erase(p_item);
  733. if (_file_items.find(file_path)) {
  734. TreeItem *file_result = _file_items.get(file_path);
  735. int match_count = file_result->get_child_count();
  736. for (int i = 0; i < match_count; i++) {
  737. TreeItem *child_item = file_result->get_child(i);
  738. _result_items.erase(child_item);
  739. }
  740. file_result->clear_children();
  741. _file_items.erase(file_path);
  742. }
  743. TreeItem *item_parent = p_item->get_parent();
  744. if (item_parent && item_parent->get_child_count() < 2) {
  745. _file_items.erase(item_parent->get_text(0));
  746. get_tree()->queue_delete(item_parent);
  747. }
  748. get_tree()->queue_delete(p_item);
  749. update_matches_text();
  750. }
  751. // Same as get_line, but preserves line ending characters.
  752. class ConservativeGetLine {
  753. public:
  754. String get_line(Ref<FileAccess> f) {
  755. _line_buffer.clear();
  756. char32_t c = f->get_8();
  757. while (!f->eof_reached()) {
  758. if (c == '\n') {
  759. _line_buffer.push_back(c);
  760. _line_buffer.push_back(0);
  761. return String::utf8(_line_buffer.ptr());
  762. } else if (c == '\0') {
  763. _line_buffer.push_back(c);
  764. return String::utf8(_line_buffer.ptr());
  765. } else if (c != '\r') {
  766. _line_buffer.push_back(c);
  767. }
  768. c = f->get_8();
  769. }
  770. _line_buffer.push_back(0);
  771. return String::utf8(_line_buffer.ptr());
  772. }
  773. private:
  774. Vector<char> _line_buffer;
  775. };
  776. void FindInFilesPanel::apply_replaces_in_file(const String &fpath, const Vector<Result> &locations, const String &new_text) {
  777. // If the file is already open, I assume the editor will reload it.
  778. // If there are unsaved changes, the user will be asked on focus,
  779. // however that means either losing changes or losing replaces.
  780. Ref<FileAccess> f = FileAccess::open(fpath, FileAccess::READ);
  781. ERR_FAIL_COND_MSG(f.is_null(), "Cannot open file from path '" + fpath + "'.");
  782. String buffer;
  783. int current_line = 1;
  784. ConservativeGetLine conservative;
  785. String line = conservative.get_line(f);
  786. String search_text = _finder->get_search_text();
  787. int offset = 0;
  788. for (int i = 0; i < locations.size(); ++i) {
  789. int repl_line_number = locations[i].line_number;
  790. while (current_line < repl_line_number) {
  791. buffer += line;
  792. line = conservative.get_line(f);
  793. ++current_line;
  794. offset = 0;
  795. }
  796. int repl_begin = locations[i].begin + offset;
  797. int repl_end = locations[i].end + offset;
  798. int _;
  799. if (!find_next(line, search_text, repl_begin, _finder->is_match_case(), _finder->is_whole_words(), _, _)) {
  800. // Make sure the replace is still valid in case the file was tampered with.
  801. 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)));
  802. continue;
  803. }
  804. line = line.left(repl_begin) + new_text + line.substr(repl_end);
  805. // Keep an offset in case there are successive replaces in the same line.
  806. offset += new_text.length() - (repl_end - repl_begin);
  807. }
  808. buffer += line;
  809. while (!f->eof_reached()) {
  810. buffer += conservative.get_line(f);
  811. }
  812. // Now the modified contents are in the buffer, rewrite the file with our changes.
  813. Error err = f->reopen(fpath, FileAccess::WRITE);
  814. ERR_FAIL_COND_MSG(err != OK, "Cannot create file in path '" + fpath + "'.");
  815. f->store_string(buffer);
  816. }
  817. String FindInFilesPanel::get_replace_text() {
  818. return _replace_line_edit->get_text();
  819. }
  820. void FindInFilesPanel::update_replace_buttons() {
  821. bool disabled = _finder->is_searching();
  822. _replace_all_button->set_disabled(disabled);
  823. }
  824. void FindInFilesPanel::update_matches_text() {
  825. String results_text;
  826. int result_count = _result_items.size();
  827. int file_count = _file_items.size();
  828. if (result_count == 1 && file_count == 1) {
  829. results_text = vformat(TTR("%d match in %d file"), result_count, file_count);
  830. } else if (result_count != 1 && file_count == 1) {
  831. results_text = vformat(TTR("%d matches in %d file"), result_count, file_count);
  832. } else {
  833. results_text = vformat(TTR("%d matches in %d files"), result_count, file_count);
  834. }
  835. _status_label->set_text(results_text);
  836. }
  837. void FindInFilesPanel::set_progress_visible(bool p_visible) {
  838. _progress_bar->set_self_modulate(Color(1, 1, 1, p_visible ? 1 : 0));
  839. }
  840. void FindInFilesPanel::_bind_methods() {
  841. ClassDB::bind_method("_on_result_found", &FindInFilesPanel::_on_result_found);
  842. ClassDB::bind_method("_on_finished", &FindInFilesPanel::_on_finished);
  843. ADD_SIGNAL(MethodInfo(SIGNAL_RESULT_SELECTED,
  844. PropertyInfo(Variant::STRING, "path"),
  845. PropertyInfo(Variant::INT, "line_number"),
  846. PropertyInfo(Variant::INT, "begin"),
  847. PropertyInfo(Variant::INT, "end")));
  848. ADD_SIGNAL(MethodInfo(SIGNAL_FILES_MODIFIED, PropertyInfo(Variant::STRING, "paths")));
  849. ADD_SIGNAL(MethodInfo(SIGNAL_CLOSE_BUTTON_CLICKED));
  850. }