find_in_files.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934
  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/os/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 PoolVectors
  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(CharType 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. FindInFiles::FindInFiles() {
  78. _searching = false;
  79. _whole_words = true;
  80. _match_case = true;
  81. }
  82. void FindInFiles::set_search_text(String p_pattern) {
  83. _pattern = p_pattern;
  84. }
  85. void FindInFiles::set_whole_words(bool p_whole_word) {
  86. _whole_words = p_whole_word;
  87. }
  88. void FindInFiles::set_match_case(bool p_match_case) {
  89. _match_case = p_match_case;
  90. }
  91. void FindInFiles::set_folder(String folder) {
  92. _root_dir = folder;
  93. }
  94. void FindInFiles::set_filter(const Set<String> &exts) {
  95. _extension_filter = exts;
  96. }
  97. void FindInFiles::_notification(int p_notification) {
  98. if (p_notification == NOTIFICATION_PROCESS) {
  99. _process();
  100. }
  101. }
  102. void FindInFiles::start() {
  103. if (_pattern == "") {
  104. print_verbose("Nothing to search, pattern is empty");
  105. emit_signal(SIGNAL_FINISHED);
  106. return;
  107. }
  108. if (_extension_filter.size() == 0) {
  109. print_verbose("Nothing to search, filter matches no files");
  110. emit_signal(SIGNAL_FINISHED);
  111. return;
  112. }
  113. // Init search
  114. _current_dir = "";
  115. PoolStringArray init_folder;
  116. init_folder.append(_root_dir);
  117. _folders_stack.clear();
  118. _folders_stack.push_back(init_folder);
  119. _initial_files_count = 0;
  120. _searching = true;
  121. set_process(true);
  122. }
  123. void FindInFiles::stop() {
  124. _searching = false;
  125. _current_dir = "";
  126. set_process(false);
  127. }
  128. void FindInFiles::_process() {
  129. // This part can be moved to a thread if needed
  130. OS &os = *OS::get_singleton();
  131. float time_before = os.get_ticks_msec();
  132. while (is_processing()) {
  133. _iterate();
  134. float elapsed = (os.get_ticks_msec() - time_before);
  135. if (elapsed > 1000.0 / 120.0) {
  136. break;
  137. }
  138. }
  139. }
  140. void FindInFiles::_iterate() {
  141. if (_folders_stack.size() != 0) {
  142. // Scan folders first so we can build a list of files and have progress info later
  143. PoolStringArray &folders_to_scan = _folders_stack.write[_folders_stack.size() - 1];
  144. if (folders_to_scan.size() != 0) {
  145. // Scan one folder below
  146. String folder_name = folders_to_scan[folders_to_scan.size() - 1];
  147. pop_back(folders_to_scan);
  148. _current_dir = _current_dir.plus_file(folder_name);
  149. PoolStringArray sub_dirs;
  150. _scan_dir("res://" + _current_dir, sub_dirs);
  151. _folders_stack.push_back(sub_dirs);
  152. } else {
  153. // Go back one level
  154. pop_back(_folders_stack);
  155. _current_dir = _current_dir.get_base_dir();
  156. if (_folders_stack.size() == 0) {
  157. // All folders scanned
  158. _initial_files_count = _files_to_scan.size();
  159. }
  160. }
  161. } else if (_files_to_scan.size() != 0) {
  162. // Then scan files
  163. String fpath = _files_to_scan[_files_to_scan.size() - 1];
  164. pop_back(_files_to_scan);
  165. _scan_file(fpath);
  166. } else {
  167. print_verbose("Search complete");
  168. set_process(false);
  169. _current_dir = "";
  170. _searching = false;
  171. emit_signal(SIGNAL_FINISHED);
  172. }
  173. }
  174. float FindInFiles::get_progress() const {
  175. if (_initial_files_count != 0) {
  176. return static_cast<float>(_initial_files_count - _files_to_scan.size()) / static_cast<float>(_initial_files_count);
  177. }
  178. return 0;
  179. }
  180. void FindInFiles::_scan_dir(String path, PoolStringArray &out_folders) {
  181. DirAccessRef dir = DirAccess::open(path);
  182. if (!dir) {
  183. print_verbose("Cannot open directory! " + path);
  184. return;
  185. }
  186. dir->list_dir_begin();
  187. for (int i = 0; i < 1000; ++i) {
  188. String file = dir->get_next();
  189. if (file == "") {
  190. break;
  191. }
  192. // Ignore special dirs (such as .git and .import)
  193. if (file == "." || file == ".." || file.begins_with(".")) {
  194. continue;
  195. }
  196. if (dir->current_is_hidden()) {
  197. continue;
  198. }
  199. if (dir->current_is_dir()) {
  200. out_folders.append(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(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_custom_minimum_size(Size2(500 * EDSCALE, 0));
  242. set_title(TTR("Find in Files"));
  243. VBoxContainer *vbc = memnew(VBoxContainer);
  244. vbc->set_anchor_and_margin(MARGIN_LEFT, ANCHOR_BEGIN, 8 * EDSCALE);
  245. vbc->set_anchor_and_margin(MARGIN_TOP, ANCHOR_BEGIN, 8 * EDSCALE);
  246. vbc->set_anchor_and_margin(MARGIN_RIGHT, ANCHOR_END, -8 * EDSCALE);
  247. vbc->set_anchor_and_margin(MARGIN_BOTTOM, 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(SIZE_EXPAND_FILL);
  257. _search_text_line_edit->connect("text_changed", this, "_on_search_text_modified");
  258. _search_text_line_edit->connect("text_entered", this, "_on_search_text_entered");
  259. gc->add_child(_search_text_line_edit);
  260. gc->add_child(memnew(Control)); // Space to maintain the grid aligned.
  261. {
  262. HBoxContainer *hbc = memnew(HBoxContainer);
  263. _whole_words_checkbox = memnew(CheckBox);
  264. _whole_words_checkbox->set_text(TTR("Whole Words"));
  265. hbc->add_child(_whole_words_checkbox);
  266. _match_case_checkbox = memnew(CheckBox);
  267. _match_case_checkbox->set_text(TTR("Match Case"));
  268. hbc->add_child(_match_case_checkbox);
  269. gc->add_child(hbc);
  270. }
  271. Label *folder_label = memnew(Label);
  272. folder_label->set_text(TTR("Folder:"));
  273. gc->add_child(folder_label);
  274. {
  275. HBoxContainer *hbc = memnew(HBoxContainer);
  276. Label *prefix_label = memnew(Label);
  277. prefix_label->set_text("res://");
  278. hbc->add_child(prefix_label);
  279. _folder_line_edit = memnew(LineEdit);
  280. _folder_line_edit->set_h_size_flags(SIZE_EXPAND_FILL);
  281. hbc->add_child(_folder_line_edit);
  282. Button *folder_button = memnew(Button);
  283. folder_button->set_text("...");
  284. folder_button->connect("pressed", this, "_on_folder_button_pressed");
  285. hbc->add_child(folder_button);
  286. _folder_dialog = memnew(FileDialog);
  287. _folder_dialog->set_mode(FileDialog::MODE_OPEN_DIR);
  288. _folder_dialog->connect("dir_selected", this, "_on_folder_selected");
  289. add_child(_folder_dialog);
  290. gc->add_child(hbc);
  291. }
  292. Label *filter_label = memnew(Label);
  293. filter_label->set_text(TTR("Filters:"));
  294. filter_label->set_tooltip(TTR("Include the files with the following extensions. Add or remove them in ProjectSettings."));
  295. gc->add_child(filter_label);
  296. _filters_container = memnew(HBoxContainer);
  297. gc->add_child(_filters_container);
  298. _find_button = add_button(TTR("Find..."), false, "find");
  299. _find_button->set_disabled(true);
  300. _replace_button = add_button(TTR("Replace..."), false, "replace");
  301. _replace_button->set_disabled(true);
  302. Button *cancel_button = get_ok();
  303. cancel_button->set_text(TTR("Cancel"));
  304. }
  305. void FindInFilesDialog::set_search_text(String text) {
  306. _search_text_line_edit->set_text(text);
  307. _on_search_text_modified(text);
  308. }
  309. String FindInFilesDialog::get_search_text() const {
  310. String text = _search_text_line_edit->get_text();
  311. return text.strip_edges();
  312. }
  313. bool FindInFilesDialog::is_match_case() const {
  314. return _match_case_checkbox->is_pressed();
  315. }
  316. bool FindInFilesDialog::is_whole_words() const {
  317. return _whole_words_checkbox->is_pressed();
  318. }
  319. String FindInFilesDialog::get_folder() const {
  320. String text = _folder_line_edit->get_text();
  321. return text.strip_edges();
  322. }
  323. Set<String> FindInFilesDialog::get_filter() const {
  324. // could check the _filters_preferences but it might not have been generated yet.
  325. Set<String> filters;
  326. for (int i = 0; i < _filters_container->get_child_count(); ++i) {
  327. CheckBox *cb = (CheckBox *)_filters_container->get_child(i);
  328. if (cb->is_pressed()) {
  329. filters.insert(cb->get_text());
  330. }
  331. }
  332. return filters;
  333. }
  334. void FindInFilesDialog::_notification(int p_what) {
  335. if (p_what == NOTIFICATION_VISIBILITY_CHANGED) {
  336. if (is_visible()) {
  337. // Doesn't work more than once if not deferred...
  338. _search_text_line_edit->call_deferred("grab_focus");
  339. _search_text_line_edit->select_all();
  340. // Extensions might have changed in the meantime, we clean them and instance them again.
  341. for (int i = 0; i < _filters_container->get_child_count(); i++) {
  342. _filters_container->get_child(i)->queue_delete();
  343. }
  344. Array exts = ProjectSettings::get_singleton()->get("editor/search_in_file_extensions");
  345. for (int i = 0; i < exts.size(); ++i) {
  346. CheckBox *cb = memnew(CheckBox);
  347. cb->set_text(exts[i]);
  348. if (!_filters_preferences.has(exts[i])) {
  349. _filters_preferences[exts[i]] = true;
  350. }
  351. cb->set_pressed(_filters_preferences[exts[i]]);
  352. _filters_container->add_child(cb);
  353. }
  354. }
  355. }
  356. }
  357. void FindInFilesDialog::_on_folder_button_pressed() {
  358. _folder_dialog->popup_centered_ratio();
  359. }
  360. void FindInFilesDialog::custom_action(const String &p_action) {
  361. for (int i = 0; i < _filters_container->get_child_count(); ++i) {
  362. CheckBox *cb = (CheckBox *)_filters_container->get_child(i);
  363. _filters_preferences[cb->get_text()] = cb->is_pressed();
  364. }
  365. if (p_action == "find") {
  366. emit_signal(SIGNAL_FIND_REQUESTED);
  367. hide();
  368. } else if (p_action == "replace") {
  369. emit_signal(SIGNAL_REPLACE_REQUESTED);
  370. hide();
  371. }
  372. }
  373. void FindInFilesDialog::_on_search_text_modified(String text) {
  374. ERR_FAIL_COND(!_find_button);
  375. ERR_FAIL_COND(!_replace_button);
  376. _find_button->set_disabled(get_search_text().empty());
  377. _replace_button->set_disabled(get_search_text().empty());
  378. }
  379. void FindInFilesDialog::_on_search_text_entered(String text) {
  380. // This allows to trigger a global search without leaving the keyboard
  381. if (!_find_button->is_disabled()) {
  382. custom_action("find");
  383. }
  384. }
  385. void FindInFilesDialog::_on_folder_selected(String path) {
  386. int i = path.find("://");
  387. if (i != -1) {
  388. path = path.right(i + 3);
  389. }
  390. _folder_line_edit->set_text(path);
  391. }
  392. void FindInFilesDialog::_bind_methods() {
  393. ClassDB::bind_method("_on_folder_button_pressed", &FindInFilesDialog::_on_folder_button_pressed);
  394. ClassDB::bind_method("_on_folder_selected", &FindInFilesDialog::_on_folder_selected);
  395. ClassDB::bind_method("_on_search_text_modified", &FindInFilesDialog::_on_search_text_modified);
  396. ClassDB::bind_method("_on_search_text_entered", &FindInFilesDialog::_on_search_text_entered);
  397. ADD_SIGNAL(MethodInfo(SIGNAL_FIND_REQUESTED));
  398. ADD_SIGNAL(MethodInfo(SIGNAL_REPLACE_REQUESTED));
  399. }
  400. //-----------------------------------------------------------------------------
  401. const char *FindInFilesPanel::SIGNAL_RESULT_SELECTED = "result_selected";
  402. const char *FindInFilesPanel::SIGNAL_FILES_MODIFIED = "files_modified";
  403. FindInFilesPanel::FindInFilesPanel() {
  404. _finder = memnew(FindInFiles);
  405. _finder->connect(FindInFiles::SIGNAL_RESULT_FOUND, this, "_on_result_found");
  406. _finder->connect(FindInFiles::SIGNAL_FINISHED, this, "_on_finished");
  407. add_child(_finder);
  408. VBoxContainer *vbc = memnew(VBoxContainer);
  409. vbc->set_anchor_and_margin(MARGIN_LEFT, ANCHOR_BEGIN, 0);
  410. vbc->set_anchor_and_margin(MARGIN_TOP, ANCHOR_BEGIN, 0);
  411. vbc->set_anchor_and_margin(MARGIN_RIGHT, ANCHOR_END, 0);
  412. vbc->set_anchor_and_margin(MARGIN_BOTTOM, ANCHOR_END, 0);
  413. add_child(vbc);
  414. {
  415. HBoxContainer *hbc = memnew(HBoxContainer);
  416. Label *find_label = memnew(Label);
  417. find_label->set_text(TTR("Find: "));
  418. hbc->add_child(find_label);
  419. _search_text_label = memnew(Label);
  420. _search_text_label->add_font_override("font", EditorNode::get_singleton()->get_gui_base()->get_font("source", "EditorFonts"));
  421. hbc->add_child(_search_text_label);
  422. _progress_bar = memnew(ProgressBar);
  423. _progress_bar->set_h_size_flags(SIZE_EXPAND_FILL);
  424. _progress_bar->set_v_size_flags(SIZE_SHRINK_CENTER);
  425. hbc->add_child(_progress_bar);
  426. set_progress_visible(false);
  427. _status_label = memnew(Label);
  428. hbc->add_child(_status_label);
  429. _refresh_button = memnew(Button);
  430. _refresh_button->set_text(TTR("Refresh"));
  431. _refresh_button->connect("pressed", this, "_on_refresh_button_clicked");
  432. _refresh_button->hide();
  433. hbc->add_child(_refresh_button);
  434. _cancel_button = memnew(Button);
  435. _cancel_button->set_text(TTR("Cancel"));
  436. _cancel_button->connect("pressed", this, "_on_cancel_button_clicked");
  437. _cancel_button->hide();
  438. hbc->add_child(_cancel_button);
  439. vbc->add_child(hbc);
  440. }
  441. _results_display = memnew(Tree);
  442. _results_display->add_font_override("font", EditorNode::get_singleton()->get_gui_base()->get_font("source", "EditorFonts"));
  443. _results_display->set_v_size_flags(SIZE_EXPAND_FILL);
  444. _results_display->connect("item_selected", this, "_on_result_selected");
  445. _results_display->connect("item_edited", this, "_on_item_edited");
  446. _results_display->set_hide_root(true);
  447. _results_display->set_select_mode(Tree::SELECT_ROW);
  448. _results_display->set_allow_rmb_select(true);
  449. _results_display->create_item(); // Root
  450. vbc->add_child(_results_display);
  451. _with_replace = false;
  452. {
  453. _replace_container = memnew(HBoxContainer);
  454. Label *replace_label = memnew(Label);
  455. replace_label->set_text(TTR("Replace: "));
  456. _replace_container->add_child(replace_label);
  457. _replace_line_edit = memnew(LineEdit);
  458. _replace_line_edit->set_h_size_flags(SIZE_EXPAND_FILL);
  459. _replace_line_edit->connect("text_changed", this, "_on_replace_text_changed");
  460. _replace_container->add_child(_replace_line_edit);
  461. _replace_all_button = memnew(Button);
  462. _replace_all_button->set_text(TTR("Replace all (no undo)"));
  463. _replace_all_button->connect("pressed", this, "_on_replace_all_clicked");
  464. _replace_container->add_child(_replace_all_button);
  465. _replace_container->hide();
  466. vbc->add_child(_replace_container);
  467. }
  468. }
  469. void FindInFilesPanel::set_with_replace(bool with_replace) {
  470. _with_replace = with_replace;
  471. _replace_container->set_visible(with_replace);
  472. if (with_replace) {
  473. // Results show checkboxes on their left so they can be opted out
  474. _results_display->set_columns(2);
  475. _results_display->set_column_expand(0, false);
  476. _results_display->set_column_min_width(0, 48 * EDSCALE);
  477. } else {
  478. // Results are single-cell items
  479. _results_display->set_column_expand(0, true);
  480. _results_display->set_columns(1);
  481. }
  482. }
  483. void FindInFilesPanel::clear() {
  484. _file_items.clear();
  485. _result_items.clear();
  486. _results_display->clear();
  487. _results_display->create_item(); // Root
  488. }
  489. void FindInFilesPanel::start_search() {
  490. clear();
  491. _status_label->set_text(TTR("Searching..."));
  492. _search_text_label->set_text(_finder->get_search_text());
  493. set_process(true);
  494. set_progress_visible(true);
  495. _finder->start();
  496. update_replace_buttons();
  497. _refresh_button->hide();
  498. _cancel_button->show();
  499. }
  500. void FindInFilesPanel::stop_search() {
  501. _finder->stop();
  502. _status_label->set_text("");
  503. update_replace_buttons();
  504. set_progress_visible(false);
  505. _refresh_button->show();
  506. _cancel_button->hide();
  507. }
  508. void FindInFilesPanel::_notification(int p_what) {
  509. if (p_what == NOTIFICATION_PROCESS) {
  510. _progress_bar->set_as_ratio(_finder->get_progress());
  511. } else if (p_what == NOTIFICATION_THEME_CHANGED) {
  512. _search_text_label->add_font_override("font", get_font("source", "EditorFonts"));
  513. _results_display->add_font_override("font", get_font("source", "EditorFonts"));
  514. }
  515. }
  516. void FindInFilesPanel::_on_result_found(String fpath, int line_number, int begin, int end, String text) {
  517. TreeItem *file_item;
  518. Map<String, TreeItem *>::Element *E = _file_items.find(fpath);
  519. if (E == nullptr) {
  520. file_item = _results_display->create_item();
  521. file_item->set_text(0, fpath);
  522. file_item->set_metadata(0, fpath);
  523. // The width of this column is restrained to checkboxes, but that doesn't make sense for the parent items,
  524. // so we override their width so they can expand to full width
  525. file_item->set_expand_right(0, true);
  526. _file_items[fpath] = file_item;
  527. } else {
  528. file_item = E->value();
  529. }
  530. int text_index = _with_replace ? 1 : 0;
  531. TreeItem *item = _results_display->create_item(file_item);
  532. // Do this first because it resets properties of the cell...
  533. item->set_cell_mode(text_index, TreeItem::CELL_MODE_CUSTOM);
  534. // Trim result item line
  535. int old_text_size = text.size();
  536. text = text.strip_edges(true, false);
  537. int chars_removed = old_text_size - text.size();
  538. String start = vformat("%3s: ", line_number);
  539. item->set_text(text_index, start + text);
  540. item->set_custom_draw(text_index, this, "_draw_result_text");
  541. Result r;
  542. r.line_number = line_number;
  543. r.begin = begin;
  544. r.end = end;
  545. r.begin_trimmed = begin - chars_removed + start.size() - 1;
  546. _result_items[item] = r;
  547. if (_with_replace) {
  548. item->set_cell_mode(0, TreeItem::CELL_MODE_CHECK);
  549. item->set_checked(0, true);
  550. item->set_editable(0, true);
  551. }
  552. }
  553. void FindInFilesPanel::draw_result_text(Object *item_obj, Rect2 rect) {
  554. TreeItem *item = Object::cast_to<TreeItem>(item_obj);
  555. if (!item) {
  556. return;
  557. }
  558. Map<TreeItem *, Result>::Element *E = _result_items.find(item);
  559. if (!E) {
  560. return;
  561. }
  562. Result r = E->value();
  563. String item_text = item->get_text(_with_replace ? 1 : 0);
  564. Ref<Font> font = _results_display->get_font("font");
  565. Rect2 match_rect = rect;
  566. match_rect.position.x += font->get_string_size(item_text.left(r.begin_trimmed)).x;
  567. match_rect.size.x = font->get_string_size(_search_text_label->get_text()).x;
  568. match_rect.position.y += 1 * EDSCALE;
  569. match_rect.size.y -= 2 * EDSCALE;
  570. // Use the inverted accent color to help match rectangles stand out even on the currently selected line.
  571. _results_display->draw_rect(match_rect, get_color("accent_color", "Editor").inverted() * Color(1, 1, 1, 0.5));
  572. // Text is drawn by Tree already.
  573. }
  574. void FindInFilesPanel::_on_item_edited() {
  575. TreeItem *item = _results_display->get_selected();
  576. if (item->is_checked(0)) {
  577. item->set_custom_color(1, _results_display->get_color("font_color"));
  578. } else {
  579. // Grey out
  580. Color color = _results_display->get_color("font_color");
  581. color.a /= 2.0;
  582. item->set_custom_color(1, color);
  583. }
  584. }
  585. void FindInFilesPanel::_on_finished() {
  586. String results_text;
  587. int result_count = _result_items.size();
  588. int file_count = _file_items.size();
  589. if (result_count == 1 && file_count == 1) {
  590. results_text = vformat(TTR("%d match in %d file."), result_count, file_count);
  591. } else if (result_count != 1 && file_count == 1) {
  592. results_text = vformat(TTR("%d matches in %d file."), result_count, file_count);
  593. } else {
  594. results_text = vformat(TTR("%d matches in %d files."), result_count, file_count);
  595. }
  596. _status_label->set_text(results_text);
  597. update_replace_buttons();
  598. set_progress_visible(false);
  599. _refresh_button->show();
  600. _cancel_button->hide();
  601. }
  602. void FindInFilesPanel::_on_refresh_button_clicked() {
  603. start_search();
  604. }
  605. void FindInFilesPanel::_on_cancel_button_clicked() {
  606. stop_search();
  607. }
  608. void FindInFilesPanel::_on_result_selected() {
  609. TreeItem *item = _results_display->get_selected();
  610. Map<TreeItem *, Result>::Element *E = _result_items.find(item);
  611. if (E == nullptr) {
  612. return;
  613. }
  614. Result r = E->value();
  615. TreeItem *file_item = item->get_parent();
  616. String fpath = file_item->get_metadata(0);
  617. emit_signal(SIGNAL_RESULT_SELECTED, fpath, r.line_number, r.begin, r.end);
  618. }
  619. void FindInFilesPanel::_on_replace_text_changed(String text) {
  620. update_replace_buttons();
  621. }
  622. void FindInFilesPanel::_on_replace_all_clicked() {
  623. String replace_text = get_replace_text();
  624. PoolStringArray modified_files;
  625. for (Map<String, TreeItem *>::Element *E = _file_items.front(); E; E = E->next()) {
  626. TreeItem *file_item = E->value();
  627. String fpath = file_item->get_metadata(0);
  628. Vector<Result> locations;
  629. for (TreeItem *item = file_item->get_children(); item; item = item->get_next()) {
  630. if (!item->is_checked(0)) {
  631. continue;
  632. }
  633. Map<TreeItem *, Result>::Element *F = _result_items.find(item);
  634. ERR_FAIL_COND(F == nullptr);
  635. locations.push_back(F->value());
  636. }
  637. if (locations.size() != 0) {
  638. // Results are sorted by file, so we can batch replaces
  639. apply_replaces_in_file(fpath, locations, replace_text);
  640. modified_files.append(fpath);
  641. }
  642. }
  643. // Hide replace bar so we can't trigger the action twice without doing a new search
  644. _replace_container->hide();
  645. emit_signal(SIGNAL_FILES_MODIFIED, modified_files);
  646. }
  647. // Same as get_line, but preserves line ending characters
  648. class ConservativeGetLine {
  649. public:
  650. String get_line(FileAccess *f) {
  651. _line_buffer.clear();
  652. CharType c = f->get_8();
  653. while (!f->eof_reached()) {
  654. if (c == '\n') {
  655. _line_buffer.push_back(c);
  656. _line_buffer.push_back(0);
  657. return String::utf8(_line_buffer.ptr());
  658. } else if (c == '\0') {
  659. _line_buffer.push_back(c);
  660. return String::utf8(_line_buffer.ptr());
  661. } else if (c != '\r') {
  662. _line_buffer.push_back(c);
  663. }
  664. c = f->get_8();
  665. }
  666. _line_buffer.push_back(0);
  667. return String::utf8(_line_buffer.ptr());
  668. }
  669. private:
  670. Vector<char> _line_buffer;
  671. };
  672. void FindInFilesPanel::apply_replaces_in_file(String fpath, const Vector<Result> &locations, String new_text) {
  673. // If the file is already open, I assume the editor will reload it.
  674. // If there are unsaved changes, the user will be asked on focus,
  675. // however that means either losing changes or losing replaces.
  676. FileAccessRef f = FileAccess::open(fpath, FileAccess::READ);
  677. ERR_FAIL_COND_MSG(!f, "Cannot open file from path '" + fpath + "'.");
  678. String buffer;
  679. int current_line = 1;
  680. ConservativeGetLine conservative;
  681. String line = conservative.get_line(f);
  682. String search_text = _finder->get_search_text();
  683. int offset = 0;
  684. for (int i = 0; i < locations.size(); ++i) {
  685. int repl_line_number = locations[i].line_number;
  686. while (current_line < repl_line_number) {
  687. buffer += line;
  688. line = conservative.get_line(f);
  689. ++current_line;
  690. offset = 0;
  691. }
  692. int repl_begin = locations[i].begin + offset;
  693. int repl_end = locations[i].end + offset;
  694. int _;
  695. if (!find_next(line, search_text, repl_begin, _finder->is_match_case(), _finder->is_whole_words(), _, _)) {
  696. // Make sure the replace is still valid in case the file was tampered with.
  697. 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)));
  698. continue;
  699. }
  700. line = line.left(repl_begin) + new_text + line.right(repl_end);
  701. // keep an offset in case there are successive replaces in the same line
  702. offset += new_text.length() - (repl_end - repl_begin);
  703. }
  704. buffer += line;
  705. while (!f->eof_reached()) {
  706. buffer += conservative.get_line(f);
  707. }
  708. // Now the modified contents are in the buffer, rewrite the file with our changes
  709. Error err = f->reopen(fpath, FileAccess::WRITE);
  710. ERR_FAIL_COND_MSG(err != OK, "Cannot create file in path '" + fpath + "'.");
  711. f->store_string(buffer);
  712. f->close();
  713. }
  714. String FindInFilesPanel::get_replace_text() {
  715. return _replace_line_edit->get_text().strip_edges();
  716. }
  717. void FindInFilesPanel::update_replace_buttons() {
  718. bool disabled = _finder->is_searching();
  719. _replace_all_button->set_disabled(disabled);
  720. }
  721. void FindInFilesPanel::set_progress_visible(bool visible) {
  722. _progress_bar->set_self_modulate(Color(1, 1, 1, visible ? 1 : 0));
  723. }
  724. void FindInFilesPanel::_bind_methods() {
  725. ClassDB::bind_method("_on_result_found", &FindInFilesPanel::_on_result_found);
  726. ClassDB::bind_method("_on_item_edited", &FindInFilesPanel::_on_item_edited);
  727. ClassDB::bind_method("_on_finished", &FindInFilesPanel::_on_finished);
  728. ClassDB::bind_method("_on_refresh_button_clicked", &FindInFilesPanel::_on_refresh_button_clicked);
  729. ClassDB::bind_method("_on_cancel_button_clicked", &FindInFilesPanel::_on_cancel_button_clicked);
  730. ClassDB::bind_method("_on_result_selected", &FindInFilesPanel::_on_result_selected);
  731. ClassDB::bind_method("_on_replace_text_changed", &FindInFilesPanel::_on_replace_text_changed);
  732. ClassDB::bind_method("_on_replace_all_clicked", &FindInFilesPanel::_on_replace_all_clicked);
  733. ClassDB::bind_method("_draw_result_text", &FindInFilesPanel::draw_result_text);
  734. ADD_SIGNAL(MethodInfo(SIGNAL_RESULT_SELECTED,
  735. PropertyInfo(Variant::STRING, "path"),
  736. PropertyInfo(Variant::INT, "line_number"),
  737. PropertyInfo(Variant::INT, "begin"),
  738. PropertyInfo(Variant::INT, "end")));
  739. ADD_SIGNAL(MethodInfo(SIGNAL_FILES_MODIFIED, PropertyInfo(Variant::STRING, "paths")));
  740. }