find_in_files.cpp 28 KB

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