find_in_files.cpp 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027
  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->set_hide_root(true);
  514. _results_display->set_select_mode(Tree::SELECT_ROW);
  515. _results_display->set_allow_rmb_select(true);
  516. _results_display->set_allow_reselect(true);
  517. _results_display->add_theme_constant_override("inner_item_margin_left", 0);
  518. _results_display->add_theme_constant_override("inner_item_margin_right", 0);
  519. _results_display->create_item(); // Root
  520. vbc->add_child(_results_display);
  521. {
  522. _replace_container = memnew(HBoxContainer);
  523. Label *replace_label = memnew(Label);
  524. replace_label->set_text(TTR("Replace:"));
  525. _replace_container->add_child(replace_label);
  526. _replace_line_edit = memnew(LineEdit);
  527. _replace_line_edit->set_h_size_flags(SIZE_EXPAND_FILL);
  528. _replace_line_edit->connect(SceneStringName(text_changed), callable_mp(this, &FindInFilesPanel::_on_replace_text_changed));
  529. _replace_container->add_child(_replace_line_edit);
  530. _replace_all_button = memnew(Button);
  531. _replace_all_button->set_text(TTR("Replace all (no undo)"));
  532. _replace_all_button->connect(SceneStringName(pressed), callable_mp(this, &FindInFilesPanel::_on_replace_all_clicked));
  533. _replace_container->add_child(_replace_all_button);
  534. _replace_container->hide();
  535. vbc->add_child(_replace_container);
  536. }
  537. }
  538. void FindInFilesPanel::set_with_replace(bool with_replace) {
  539. _with_replace = with_replace;
  540. _replace_container->set_visible(with_replace);
  541. if (with_replace) {
  542. // Results show checkboxes on their left so they can be opted out.
  543. _results_display->set_columns(2);
  544. _results_display->set_column_expand(0, false);
  545. _results_display->set_column_custom_minimum_width(0, 48 * EDSCALE);
  546. } else {
  547. // Results are single-cell items.
  548. _results_display->set_column_expand(0, true);
  549. _results_display->set_columns(1);
  550. }
  551. }
  552. void FindInFilesPanel::set_replace_text(const String &text) {
  553. _replace_line_edit->set_text(text);
  554. }
  555. void FindInFilesPanel::clear() {
  556. _file_items.clear();
  557. _result_items.clear();
  558. _results_display->clear();
  559. _results_display->create_item(); // Root
  560. }
  561. void FindInFilesPanel::start_search() {
  562. clear();
  563. _status_label->set_text(TTR("Searching..."));
  564. _search_text_label->set_text(_finder->get_search_text());
  565. set_process(true);
  566. set_progress_visible(true);
  567. _finder->start();
  568. update_replace_buttons();
  569. _refresh_button->hide();
  570. _cancel_button->show();
  571. }
  572. void FindInFilesPanel::stop_search() {
  573. _finder->stop();
  574. _status_label->set_text("");
  575. update_replace_buttons();
  576. set_progress_visible(false);
  577. _refresh_button->show();
  578. _cancel_button->hide();
  579. }
  580. void FindInFilesPanel::_notification(int p_what) {
  581. switch (p_what) {
  582. case NOTIFICATION_THEME_CHANGED: {
  583. _search_text_label->add_theme_font_override(SceneStringName(font), get_theme_font(SNAME("source"), EditorStringName(EditorFonts)));
  584. _search_text_label->add_theme_font_size_override(SceneStringName(font_size), get_theme_font_size(SNAME("source_size"), EditorStringName(EditorFonts)));
  585. _results_display->add_theme_font_override(SceneStringName(font), get_theme_font(SNAME("source"), EditorStringName(EditorFonts)));
  586. _results_display->add_theme_font_size_override(SceneStringName(font_size), get_theme_font_size(SNAME("source_size"), EditorStringName(EditorFonts)));
  587. // Rebuild search tree.
  588. if (!_finder->get_search_text().is_empty()) {
  589. start_search();
  590. }
  591. } break;
  592. case NOTIFICATION_PROCESS: {
  593. _progress_bar->set_as_ratio(_finder->get_progress());
  594. } break;
  595. }
  596. }
  597. void FindInFilesPanel::_on_result_found(const String &fpath, int line_number, int begin, int end, String text) {
  598. TreeItem *file_item;
  599. HashMap<String, TreeItem *>::Iterator E = _file_items.find(fpath);
  600. if (!E) {
  601. file_item = _results_display->create_item();
  602. file_item->set_text(0, fpath);
  603. file_item->set_metadata(0, fpath);
  604. // The width of this column is restrained to checkboxes,
  605. // but that doesn't make sense for the parent items,
  606. // so we override their width so they can expand to full width.
  607. file_item->set_expand_right(0, true);
  608. _file_items[fpath] = file_item;
  609. } else {
  610. file_item = E->value;
  611. }
  612. Color file_item_color = _results_display->get_theme_color(SceneStringName(font_color)) * Color(1, 1, 1, 0.67);
  613. file_item->set_custom_color(0, file_item_color);
  614. file_item->set_selectable(0, false);
  615. int text_index = _with_replace ? 1 : 0;
  616. TreeItem *item = _results_display->create_item(file_item);
  617. // Do this first because it resets properties of the cell...
  618. item->set_cell_mode(text_index, TreeItem::CELL_MODE_CUSTOM);
  619. // Trim result item line.
  620. int old_text_size = text.size();
  621. text = text.strip_edges(true, false);
  622. int chars_removed = old_text_size - text.size();
  623. String start = vformat("%3s: ", line_number);
  624. item->set_text(text_index, start + text);
  625. item->set_custom_draw_callback(text_index, callable_mp(this, &FindInFilesPanel::draw_result_text));
  626. Result r;
  627. r.line_number = line_number;
  628. r.begin = begin;
  629. r.end = end;
  630. r.begin_trimmed = begin - chars_removed + start.size() - 1;
  631. _result_items[item] = r;
  632. if (_with_replace) {
  633. item->set_cell_mode(0, TreeItem::CELL_MODE_CHECK);
  634. item->set_checked(0, true);
  635. item->set_editable(0, true);
  636. }
  637. }
  638. void FindInFilesPanel::draw_result_text(Object *item_obj, Rect2 rect) {
  639. TreeItem *item = Object::cast_to<TreeItem>(item_obj);
  640. if (!item) {
  641. return;
  642. }
  643. HashMap<TreeItem *, Result>::Iterator E = _result_items.find(item);
  644. if (!E) {
  645. return;
  646. }
  647. Result r = E->value;
  648. String item_text = item->get_text(_with_replace ? 1 : 0);
  649. Ref<Font> font = _results_display->get_theme_font(SceneStringName(font));
  650. int font_size = _results_display->get_theme_font_size(SceneStringName(font_size));
  651. Rect2 match_rect = rect;
  652. match_rect.position.x += font->get_string_size(item_text.left(r.begin_trimmed), HORIZONTAL_ALIGNMENT_LEFT, -1, font_size).x - 1;
  653. match_rect.size.x = font->get_string_size(_search_text_label->get_text(), HORIZONTAL_ALIGNMENT_LEFT, -1, font_size).x + 1;
  654. match_rect.position.y += 1 * EDSCALE;
  655. match_rect.size.y -= 2 * EDSCALE;
  656. _results_display->draw_rect(match_rect, get_theme_color(SNAME("accent_color"), EditorStringName(Editor)) * Color(1, 1, 1, 0.33), false, 2.0);
  657. _results_display->draw_rect(match_rect, get_theme_color(SNAME("accent_color"), EditorStringName(Editor)) * Color(1, 1, 1, 0.17), true);
  658. // Text is drawn by Tree already.
  659. }
  660. void FindInFilesPanel::_on_item_edited() {
  661. TreeItem *item = _results_display->get_selected();
  662. // Change opacity to half if checkbox is checked, otherwise full.
  663. Color use_color = _results_display->get_theme_color(SceneStringName(font_color));
  664. if (!item->is_checked(0)) {
  665. use_color.a *= 0.5;
  666. }
  667. item->set_custom_color(1, use_color);
  668. }
  669. void FindInFilesPanel::_on_finished() {
  670. String results_text;
  671. int result_count = _result_items.size();
  672. int file_count = _file_items.size();
  673. if (result_count == 1 && file_count == 1) {
  674. results_text = vformat(TTR("%d match in %d file"), result_count, file_count);
  675. } else if (result_count != 1 && file_count == 1) {
  676. results_text = vformat(TTR("%d matches in %d file"), result_count, file_count);
  677. } else {
  678. results_text = vformat(TTR("%d matches in %d files"), result_count, file_count);
  679. }
  680. _status_label->set_text(results_text);
  681. update_replace_buttons();
  682. set_progress_visible(false);
  683. _refresh_button->show();
  684. _cancel_button->hide();
  685. }
  686. void FindInFilesPanel::_on_refresh_button_clicked() {
  687. start_search();
  688. }
  689. void FindInFilesPanel::_on_cancel_button_clicked() {
  690. stop_search();
  691. }
  692. void FindInFilesPanel::_on_close_button_clicked() {
  693. emit_signal(SNAME(SIGNAL_CLOSE_BUTTON_CLICKED));
  694. }
  695. void FindInFilesPanel::_on_result_selected() {
  696. TreeItem *item = _results_display->get_selected();
  697. HashMap<TreeItem *, Result>::Iterator E = _result_items.find(item);
  698. if (!E) {
  699. return;
  700. }
  701. Result r = E->value;
  702. TreeItem *file_item = item->get_parent();
  703. String fpath = file_item->get_metadata(0);
  704. emit_signal(SNAME(SIGNAL_RESULT_SELECTED), fpath, r.line_number, r.begin, r.end);
  705. }
  706. void FindInFilesPanel::_on_replace_text_changed(const String &text) {
  707. update_replace_buttons();
  708. }
  709. void FindInFilesPanel::_on_replace_all_clicked() {
  710. String replace_text = get_replace_text();
  711. PackedStringArray modified_files;
  712. for (KeyValue<String, TreeItem *> &E : _file_items) {
  713. TreeItem *file_item = E.value;
  714. String fpath = file_item->get_metadata(0);
  715. Vector<Result> locations;
  716. for (TreeItem *item = file_item->get_first_child(); item; item = item->get_next()) {
  717. if (!item->is_checked(0)) {
  718. continue;
  719. }
  720. HashMap<TreeItem *, Result>::Iterator F = _result_items.find(item);
  721. ERR_FAIL_COND(!F);
  722. locations.push_back(F->value);
  723. }
  724. if (locations.size() != 0) {
  725. // Results are sorted by file, so we can batch replaces.
  726. apply_replaces_in_file(fpath, locations, replace_text);
  727. modified_files.push_back(fpath);
  728. }
  729. }
  730. // Hide replace bar so we can't trigger the action twice without doing a new search.
  731. _replace_container->hide();
  732. emit_signal(SNAME(SIGNAL_FILES_MODIFIED), modified_files);
  733. }
  734. // Same as get_line, but preserves line ending characters.
  735. class ConservativeGetLine {
  736. public:
  737. String get_line(Ref<FileAccess> f) {
  738. _line_buffer.clear();
  739. char32_t c = f->get_8();
  740. while (!f->eof_reached()) {
  741. if (c == '\n') {
  742. _line_buffer.push_back(c);
  743. _line_buffer.push_back(0);
  744. return String::utf8(_line_buffer.ptr());
  745. } else if (c == '\0') {
  746. _line_buffer.push_back(c);
  747. return String::utf8(_line_buffer.ptr());
  748. } else if (c != '\r') {
  749. _line_buffer.push_back(c);
  750. }
  751. c = f->get_8();
  752. }
  753. _line_buffer.push_back(0);
  754. return String::utf8(_line_buffer.ptr());
  755. }
  756. private:
  757. Vector<char> _line_buffer;
  758. };
  759. void FindInFilesPanel::apply_replaces_in_file(const String &fpath, const Vector<Result> &locations, const String &new_text) {
  760. // If the file is already open, I assume the editor will reload it.
  761. // If there are unsaved changes, the user will be asked on focus,
  762. // however that means either losing changes or losing replaces.
  763. Ref<FileAccess> f = FileAccess::open(fpath, FileAccess::READ);
  764. ERR_FAIL_COND_MSG(f.is_null(), "Cannot open file from path '" + fpath + "'.");
  765. String buffer;
  766. int current_line = 1;
  767. ConservativeGetLine conservative;
  768. String line = conservative.get_line(f);
  769. String search_text = _finder->get_search_text();
  770. int offset = 0;
  771. for (int i = 0; i < locations.size(); ++i) {
  772. int repl_line_number = locations[i].line_number;
  773. while (current_line < repl_line_number) {
  774. buffer += line;
  775. line = conservative.get_line(f);
  776. ++current_line;
  777. offset = 0;
  778. }
  779. int repl_begin = locations[i].begin + offset;
  780. int repl_end = locations[i].end + offset;
  781. int _;
  782. if (!find_next(line, search_text, repl_begin, _finder->is_match_case(), _finder->is_whole_words(), _, _)) {
  783. // Make sure the replace is still valid in case the file was tampered with.
  784. 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)));
  785. continue;
  786. }
  787. line = line.left(repl_begin) + new_text + line.substr(repl_end);
  788. // Keep an offset in case there are successive replaces in the same line.
  789. offset += new_text.length() - (repl_end - repl_begin);
  790. }
  791. buffer += line;
  792. while (!f->eof_reached()) {
  793. buffer += conservative.get_line(f);
  794. }
  795. // Now the modified contents are in the buffer, rewrite the file with our changes.
  796. Error err = f->reopen(fpath, FileAccess::WRITE);
  797. ERR_FAIL_COND_MSG(err != OK, "Cannot create file in path '" + fpath + "'.");
  798. f->store_string(buffer);
  799. }
  800. String FindInFilesPanel::get_replace_text() {
  801. return _replace_line_edit->get_text();
  802. }
  803. void FindInFilesPanel::update_replace_buttons() {
  804. bool disabled = _finder->is_searching();
  805. _replace_all_button->set_disabled(disabled);
  806. }
  807. void FindInFilesPanel::set_progress_visible(bool p_visible) {
  808. _progress_bar->set_self_modulate(Color(1, 1, 1, p_visible ? 1 : 0));
  809. }
  810. void FindInFilesPanel::_bind_methods() {
  811. ClassDB::bind_method("_on_result_found", &FindInFilesPanel::_on_result_found);
  812. ClassDB::bind_method("_on_finished", &FindInFilesPanel::_on_finished);
  813. ADD_SIGNAL(MethodInfo(SIGNAL_RESULT_SELECTED,
  814. PropertyInfo(Variant::STRING, "path"),
  815. PropertyInfo(Variant::INT, "line_number"),
  816. PropertyInfo(Variant::INT, "begin"),
  817. PropertyInfo(Variant::INT, "end")));
  818. ADD_SIGNAL(MethodInfo(SIGNAL_FILES_MODIFIED, PropertyInfo(Variant::STRING, "paths")));
  819. ADD_SIGNAL(MethodInfo(SIGNAL_CLOSE_BUTTON_CLICKED));
  820. }