find_in_files.cpp 30 KB

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