find_in_files.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990
  1. /*************************************************************************/
  2. /* find_in_files.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "find_in_files.h"
  31. #include "core/io/dir_access.h"
  32. #include "core/os/os.h"
  33. #include "editor_node.h"
  34. #include "editor_scale.h"
  35. #include "scene/gui/box_container.h"
  36. #include "scene/gui/button.h"
  37. #include "scene/gui/check_box.h"
  38. #include "scene/gui/file_dialog.h"
  39. #include "scene/gui/grid_container.h"
  40. #include "scene/gui/label.h"
  41. #include "scene/gui/line_edit.h"
  42. #include "scene/gui/progress_bar.h"
  43. #include "scene/gui/tree.h"
  44. const char *FindInFiles::SIGNAL_RESULT_FOUND = "result_found";
  45. const char *FindInFiles::SIGNAL_FINISHED = "finished";
  46. // TODO Would be nice in Vector and Vectors
  47. template <typename T>
  48. inline void pop_back(T &container) {
  49. container.resize(container.size() - 1);
  50. }
  51. // TODO Copied from TextEdit private, would be nice to extract it in a single place
  52. static bool is_text_char(char32_t c) {
  53. return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_';
  54. }
  55. static bool find_next(const String &line, 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_text_char(line[begin - 1])) {
  67. continue;
  68. }
  69. if (end < line.size() && is_text_char(line[end])) {
  70. continue;
  71. }
  72. }
  73. return true;
  74. }
  75. }
  76. //--------------------------------------------------------------------------------
  77. void FindInFiles::set_search_text(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(String folder) {
  87. _root_dir = folder;
  88. }
  89. void FindInFiles::set_filter(const Set<String> &exts) {
  90. _extension_filter = exts;
  91. }
  92. void FindInFiles::_notification(int p_notification) {
  93. if (p_notification == NOTIFICATION_PROCESS) {
  94. _process();
  95. }
  96. }
  97. void FindInFiles::start() {
  98. if (_pattern == "") {
  99. print_verbose("Nothing to search, pattern is empty");
  100. emit_signal(SNAME(SIGNAL_FINISHED));
  101. return;
  102. }
  103. if (_extension_filter.size() == 0) {
  104. print_verbose("Nothing to search, filter matches no files");
  105. emit_signal(SNAME(SIGNAL_FINISHED));
  106. return;
  107. }
  108. // Init search
  109. _current_dir = "";
  110. PackedStringArray init_folder;
  111. init_folder.push_back(_root_dir);
  112. _folders_stack.clear();
  113. _folders_stack.push_back(init_folder);
  114. _initial_files_count = 0;
  115. _searching = true;
  116. set_process(true);
  117. }
  118. void FindInFiles::stop() {
  119. _searching = false;
  120. _current_dir = "";
  121. set_process(false);
  122. }
  123. void FindInFiles::_process() {
  124. // This part can be moved to a thread if needed
  125. OS &os = *OS::get_singleton();
  126. float time_before = os.get_ticks_msec();
  127. while (is_processing()) {
  128. _iterate();
  129. float elapsed = (os.get_ticks_msec() - time_before);
  130. if (elapsed > 1000.0 / 120.0) {
  131. break;
  132. }
  133. }
  134. }
  135. void FindInFiles::_iterate() {
  136. if (_folders_stack.size() != 0) {
  137. // Scan folders first so we can build a list of files and have progress info later
  138. PackedStringArray &folders_to_scan = _folders_stack.write[_folders_stack.size() - 1];
  139. if (folders_to_scan.size() != 0) {
  140. // Scan one folder below
  141. String folder_name = folders_to_scan[folders_to_scan.size() - 1];
  142. pop_back(folders_to_scan);
  143. _current_dir = _current_dir.plus_file(folder_name);
  144. PackedStringArray sub_dirs;
  145. _scan_dir("res://" + _current_dir, sub_dirs);
  146. _folders_stack.push_back(sub_dirs);
  147. } else {
  148. // Go back one level
  149. pop_back(_folders_stack);
  150. _current_dir = _current_dir.get_base_dir();
  151. if (_folders_stack.size() == 0) {
  152. // All folders scanned
  153. _initial_files_count = _files_to_scan.size();
  154. }
  155. }
  156. } else if (_files_to_scan.size() != 0) {
  157. // Then scan files
  158. String fpath = _files_to_scan[_files_to_scan.size() - 1];
  159. pop_back(_files_to_scan);
  160. _scan_file(fpath);
  161. } else {
  162. print_verbose("Search complete");
  163. set_process(false);
  164. _current_dir = "";
  165. _searching = false;
  166. emit_signal(SNAME(SIGNAL_FINISHED));
  167. }
  168. }
  169. float FindInFiles::get_progress() const {
  170. if (_initial_files_count != 0) {
  171. return static_cast<float>(_initial_files_count - _files_to_scan.size()) / static_cast<float>(_initial_files_count);
  172. }
  173. return 0;
  174. }
  175. void FindInFiles::_scan_dir(String path, PackedStringArray &out_folders) {
  176. DirAccessRef dir = DirAccess::open(path);
  177. if (!dir) {
  178. print_verbose("Cannot open directory! " + path);
  179. return;
  180. }
  181. dir->list_dir_begin();
  182. for (int i = 0; i < 1000; ++i) {
  183. String file = dir->get_next();
  184. if (file == "") {
  185. break;
  186. }
  187. // If there is a .gdignore file in the directory, don't bother searching it
  188. if (file == ".gdignore") {
  189. break;
  190. }
  191. // Ignore special dirs (such as .git and project data directory)
  192. String project_data_dir_name = ProjectSettings::get_singleton()->get_project_data_dir_name();
  193. if (file.begins_with(".") || file == project_data_dir_name) {
  194. continue;
  195. }
  196. if (dir->current_is_hidden()) {
  197. continue;
  198. }
  199. if (dir->current_is_dir()) {
  200. out_folders.push_back(file);
  201. } else {
  202. String file_ext = file.get_extension();
  203. if (_extension_filter.has(file_ext)) {
  204. _files_to_scan.push_back(path.plus_file(file));
  205. }
  206. }
  207. }
  208. }
  209. void FindInFiles::_scan_file(String fpath) {
  210. FileAccessRef f = FileAccess::open(fpath, FileAccess::READ);
  211. if (!f) {
  212. print_verbose(String("Cannot open file ") + fpath);
  213. return;
  214. }
  215. int line_number = 0;
  216. while (!f->eof_reached()) {
  217. // line number starts at 1
  218. ++line_number;
  219. int begin = 0;
  220. int end = 0;
  221. String line = f->get_line();
  222. while (find_next(line, _pattern, end, _match_case, _whole_words, begin, end)) {
  223. emit_signal(SNAME(SIGNAL_RESULT_FOUND), fpath, line_number, begin, end, line);
  224. }
  225. }
  226. f->close();
  227. }
  228. void FindInFiles::_bind_methods() {
  229. ADD_SIGNAL(MethodInfo(SIGNAL_RESULT_FOUND,
  230. PropertyInfo(Variant::STRING, "path"),
  231. PropertyInfo(Variant::INT, "line_number"),
  232. PropertyInfo(Variant::INT, "begin"),
  233. PropertyInfo(Variant::INT, "end"),
  234. PropertyInfo(Variant::STRING, "text")));
  235. ADD_SIGNAL(MethodInfo(SIGNAL_FINISHED));
  236. }
  237. //-----------------------------------------------------------------------------
  238. const char *FindInFilesDialog::SIGNAL_FIND_REQUESTED = "find_requested";
  239. const char *FindInFilesDialog::SIGNAL_REPLACE_REQUESTED = "replace_requested";
  240. FindInFilesDialog::FindInFilesDialog() {
  241. set_min_size(Size2(500 * EDSCALE, 0));
  242. set_title(TTR("Find in Files"));
  243. VBoxContainer *vbc = memnew(VBoxContainer);
  244. vbc->set_anchor_and_offset(SIDE_LEFT, Control::ANCHOR_BEGIN, 8 * EDSCALE);
  245. vbc->set_anchor_and_offset(SIDE_TOP, Control::ANCHOR_BEGIN, 8 * EDSCALE);
  246. vbc->set_anchor_and_offset(SIDE_RIGHT, Control::ANCHOR_END, -8 * EDSCALE);
  247. vbc->set_anchor_and_offset(SIDE_BOTTOM, Control::ANCHOR_END, -8 * EDSCALE);
  248. add_child(vbc);
  249. GridContainer *gc = memnew(GridContainer);
  250. gc->set_columns(2);
  251. vbc->add_child(gc);
  252. Label *find_label = memnew(Label);
  253. find_label->set_text(TTR("Find:"));
  254. gc->add_child(find_label);
  255. _search_text_line_edit = memnew(LineEdit);
  256. _search_text_line_edit->set_h_size_flags(Control::SIZE_EXPAND_FILL);
  257. _search_text_line_edit->connect("text_changed", callable_mp(this, &FindInFilesDialog::_on_search_text_modified));
  258. _search_text_line_edit->connect("text_submitted", callable_mp(this, &FindInFilesDialog::_on_search_text_submitted));
  259. gc->add_child(_search_text_line_edit);
  260. _replace_label = memnew(Label);
  261. _replace_label->set_text(TTR("Replace:"));
  262. _replace_label->hide();
  263. gc->add_child(_replace_label);
  264. _replace_text_line_edit = memnew(LineEdit);
  265. _replace_text_line_edit->set_h_size_flags(Control::SIZE_EXPAND_FILL);
  266. _replace_text_line_edit->connect("text_submitted", callable_mp(this, &FindInFilesDialog::_on_replace_text_submitted));
  267. _replace_text_line_edit->hide();
  268. gc->add_child(_replace_text_line_edit);
  269. gc->add_child(memnew(Control)); // Space to maintain the grid aligned.
  270. {
  271. HBoxContainer *hbc = memnew(HBoxContainer);
  272. _whole_words_checkbox = memnew(CheckBox);
  273. _whole_words_checkbox->set_text(TTR("Whole Words"));
  274. hbc->add_child(_whole_words_checkbox);
  275. _match_case_checkbox = memnew(CheckBox);
  276. _match_case_checkbox->set_text(TTR("Match Case"));
  277. hbc->add_child(_match_case_checkbox);
  278. gc->add_child(hbc);
  279. }
  280. Label *folder_label = memnew(Label);
  281. folder_label->set_text(TTR("Folder:"));
  282. gc->add_child(folder_label);
  283. {
  284. HBoxContainer *hbc = memnew(HBoxContainer);
  285. Label *prefix_label = memnew(Label);
  286. prefix_label->set_text("res://");
  287. hbc->add_child(prefix_label);
  288. _folder_line_edit = memnew(LineEdit);
  289. _folder_line_edit->set_h_size_flags(Control::SIZE_EXPAND_FILL);
  290. hbc->add_child(_folder_line_edit);
  291. Button *folder_button = memnew(Button);
  292. folder_button->set_text("...");
  293. folder_button->connect("pressed", callable_mp(this, &FindInFilesDialog::_on_folder_button_pressed));
  294. hbc->add_child(folder_button);
  295. _folder_dialog = memnew(FileDialog);
  296. _folder_dialog->set_file_mode(FileDialog::FILE_MODE_OPEN_DIR);
  297. _folder_dialog->connect("dir_selected", callable_mp(this, &FindInFilesDialog::_on_folder_selected));
  298. add_child(_folder_dialog);
  299. gc->add_child(hbc);
  300. }
  301. Label *filter_label = memnew(Label);
  302. filter_label->set_text(TTR("Filters:"));
  303. filter_label->set_tooltip(TTR("Include the files with the following extensions. Add or remove them in ProjectSettings."));
  304. gc->add_child(filter_label);
  305. _filters_container = memnew(HBoxContainer);
  306. gc->add_child(_filters_container);
  307. _find_button = add_button(TTR("Find..."), false, "find");
  308. _find_button->set_disabled(true);
  309. _replace_button = add_button(TTR("Replace..."), false, "replace");
  310. _replace_button->set_disabled(true);
  311. Button *cancel_button = get_ok_button();
  312. cancel_button->set_text(TTR("Cancel"));
  313. _mode = SEARCH_MODE;
  314. }
  315. void FindInFilesDialog::set_search_text(String text) {
  316. _search_text_line_edit->set_text(text);
  317. _on_search_text_modified(text);
  318. }
  319. void FindInFilesDialog::set_replace_text(String text) {
  320. _replace_text_line_edit->set_text(text);
  321. }
  322. void FindInFilesDialog::set_find_in_files_mode(FindInFilesMode p_mode) {
  323. if (_mode == p_mode) {
  324. return;
  325. }
  326. _mode = p_mode;
  327. if (p_mode == SEARCH_MODE) {
  328. set_title(TTR("Find in Files"));
  329. _replace_label->hide();
  330. _replace_text_line_edit->hide();
  331. } else if (p_mode == REPLACE_MODE) {
  332. set_title(TTR("Replace in Files"));
  333. _replace_label->show();
  334. _replace_text_line_edit->show();
  335. }
  336. // After hiding some child controls, let's recalculate proper Dialog size
  337. set_size(Size2(get_size().x, 0));
  338. }
  339. String FindInFilesDialog::get_search_text() const {
  340. String text = _search_text_line_edit->get_text();
  341. return text.strip_edges();
  342. }
  343. String FindInFilesDialog::get_replace_text() const {
  344. return _replace_text_line_edit->get_text();
  345. }
  346. bool FindInFilesDialog::is_match_case() const {
  347. return _match_case_checkbox->is_pressed();
  348. }
  349. bool FindInFilesDialog::is_whole_words() const {
  350. return _whole_words_checkbox->is_pressed();
  351. }
  352. String FindInFilesDialog::get_folder() const {
  353. String text = _folder_line_edit->get_text();
  354. return text.strip_edges();
  355. }
  356. Set<String> FindInFilesDialog::get_filter() const {
  357. // could check the _filters_preferences but it might not have been generated yet.
  358. Set<String> filters;
  359. for (int i = 0; i < _filters_container->get_child_count(); ++i) {
  360. CheckBox *cb = (CheckBox *)_filters_container->get_child(i);
  361. if (cb->is_pressed()) {
  362. filters.insert(cb->get_text());
  363. }
  364. }
  365. return filters;
  366. }
  367. void FindInFilesDialog::_notification(int p_what) {
  368. if (p_what == NOTIFICATION_VISIBILITY_CHANGED) {
  369. if (is_visible()) {
  370. // Doesn't work more than once if not deferred...
  371. _search_text_line_edit->call_deferred(SNAME("grab_focus"));
  372. _search_text_line_edit->select_all();
  373. // Extensions might have changed in the meantime, we clean them and instance them again.
  374. for (int i = 0; i < _filters_container->get_child_count(); i++) {
  375. _filters_container->get_child(i)->queue_delete();
  376. }
  377. Array exts = ProjectSettings::get_singleton()->get("editor/script/search_in_file_extensions");
  378. for (int i = 0; i < exts.size(); ++i) {
  379. CheckBox *cb = memnew(CheckBox);
  380. cb->set_text(exts[i]);
  381. if (!_filters_preferences.has(exts[i])) {
  382. _filters_preferences[exts[i]] = true;
  383. }
  384. cb->set_pressed(_filters_preferences[exts[i]]);
  385. _filters_container->add_child(cb);
  386. }
  387. }
  388. }
  389. }
  390. void FindInFilesDialog::_on_folder_button_pressed() {
  391. _folder_dialog->popup_file_dialog();
  392. }
  393. void FindInFilesDialog::custom_action(const String &p_action) {
  394. for (int i = 0; i < _filters_container->get_child_count(); ++i) {
  395. CheckBox *cb = (CheckBox *)_filters_container->get_child(i);
  396. _filters_preferences[cb->get_text()] = cb->is_pressed();
  397. }
  398. if (p_action == "find") {
  399. emit_signal(SNAME(SIGNAL_FIND_REQUESTED));
  400. hide();
  401. } else if (p_action == "replace") {
  402. emit_signal(SNAME(SIGNAL_REPLACE_REQUESTED));
  403. hide();
  404. }
  405. }
  406. void FindInFilesDialog::_on_search_text_modified(String text) {
  407. ERR_FAIL_COND(!_find_button);
  408. ERR_FAIL_COND(!_replace_button);
  409. _find_button->set_disabled(get_search_text().is_empty());
  410. _replace_button->set_disabled(get_search_text().is_empty());
  411. }
  412. void FindInFilesDialog::_on_search_text_submitted(String text) {
  413. // This allows to trigger a global search without leaving the keyboard
  414. if (!_find_button->is_disabled()) {
  415. if (_mode == SEARCH_MODE) {
  416. custom_action("find");
  417. }
  418. }
  419. if (!_replace_button->is_disabled()) {
  420. if (_mode == REPLACE_MODE) {
  421. custom_action("replace");
  422. }
  423. }
  424. }
  425. void FindInFilesDialog::_on_replace_text_submitted(String text) {
  426. // This allows to trigger a global search without leaving the keyboard
  427. if (!_replace_button->is_disabled()) {
  428. if (_mode == REPLACE_MODE) {
  429. custom_action("replace");
  430. }
  431. }
  432. }
  433. void FindInFilesDialog::_on_folder_selected(String path) {
  434. int i = path.find("://");
  435. if (i != -1) {
  436. path = path.substr(i + 3);
  437. }
  438. _folder_line_edit->set_text(path);
  439. }
  440. void FindInFilesDialog::_bind_methods() {
  441. ADD_SIGNAL(MethodInfo(SIGNAL_FIND_REQUESTED));
  442. ADD_SIGNAL(MethodInfo(SIGNAL_REPLACE_REQUESTED));
  443. }
  444. //-----------------------------------------------------------------------------
  445. const char *FindInFilesPanel::SIGNAL_RESULT_SELECTED = "result_selected";
  446. const char *FindInFilesPanel::SIGNAL_FILES_MODIFIED = "files_modified";
  447. FindInFilesPanel::FindInFilesPanel() {
  448. _finder = memnew(FindInFiles);
  449. _finder->connect(FindInFiles::SIGNAL_RESULT_FOUND, callable_mp(this, &FindInFilesPanel::_on_result_found));
  450. _finder->connect(FindInFiles::SIGNAL_FINISHED, callable_mp(this, &FindInFilesPanel::_on_finished));
  451. add_child(_finder);
  452. VBoxContainer *vbc = memnew(VBoxContainer);
  453. vbc->set_anchor_and_offset(SIDE_LEFT, ANCHOR_BEGIN, 0);
  454. vbc->set_anchor_and_offset(SIDE_TOP, ANCHOR_BEGIN, 0);
  455. vbc->set_anchor_and_offset(SIDE_RIGHT, ANCHOR_END, 0);
  456. vbc->set_anchor_and_offset(SIDE_BOTTOM, ANCHOR_END, 0);
  457. add_child(vbc);
  458. {
  459. HBoxContainer *hbc = memnew(HBoxContainer);
  460. Label *find_label = memnew(Label);
  461. find_label->set_text(TTR("Find: "));
  462. hbc->add_child(find_label);
  463. _search_text_label = memnew(Label);
  464. _search_text_label->add_theme_font_override("font", EditorNode::get_singleton()->get_gui_base()->get_theme_font(SNAME("source"), SNAME("EditorFonts")));
  465. _search_text_label->add_theme_font_size_override("font_size", EditorNode::get_singleton()->get_gui_base()->get_theme_font_size(SNAME("source_size"), SNAME("EditorFonts")));
  466. hbc->add_child(_search_text_label);
  467. _progress_bar = memnew(ProgressBar);
  468. _progress_bar->set_h_size_flags(SIZE_EXPAND_FILL);
  469. _progress_bar->set_v_size_flags(SIZE_SHRINK_CENTER);
  470. hbc->add_child(_progress_bar);
  471. set_progress_visible(false);
  472. _status_label = memnew(Label);
  473. hbc->add_child(_status_label);
  474. _refresh_button = memnew(Button);
  475. _refresh_button->set_text(TTR("Refresh"));
  476. _refresh_button->connect("pressed", callable_mp(this, &FindInFilesPanel::_on_refresh_button_clicked));
  477. _refresh_button->hide();
  478. hbc->add_child(_refresh_button);
  479. _cancel_button = memnew(Button);
  480. _cancel_button->set_text(TTR("Cancel"));
  481. _cancel_button->connect("pressed", callable_mp(this, &FindInFilesPanel::_on_cancel_button_clicked));
  482. _cancel_button->hide();
  483. hbc->add_child(_cancel_button);
  484. vbc->add_child(hbc);
  485. }
  486. _results_display = memnew(Tree);
  487. _results_display->add_theme_font_override("font", EditorNode::get_singleton()->get_gui_base()->get_theme_font(SNAME("source"), SNAME("EditorFonts")));
  488. _results_display->add_theme_font_size_override("font_size", EditorNode::get_singleton()->get_gui_base()->get_theme_font_size(SNAME("source_size"), SNAME("EditorFonts")));
  489. _results_display->set_v_size_flags(SIZE_EXPAND_FILL);
  490. _results_display->connect("item_selected", callable_mp(this, &FindInFilesPanel::_on_result_selected));
  491. _results_display->connect("item_edited", callable_mp(this, &FindInFilesPanel::_on_item_edited));
  492. _results_display->set_hide_root(true);
  493. _results_display->set_select_mode(Tree::SELECT_ROW);
  494. _results_display->set_allow_rmb_select(true);
  495. _results_display->create_item(); // Root
  496. vbc->add_child(_results_display);
  497. _with_replace = false;
  498. {
  499. _replace_container = memnew(HBoxContainer);
  500. Label *replace_label = memnew(Label);
  501. replace_label->set_text(TTR("Replace: "));
  502. _replace_container->add_child(replace_label);
  503. _replace_line_edit = memnew(LineEdit);
  504. _replace_line_edit->set_h_size_flags(SIZE_EXPAND_FILL);
  505. _replace_line_edit->connect("text_changed", callable_mp(this, &FindInFilesPanel::_on_replace_text_changed));
  506. _replace_container->add_child(_replace_line_edit);
  507. _replace_all_button = memnew(Button);
  508. _replace_all_button->set_text(TTR("Replace all (no undo)"));
  509. _replace_all_button->connect("pressed", callable_mp(this, &FindInFilesPanel::_on_replace_all_clicked));
  510. _replace_container->add_child(_replace_all_button);
  511. _replace_container->hide();
  512. vbc->add_child(_replace_container);
  513. }
  514. }
  515. void FindInFilesPanel::set_with_replace(bool with_replace) {
  516. _with_replace = with_replace;
  517. _replace_container->set_visible(with_replace);
  518. if (with_replace) {
  519. // Results show checkboxes on their left so they can be opted out
  520. _results_display->set_columns(2);
  521. _results_display->set_column_expand(0, false);
  522. _results_display->set_column_custom_minimum_width(0, 48 * EDSCALE);
  523. } else {
  524. // Results are single-cell items
  525. _results_display->set_column_expand(0, true);
  526. _results_display->set_columns(1);
  527. }
  528. }
  529. void FindInFilesPanel::set_replace_text(String text) {
  530. _replace_line_edit->set_text(text);
  531. }
  532. void FindInFilesPanel::clear() {
  533. _file_items.clear();
  534. _result_items.clear();
  535. _results_display->clear();
  536. _results_display->create_item(); // Root
  537. }
  538. void FindInFilesPanel::start_search() {
  539. clear();
  540. _status_label->set_text(TTR("Searching..."));
  541. _search_text_label->set_text(_finder->get_search_text());
  542. set_process(true);
  543. set_progress_visible(true);
  544. _finder->start();
  545. update_replace_buttons();
  546. _refresh_button->hide();
  547. _cancel_button->show();
  548. }
  549. void FindInFilesPanel::stop_search() {
  550. _finder->stop();
  551. _status_label->set_text("");
  552. update_replace_buttons();
  553. set_progress_visible(false);
  554. _refresh_button->show();
  555. _cancel_button->hide();
  556. }
  557. void FindInFilesPanel::_notification(int p_what) {
  558. if (p_what == NOTIFICATION_PROCESS) {
  559. _progress_bar->set_as_ratio(_finder->get_progress());
  560. } else if (p_what == NOTIFICATION_THEME_CHANGED) {
  561. _search_text_label->add_theme_font_override("font", get_theme_font(SNAME("source"), SNAME("EditorFonts")));
  562. _results_display->add_theme_font_override("font", get_theme_font(SNAME("source"), SNAME("EditorFonts")));
  563. }
  564. }
  565. void FindInFilesPanel::_on_result_found(String fpath, int line_number, int begin, int end, String text) {
  566. TreeItem *file_item;
  567. Map<String, TreeItem *>::Element *E = _file_items.find(fpath);
  568. if (E == nullptr) {
  569. file_item = _results_display->create_item();
  570. file_item->set_text(0, fpath);
  571. file_item->set_metadata(0, fpath);
  572. // The width of this column is restrained to checkboxes, but that doesn't make sense for the parent items,
  573. // so we override their width so they can expand to full width
  574. file_item->set_expand_right(0, true);
  575. _file_items[fpath] = file_item;
  576. } else {
  577. file_item = E->value();
  578. }
  579. int text_index = _with_replace ? 1 : 0;
  580. TreeItem *item = _results_display->create_item(file_item);
  581. // Do this first because it resets properties of the cell...
  582. item->set_cell_mode(text_index, TreeItem::CELL_MODE_CUSTOM);
  583. // Trim result item line
  584. int old_text_size = text.size();
  585. text = text.strip_edges(true, false);
  586. int chars_removed = old_text_size - text.size();
  587. String start = vformat("%3s: ", line_number);
  588. item->set_text(text_index, start + text);
  589. item->set_custom_draw(text_index, this, "_draw_result_text");
  590. Result r;
  591. r.line_number = line_number;
  592. r.begin = begin;
  593. r.end = end;
  594. r.begin_trimmed = begin - chars_removed + start.size() - 1;
  595. _result_items[item] = r;
  596. if (_with_replace) {
  597. item->set_cell_mode(0, TreeItem::CELL_MODE_CHECK);
  598. item->set_checked(0, true);
  599. item->set_editable(0, true);
  600. }
  601. }
  602. void FindInFilesPanel::draw_result_text(Object *item_obj, Rect2 rect) {
  603. TreeItem *item = Object::cast_to<TreeItem>(item_obj);
  604. if (!item) {
  605. return;
  606. }
  607. Map<TreeItem *, Result>::Element *E = _result_items.find(item);
  608. if (!E) {
  609. return;
  610. }
  611. Result r = E->value();
  612. String item_text = item->get_text(_with_replace ? 1 : 0);
  613. Ref<Font> font = _results_display->get_theme_font(SNAME("font"));
  614. int font_size = _results_display->get_theme_font_size(SNAME("font_size"));
  615. Rect2 match_rect = rect;
  616. match_rect.position.x += font->get_string_size(item_text.left(r.begin_trimmed), font_size).x;
  617. match_rect.size.x = font->get_string_size(_search_text_label->get_text(), font_size).x;
  618. match_rect.position.y += 1 * EDSCALE;
  619. match_rect.size.y -= 2 * EDSCALE;
  620. // Use the inverted accent color to help match rectangles stand out even on the currently selected line.
  621. _results_display->draw_rect(match_rect, get_theme_color(SNAME("accent_color"), SNAME("Editor")).inverted() * Color(1, 1, 1, 0.5));
  622. // Text is drawn by Tree already.
  623. }
  624. void FindInFilesPanel::_on_item_edited() {
  625. TreeItem *item = _results_display->get_selected();
  626. if (item->is_checked(0)) {
  627. item->set_custom_color(1, _results_display->get_theme_color(SNAME("font_color")));
  628. } else {
  629. // Grey out
  630. Color color = _results_display->get_theme_color(SNAME("font_color"));
  631. color.a /= 2.0;
  632. item->set_custom_color(1, color);
  633. }
  634. }
  635. void FindInFilesPanel::_on_finished() {
  636. String results_text;
  637. int result_count = _result_items.size();
  638. int file_count = _file_items.size();
  639. if (result_count == 1 && file_count == 1) {
  640. results_text = vformat(TTR("%d match in %d file."), result_count, file_count);
  641. } else if (result_count != 1 && file_count == 1) {
  642. results_text = vformat(TTR("%d matches in %d file."), result_count, file_count);
  643. } else {
  644. results_text = vformat(TTR("%d matches in %d files."), result_count, file_count);
  645. }
  646. _status_label->set_text(results_text);
  647. update_replace_buttons();
  648. set_progress_visible(false);
  649. _refresh_button->show();
  650. _cancel_button->hide();
  651. }
  652. void FindInFilesPanel::_on_refresh_button_clicked() {
  653. start_search();
  654. }
  655. void FindInFilesPanel::_on_cancel_button_clicked() {
  656. stop_search();
  657. }
  658. void FindInFilesPanel::_on_result_selected() {
  659. TreeItem *item = _results_display->get_selected();
  660. Map<TreeItem *, Result>::Element *E = _result_items.find(item);
  661. if (E == nullptr) {
  662. return;
  663. }
  664. Result r = E->value();
  665. TreeItem *file_item = item->get_parent();
  666. String fpath = file_item->get_metadata(0);
  667. emit_signal(SNAME(SIGNAL_RESULT_SELECTED), fpath, r.line_number, r.begin, r.end);
  668. }
  669. void FindInFilesPanel::_on_replace_text_changed(String text) {
  670. update_replace_buttons();
  671. }
  672. void FindInFilesPanel::_on_replace_all_clicked() {
  673. String replace_text = get_replace_text();
  674. PackedStringArray modified_files;
  675. for (KeyValue<String, TreeItem *> &E : _file_items) {
  676. TreeItem *file_item = E.value;
  677. String fpath = file_item->get_metadata(0);
  678. Vector<Result> locations;
  679. for (TreeItem *item = file_item->get_first_child(); item; item = item->get_next()) {
  680. if (!item->is_checked(0)) {
  681. continue;
  682. }
  683. Map<TreeItem *, Result>::Element *F = _result_items.find(item);
  684. ERR_FAIL_COND(F == nullptr);
  685. locations.push_back(F->value());
  686. }
  687. if (locations.size() != 0) {
  688. // Results are sorted by file, so we can batch replaces
  689. apply_replaces_in_file(fpath, locations, replace_text);
  690. modified_files.push_back(fpath);
  691. }
  692. }
  693. // Hide replace bar so we can't trigger the action twice without doing a new search
  694. _replace_container->hide();
  695. emit_signal(SNAME(SIGNAL_FILES_MODIFIED), modified_files);
  696. }
  697. // Same as get_line, but preserves line ending characters
  698. class ConservativeGetLine {
  699. public:
  700. String get_line(FileAccess *f) {
  701. _line_buffer.clear();
  702. char32_t c = f->get_8();
  703. while (!f->eof_reached()) {
  704. if (c == '\n') {
  705. _line_buffer.push_back(c);
  706. _line_buffer.push_back(0);
  707. return String::utf8(_line_buffer.ptr());
  708. } else if (c == '\0') {
  709. _line_buffer.push_back(c);
  710. return String::utf8(_line_buffer.ptr());
  711. } else if (c != '\r') {
  712. _line_buffer.push_back(c);
  713. }
  714. c = f->get_8();
  715. }
  716. _line_buffer.push_back(0);
  717. return String::utf8(_line_buffer.ptr());
  718. }
  719. private:
  720. Vector<char> _line_buffer;
  721. };
  722. void FindInFilesPanel::apply_replaces_in_file(String fpath, const Vector<Result> &locations, String new_text) {
  723. // If the file is already open, I assume the editor will reload it.
  724. // If there are unsaved changes, the user will be asked on focus,
  725. // however that means either losing changes or losing replaces.
  726. FileAccessRef f = FileAccess::open(fpath, FileAccess::READ);
  727. ERR_FAIL_COND_MSG(!f, "Cannot open file from path '" + fpath + "'.");
  728. String buffer;
  729. int current_line = 1;
  730. ConservativeGetLine conservative;
  731. String line = conservative.get_line(f);
  732. String search_text = _finder->get_search_text();
  733. int offset = 0;
  734. for (int i = 0; i < locations.size(); ++i) {
  735. int repl_line_number = locations[i].line_number;
  736. while (current_line < repl_line_number) {
  737. buffer += line;
  738. line = conservative.get_line(f);
  739. ++current_line;
  740. offset = 0;
  741. }
  742. int repl_begin = locations[i].begin + offset;
  743. int repl_end = locations[i].end + offset;
  744. int _;
  745. if (!find_next(line, search_text, repl_begin, _finder->is_match_case(), _finder->is_whole_words(), _, _)) {
  746. // Make sure the replace is still valid in case the file was tampered with.
  747. 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)));
  748. continue;
  749. }
  750. line = line.left(repl_begin) + new_text + line.substr(repl_end);
  751. // keep an offset in case there are successive replaces in the same line
  752. offset += new_text.length() - (repl_end - repl_begin);
  753. }
  754. buffer += line;
  755. while (!f->eof_reached()) {
  756. buffer += conservative.get_line(f);
  757. }
  758. // Now the modified contents are in the buffer, rewrite the file with our changes
  759. Error err = f->reopen(fpath, FileAccess::WRITE);
  760. ERR_FAIL_COND_MSG(err != OK, "Cannot create file in path '" + fpath + "'.");
  761. f->store_string(buffer);
  762. f->close();
  763. }
  764. String FindInFilesPanel::get_replace_text() {
  765. return _replace_line_edit->get_text();
  766. }
  767. void FindInFilesPanel::update_replace_buttons() {
  768. bool disabled = _finder->is_searching();
  769. _replace_all_button->set_disabled(disabled);
  770. }
  771. void FindInFilesPanel::set_progress_visible(bool visible) {
  772. _progress_bar->set_self_modulate(Color(1, 1, 1, visible ? 1 : 0));
  773. }
  774. void FindInFilesPanel::_bind_methods() {
  775. ClassDB::bind_method("_on_result_found", &FindInFilesPanel::_on_result_found);
  776. ClassDB::bind_method("_on_finished", &FindInFilesPanel::_on_finished);
  777. ClassDB::bind_method("_draw_result_text", &FindInFilesPanel::draw_result_text);
  778. ADD_SIGNAL(MethodInfo(SIGNAL_RESULT_SELECTED,
  779. PropertyInfo(Variant::STRING, "path"),
  780. PropertyInfo(Variant::INT, "line_number"),
  781. PropertyInfo(Variant::INT, "begin"),
  782. PropertyInfo(Variant::INT, "end")));
  783. ADD_SIGNAL(MethodInfo(SIGNAL_FILES_MODIFIED, PropertyInfo(Variant::STRING, "paths")));
  784. }