find_in_files.cpp 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003
  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/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. uint64_t time_before = os.get_ticks_msec();
  132. while (is_processing()) {
  133. _iterate();
  134. uint64_t elapsed = (os.get_ticks_msec() - time_before);
  135. if (elapsed > 8) { // Process again after waiting 8 ticks
  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. // If there is a .gdignore file in the directory, don't bother searching it
  193. if (file == ".gdignore") {
  194. break;
  195. }
  196. // Ignore special dirs (such as .git and project data directory)
  197. String project_data_dir_name = ProjectSettings::get_singleton()->get_project_data_dir_name();
  198. if (file.begins_with(".") || file == project_data_dir_name) {
  199. continue;
  200. }
  201. if (dir->current_is_hidden()) {
  202. continue;
  203. }
  204. if (dir->current_is_dir()) {
  205. out_folders.append(file);
  206. } else {
  207. String file_ext = file.get_extension();
  208. if (_extension_filter.has(file_ext)) {
  209. _files_to_scan.push_back(path.plus_file(file));
  210. }
  211. }
  212. }
  213. }
  214. void FindInFiles::_scan_file(String fpath) {
  215. FileAccessRef f = FileAccess::open(fpath, FileAccess::READ);
  216. if (!f) {
  217. print_verbose(String("Cannot open file ") + fpath);
  218. return;
  219. }
  220. int line_number = 0;
  221. while (!f->eof_reached()) {
  222. // line number starts at 1
  223. ++line_number;
  224. int begin = 0;
  225. int end = 0;
  226. String line = f->get_line();
  227. while (find_next(line, _pattern, end, _match_case, _whole_words, begin, end)) {
  228. emit_signal(SIGNAL_RESULT_FOUND, fpath, line_number, begin, end, line);
  229. }
  230. }
  231. f->close();
  232. }
  233. void FindInFiles::_bind_methods() {
  234. ADD_SIGNAL(MethodInfo(SIGNAL_RESULT_FOUND,
  235. PropertyInfo(Variant::STRING, "path"),
  236. PropertyInfo(Variant::INT, "line_number"),
  237. PropertyInfo(Variant::INT, "begin"),
  238. PropertyInfo(Variant::INT, "end"),
  239. PropertyInfo(Variant::STRING, "text")));
  240. ADD_SIGNAL(MethodInfo(SIGNAL_FINISHED));
  241. }
  242. //-----------------------------------------------------------------------------
  243. const char *FindInFilesDialog::SIGNAL_FIND_REQUESTED = "find_requested";
  244. const char *FindInFilesDialog::SIGNAL_REPLACE_REQUESTED = "replace_requested";
  245. FindInFilesDialog::FindInFilesDialog() {
  246. set_custom_minimum_size(Size2(500 * EDSCALE, 0));
  247. set_title(TTR("Find in Files"));
  248. VBoxContainer *vbc = memnew(VBoxContainer);
  249. vbc->set_anchor_and_margin(MARGIN_LEFT, ANCHOR_BEGIN, 8 * EDSCALE);
  250. vbc->set_anchor_and_margin(MARGIN_TOP, ANCHOR_BEGIN, 8 * EDSCALE);
  251. vbc->set_anchor_and_margin(MARGIN_RIGHT, ANCHOR_END, -8 * EDSCALE);
  252. vbc->set_anchor_and_margin(MARGIN_BOTTOM, ANCHOR_END, -8 * EDSCALE);
  253. add_child(vbc);
  254. GridContainer *gc = memnew(GridContainer);
  255. gc->set_columns(2);
  256. vbc->add_child(gc);
  257. Label *find_label = memnew(Label);
  258. find_label->set_text(TTR("Find:"));
  259. gc->add_child(find_label);
  260. _search_text_line_edit = memnew(LineEdit);
  261. _search_text_line_edit->set_h_size_flags(SIZE_EXPAND_FILL);
  262. _search_text_line_edit->connect("text_changed", this, "_on_search_text_modified");
  263. _search_text_line_edit->connect("text_entered", this, "_on_search_text_entered");
  264. gc->add_child(_search_text_line_edit);
  265. _replace_label = memnew(Label);
  266. _replace_label->set_text(TTR("Replace:"));
  267. _replace_label->hide();
  268. gc->add_child(_replace_label);
  269. _replace_text_line_edit = memnew(LineEdit);
  270. _replace_text_line_edit->set_h_size_flags(SIZE_EXPAND_FILL);
  271. _replace_text_line_edit->connect("text_entered", this, "_on_replace_text_entered");
  272. _replace_text_line_edit->hide();
  273. gc->add_child(_replace_text_line_edit);
  274. gc->add_child(memnew(Control)); // Space to maintain the grid aligned.
  275. {
  276. HBoxContainer *hbc = memnew(HBoxContainer);
  277. _whole_words_checkbox = memnew(CheckBox);
  278. _whole_words_checkbox->set_text(TTR("Whole Words"));
  279. hbc->add_child(_whole_words_checkbox);
  280. _match_case_checkbox = memnew(CheckBox);
  281. _match_case_checkbox->set_text(TTR("Match Case"));
  282. hbc->add_child(_match_case_checkbox);
  283. gc->add_child(hbc);
  284. }
  285. Label *folder_label = memnew(Label);
  286. folder_label->set_text(TTR("Folder:"));
  287. gc->add_child(folder_label);
  288. {
  289. HBoxContainer *hbc = memnew(HBoxContainer);
  290. Label *prefix_label = memnew(Label);
  291. prefix_label->set_text("res://");
  292. hbc->add_child(prefix_label);
  293. _folder_line_edit = memnew(LineEdit);
  294. _folder_line_edit->set_h_size_flags(SIZE_EXPAND_FILL);
  295. hbc->add_child(_folder_line_edit);
  296. Button *folder_button = memnew(Button);
  297. folder_button->set_text("...");
  298. folder_button->connect("pressed", this, "_on_folder_button_pressed");
  299. hbc->add_child(folder_button);
  300. _folder_dialog = memnew(FileDialog);
  301. _folder_dialog->set_mode(FileDialog::MODE_OPEN_DIR);
  302. _folder_dialog->connect("dir_selected", this, "_on_folder_selected");
  303. add_child(_folder_dialog);
  304. gc->add_child(hbc);
  305. }
  306. Label *filter_label = memnew(Label);
  307. filter_label->set_text(TTR("Filters:"));
  308. filter_label->set_tooltip(TTR("Include the files with the following extensions. Add or remove them in ProjectSettings."));
  309. gc->add_child(filter_label);
  310. _filters_container = memnew(HBoxContainer);
  311. gc->add_child(_filters_container);
  312. _find_button = add_button(TTR("Find..."), false, "find");
  313. _find_button->set_disabled(true);
  314. _replace_button = add_button(TTR("Replace..."), false, "replace");
  315. _replace_button->set_disabled(true);
  316. Button *cancel_button = get_ok();
  317. cancel_button->set_text(TTR("Cancel"));
  318. _mode = SEARCH_MODE;
  319. }
  320. void FindInFilesDialog::set_search_text(String text) {
  321. _search_text_line_edit->set_text(text);
  322. _on_search_text_modified(text);
  323. }
  324. void FindInFilesDialog::set_replace_text(String text) {
  325. _replace_text_line_edit->set_text(text);
  326. }
  327. void FindInFilesDialog::set_find_in_files_mode(FindInFilesMode p_mode) {
  328. if (_mode == p_mode) {
  329. return;
  330. }
  331. _mode = p_mode;
  332. if (p_mode == SEARCH_MODE) {
  333. set_title(TTR("Find in Files"));
  334. _replace_label->hide();
  335. _replace_text_line_edit->hide();
  336. } else if (p_mode == REPLACE_MODE) {
  337. set_title(TTR("Replace in Files"));
  338. _replace_label->show();
  339. _replace_text_line_edit->show();
  340. }
  341. // After hiding some child controls, recalculate proper dialog size.
  342. set_size(Size2(get_size().x, 0));
  343. }
  344. String FindInFilesDialog::get_search_text() const {
  345. return _search_text_line_edit->get_text();
  346. }
  347. String FindInFilesDialog::get_replace_text() const {
  348. return _replace_text_line_edit->get_text();
  349. }
  350. bool FindInFilesDialog::is_match_case() const {
  351. return _match_case_checkbox->is_pressed();
  352. }
  353. bool FindInFilesDialog::is_whole_words() const {
  354. return _whole_words_checkbox->is_pressed();
  355. }
  356. String FindInFilesDialog::get_folder() const {
  357. String text = _folder_line_edit->get_text();
  358. return text.strip_edges();
  359. }
  360. Set<String> FindInFilesDialog::get_filter() const {
  361. // could check the _filters_preferences but it might not have been generated yet.
  362. Set<String> filters;
  363. for (int i = 0; i < _filters_container->get_child_count(); ++i) {
  364. CheckBox *cb = (CheckBox *)_filters_container->get_child(i);
  365. if (cb->is_pressed()) {
  366. filters.insert(cb->get_text());
  367. }
  368. }
  369. return filters;
  370. }
  371. void FindInFilesDialog::_notification(int p_what) {
  372. if (p_what == NOTIFICATION_VISIBILITY_CHANGED) {
  373. if (is_visible()) {
  374. // Doesn't work more than once if not deferred...
  375. _search_text_line_edit->call_deferred("grab_focus");
  376. _search_text_line_edit->select_all();
  377. // Extensions might have changed in the meantime, we clean them and instance them again.
  378. for (int i = 0; i < _filters_container->get_child_count(); i++) {
  379. _filters_container->get_child(i)->queue_delete();
  380. }
  381. Array exts = ProjectSettings::get_singleton()->get("editor/search_in_file_extensions");
  382. for (int i = 0; i < exts.size(); ++i) {
  383. CheckBox *cb = memnew(CheckBox);
  384. cb->set_text(exts[i]);
  385. if (!_filters_preferences.has(exts[i])) {
  386. _filters_preferences[exts[i]] = true;
  387. }
  388. cb->set_pressed(_filters_preferences[exts[i]]);
  389. _filters_container->add_child(cb);
  390. }
  391. }
  392. }
  393. }
  394. void FindInFilesDialog::_on_folder_button_pressed() {
  395. _folder_dialog->popup_centered_ratio();
  396. }
  397. void FindInFilesDialog::custom_action(const String &p_action) {
  398. for (int i = 0; i < _filters_container->get_child_count(); ++i) {
  399. CheckBox *cb = (CheckBox *)_filters_container->get_child(i);
  400. _filters_preferences[cb->get_text()] = cb->is_pressed();
  401. }
  402. if (p_action == "find") {
  403. emit_signal(SIGNAL_FIND_REQUESTED);
  404. hide();
  405. } else if (p_action == "replace") {
  406. emit_signal(SIGNAL_REPLACE_REQUESTED);
  407. hide();
  408. }
  409. }
  410. void FindInFilesDialog::_on_search_text_modified(String text) {
  411. ERR_FAIL_COND(!_find_button);
  412. ERR_FAIL_COND(!_replace_button);
  413. _find_button->set_disabled(get_search_text().empty());
  414. _replace_button->set_disabled(get_search_text().empty());
  415. }
  416. void FindInFilesDialog::_on_search_text_entered(String text) {
  417. // This allows to trigger a global search without leaving the keyboard.
  418. if (!_find_button->is_disabled()) {
  419. if (_mode == SEARCH_MODE) {
  420. custom_action("find");
  421. }
  422. }
  423. if (!_replace_button->is_disabled()) {
  424. if (_mode == REPLACE_MODE) {
  425. custom_action("replace");
  426. }
  427. }
  428. }
  429. void FindInFilesDialog::_on_replace_text_entered(String text) {
  430. // This allows to trigger a global search without leaving the keyboard.
  431. if (!_replace_button->is_disabled()) {
  432. if (_mode == REPLACE_MODE) {
  433. custom_action("replace");
  434. }
  435. }
  436. }
  437. void FindInFilesDialog::_on_folder_selected(String path) {
  438. int i = path.find("://");
  439. if (i != -1) {
  440. path = path.right(i + 3);
  441. }
  442. _folder_line_edit->set_text(path);
  443. }
  444. void FindInFilesDialog::_bind_methods() {
  445. ClassDB::bind_method("_on_folder_button_pressed", &FindInFilesDialog::_on_folder_button_pressed);
  446. ClassDB::bind_method("_on_folder_selected", &FindInFilesDialog::_on_folder_selected);
  447. ClassDB::bind_method("_on_search_text_modified", &FindInFilesDialog::_on_search_text_modified);
  448. ClassDB::bind_method("_on_search_text_entered", &FindInFilesDialog::_on_search_text_entered);
  449. ClassDB::bind_method("_on_replace_text_entered", &FindInFilesDialog::_on_replace_text_entered);
  450. ADD_SIGNAL(MethodInfo(SIGNAL_FIND_REQUESTED));
  451. ADD_SIGNAL(MethodInfo(SIGNAL_REPLACE_REQUESTED));
  452. }
  453. //-----------------------------------------------------------------------------
  454. const char *FindInFilesPanel::SIGNAL_RESULT_SELECTED = "result_selected";
  455. const char *FindInFilesPanel::SIGNAL_FILES_MODIFIED = "files_modified";
  456. FindInFilesPanel::FindInFilesPanel() {
  457. _finder = memnew(FindInFiles);
  458. _finder->connect(FindInFiles::SIGNAL_RESULT_FOUND, this, "_on_result_found");
  459. _finder->connect(FindInFiles::SIGNAL_FINISHED, this, "_on_finished");
  460. add_child(_finder);
  461. VBoxContainer *vbc = memnew(VBoxContainer);
  462. vbc->set_anchor_and_margin(MARGIN_LEFT, ANCHOR_BEGIN, 0);
  463. vbc->set_anchor_and_margin(MARGIN_TOP, ANCHOR_BEGIN, 0);
  464. vbc->set_anchor_and_margin(MARGIN_RIGHT, ANCHOR_END, 0);
  465. vbc->set_anchor_and_margin(MARGIN_BOTTOM, ANCHOR_END, 0);
  466. add_child(vbc);
  467. {
  468. HBoxContainer *hbc = memnew(HBoxContainer);
  469. Label *find_label = memnew(Label);
  470. find_label->set_text(TTR("Find:"));
  471. hbc->add_child(find_label);
  472. _search_text_label = memnew(Label);
  473. _search_text_label->add_font_override("font", EditorNode::get_singleton()->get_gui_base()->get_font("source", "EditorFonts"));
  474. hbc->add_child(_search_text_label);
  475. _progress_bar = memnew(ProgressBar);
  476. _progress_bar->set_h_size_flags(SIZE_EXPAND_FILL);
  477. _progress_bar->set_v_size_flags(SIZE_SHRINK_CENTER);
  478. hbc->add_child(_progress_bar);
  479. set_progress_visible(false);
  480. _status_label = memnew(Label);
  481. hbc->add_child(_status_label);
  482. _refresh_button = memnew(Button);
  483. _refresh_button->set_text(TTR("Refresh"));
  484. _refresh_button->connect("pressed", this, "_on_refresh_button_clicked");
  485. _refresh_button->hide();
  486. hbc->add_child(_refresh_button);
  487. _cancel_button = memnew(Button);
  488. _cancel_button->set_text(TTR("Cancel"));
  489. _cancel_button->connect("pressed", this, "_on_cancel_button_clicked");
  490. _cancel_button->hide();
  491. hbc->add_child(_cancel_button);
  492. vbc->add_child(hbc);
  493. }
  494. _results_display = memnew(Tree);
  495. _results_display->add_font_override("font", EditorNode::get_singleton()->get_gui_base()->get_font("source", "EditorFonts"));
  496. _results_display->set_v_size_flags(SIZE_EXPAND_FILL);
  497. _results_display->connect("item_selected", this, "_on_result_selected");
  498. _results_display->connect("item_edited", this, "_on_item_edited");
  499. _results_display->set_hide_root(true);
  500. _results_display->set_select_mode(Tree::SELECT_ROW);
  501. _results_display->set_allow_rmb_select(true);
  502. _results_display->create_item(); // Root
  503. vbc->add_child(_results_display);
  504. _with_replace = false;
  505. {
  506. _replace_container = memnew(HBoxContainer);
  507. Label *replace_label = memnew(Label);
  508. replace_label->set_text(TTR("Replace:"));
  509. _replace_container->add_child(replace_label);
  510. _replace_line_edit = memnew(LineEdit);
  511. _replace_line_edit->set_h_size_flags(SIZE_EXPAND_FILL);
  512. _replace_line_edit->connect("text_changed", this, "_on_replace_text_changed");
  513. _replace_container->add_child(_replace_line_edit);
  514. _replace_all_button = memnew(Button);
  515. _replace_all_button->set_text(TTR("Replace All (NO UNDO)"));
  516. _replace_all_button->connect("pressed", this, "_on_replace_all_clicked");
  517. _replace_container->add_child(_replace_all_button);
  518. _replace_container->hide();
  519. vbc->add_child(_replace_container);
  520. }
  521. }
  522. void FindInFilesPanel::set_with_replace(bool with_replace) {
  523. _with_replace = with_replace;
  524. _replace_container->set_visible(with_replace);
  525. if (with_replace) {
  526. // Results show checkboxes on their left so they can be opted out
  527. _results_display->set_columns(2);
  528. _results_display->set_column_expand(0, false);
  529. _results_display->set_column_min_width(0, 48 * EDSCALE);
  530. } else {
  531. // Results are single-cell items
  532. _results_display->set_column_expand(0, true);
  533. _results_display->set_columns(1);
  534. }
  535. }
  536. void FindInFilesPanel::set_replace_text(String text) {
  537. _replace_line_edit->set_text(text);
  538. }
  539. void FindInFilesPanel::clear() {
  540. _file_items.clear();
  541. _result_items.clear();
  542. _results_display->clear();
  543. _results_display->create_item(); // Root
  544. }
  545. void FindInFilesPanel::start_search() {
  546. clear();
  547. _status_label->set_text(TTR("Searching..."));
  548. _search_text_label->set_text(_finder->get_search_text());
  549. set_process(true);
  550. set_progress_visible(true);
  551. _finder->start();
  552. update_replace_buttons();
  553. _refresh_button->hide();
  554. _cancel_button->show();
  555. }
  556. void FindInFilesPanel::stop_search() {
  557. _finder->stop();
  558. _status_label->set_text("");
  559. update_replace_buttons();
  560. set_progress_visible(false);
  561. _refresh_button->show();
  562. _cancel_button->hide();
  563. }
  564. void FindInFilesPanel::_notification(int p_what) {
  565. if (p_what == NOTIFICATION_PROCESS) {
  566. _progress_bar->set_as_ratio(_finder->get_progress());
  567. } else if (p_what == NOTIFICATION_THEME_CHANGED) {
  568. _search_text_label->add_font_override("font", get_font("source", "EditorFonts"));
  569. _results_display->add_font_override("font", get_font("source", "EditorFonts"));
  570. }
  571. }
  572. void FindInFilesPanel::_on_result_found(String fpath, int line_number, int begin, int end, String text) {
  573. TreeItem *file_item;
  574. Map<String, TreeItem *>::Element *E = _file_items.find(fpath);
  575. if (E == nullptr) {
  576. file_item = _results_display->create_item();
  577. file_item->set_text(0, fpath);
  578. file_item->set_metadata(0, fpath);
  579. // The width of this column is restrained to checkboxes, but that doesn't make sense for the parent items,
  580. // so we override their width so they can expand to full width
  581. file_item->set_expand_right(0, true);
  582. _file_items[fpath] = file_item;
  583. } else {
  584. file_item = E->value();
  585. }
  586. int text_index = _with_replace ? 1 : 0;
  587. TreeItem *item = _results_display->create_item(file_item);
  588. // Do this first because it resets properties of the cell...
  589. item->set_cell_mode(text_index, TreeItem::CELL_MODE_CUSTOM);
  590. // Trim result item line
  591. int old_text_size = text.size();
  592. text = text.strip_edges(true, false);
  593. int chars_removed = old_text_size - text.size();
  594. String start = vformat("%3s: ", line_number);
  595. item->set_text(text_index, start + text);
  596. item->set_custom_draw(text_index, this, "_draw_result_text");
  597. Result r;
  598. r.line_number = line_number;
  599. r.begin = begin;
  600. r.end = end;
  601. r.begin_trimmed = begin - chars_removed + start.size() - 1;
  602. _result_items[item] = r;
  603. if (_with_replace) {
  604. item->set_cell_mode(0, TreeItem::CELL_MODE_CHECK);
  605. item->set_checked(0, true);
  606. item->set_editable(0, true);
  607. }
  608. }
  609. void FindInFilesPanel::draw_result_text(Object *item_obj, Rect2 rect) {
  610. TreeItem *item = Object::cast_to<TreeItem>(item_obj);
  611. if (!item) {
  612. return;
  613. }
  614. Map<TreeItem *, Result>::Element *E = _result_items.find(item);
  615. if (!E) {
  616. return;
  617. }
  618. Result r = E->value();
  619. String item_text = item->get_text(_with_replace ? 1 : 0);
  620. Ref<Font> font = _results_display->get_font("font");
  621. Rect2 match_rect = rect;
  622. match_rect.position.x += font->get_string_size(item_text.left(r.begin_trimmed)).x;
  623. match_rect.size.x = font->get_string_size(_search_text_label->get_text()).x;
  624. match_rect.position.y += 1 * EDSCALE;
  625. match_rect.size.y -= 2 * EDSCALE;
  626. // Use the inverted accent color to help match rectangles stand out even on the currently selected line.
  627. _results_display->draw_rect(match_rect, get_color("accent_color", "Editor").inverted() * Color(1, 1, 1, 0.5));
  628. // Text is drawn by Tree already.
  629. }
  630. void FindInFilesPanel::_on_item_edited() {
  631. TreeItem *item = _results_display->get_selected();
  632. if (item->is_checked(0)) {
  633. item->set_custom_color(1, _results_display->get_color("font_color"));
  634. } else {
  635. // Grey out
  636. Color color = _results_display->get_color("font_color");
  637. color.a /= 2.0;
  638. item->set_custom_color(1, color);
  639. }
  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. Map<TreeItem *, Result>::Element *E = _result_items.find(item);
  667. if (E == nullptr) {
  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(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. PoolStringArray modified_files;
  681. for (Map<String, TreeItem *>::Element *E = _file_items.front(); E; E = E->next()) {
  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_children(); item; item = item->get_next()) {
  686. if (!item->is_checked(0)) {
  687. continue;
  688. }
  689. Map<TreeItem *, Result>::Element *F = _result_items.find(item);
  690. ERR_FAIL_COND(F == nullptr);
  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.append(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(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(FileAccess *f) {
  707. _line_buffer.clear();
  708. CharType 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. FileAccessRef f = FileAccess::open(fpath, FileAccess::READ);
  733. ERR_FAIL_COND_MSG(!f, "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.right(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. f->close();
  769. }
  770. String FindInFilesPanel::get_replace_text() {
  771. return _replace_line_edit->get_text();
  772. }
  773. void FindInFilesPanel::update_replace_buttons() {
  774. bool disabled = _finder->is_searching();
  775. _replace_all_button->set_disabled(disabled);
  776. }
  777. void FindInFilesPanel::set_progress_visible(bool visible) {
  778. _progress_bar->set_self_modulate(Color(1, 1, 1, visible ? 1 : 0));
  779. }
  780. void FindInFilesPanel::_bind_methods() {
  781. ClassDB::bind_method("_on_result_found", &FindInFilesPanel::_on_result_found);
  782. ClassDB::bind_method("_on_item_edited", &FindInFilesPanel::_on_item_edited);
  783. ClassDB::bind_method("_on_finished", &FindInFilesPanel::_on_finished);
  784. ClassDB::bind_method("_on_refresh_button_clicked", &FindInFilesPanel::_on_refresh_button_clicked);
  785. ClassDB::bind_method("_on_cancel_button_clicked", &FindInFilesPanel::_on_cancel_button_clicked);
  786. ClassDB::bind_method("_on_result_selected", &FindInFilesPanel::_on_result_selected);
  787. ClassDB::bind_method("_on_replace_text_changed", &FindInFilesPanel::_on_replace_text_changed);
  788. ClassDB::bind_method("_on_replace_all_clicked", &FindInFilesPanel::_on_replace_all_clicked);
  789. ClassDB::bind_method("_draw_result_text", &FindInFilesPanel::draw_result_text);
  790. ADD_SIGNAL(MethodInfo(SIGNAL_RESULT_SELECTED,
  791. PropertyInfo(Variant::STRING, "path"),
  792. PropertyInfo(Variant::INT, "line_number"),
  793. PropertyInfo(Variant::INT, "begin"),
  794. PropertyInfo(Variant::INT, "end")));
  795. ADD_SIGNAL(MethodInfo(SIGNAL_FILES_MODIFIED, PropertyInfo(Variant::STRING, "paths")));
  796. }