find_in_files.cpp 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181
  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_string_names.h"
  36. #include "editor/themes/editor_scale.h"
  37. #include "scene/gui/box_container.h"
  38. #include "scene/gui/button.h"
  39. #include "scene/gui/check_box.h"
  40. #include "scene/gui/file_dialog.h"
  41. #include "scene/gui/grid_container.h"
  42. #include "scene/gui/label.h"
  43. #include "scene/gui/line_edit.h"
  44. #include "scene/gui/progress_bar.h"
  45. #include "scene/gui/tree.h"
  46. const char *FindInFiles::SIGNAL_RESULT_FOUND = "result_found";
  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, const 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(const 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(const String &folder) {
  84. _root_dir = folder;
  85. }
  86. void FindInFiles::set_filter(const HashSet<String> &exts) {
  87. _extension_filter = exts;
  88. }
  89. void FindInFiles::set_includes(const HashSet<String> &p_include_wildcards) {
  90. _include_wildcards = p_include_wildcards;
  91. }
  92. void FindInFiles::set_excludes(const HashSet<String> &p_exclude_wildcards) {
  93. _exclude_wildcards = p_exclude_wildcards;
  94. }
  95. void FindInFiles::_notification(int p_what) {
  96. switch (p_what) {
  97. case NOTIFICATION_PROCESS: {
  98. _process();
  99. } break;
  100. }
  101. }
  102. void FindInFiles::start() {
  103. if (_pattern.is_empty()) {
  104. print_verbose("Nothing to search, pattern is empty");
  105. emit_signal(SceneStringName(finished));
  106. return;
  107. }
  108. if (_extension_filter.is_empty()) {
  109. print_verbose("Nothing to search, filter matches no files");
  110. emit_signal(SceneStringName(finished));
  111. return;
  112. }
  113. // Init search.
  114. _current_dir = "";
  115. PackedStringArray init_folder;
  116. init_folder.push_back(_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. PackedStringArray &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.path_join(folder_name);
  149. PackedStringArray sub_dirs;
  150. PackedStringArray files_to_scan;
  151. _scan_dir("res://" + _current_dir, sub_dirs, files_to_scan);
  152. _folders_stack.push_back(sub_dirs);
  153. _files_to_scan.append_array(files_to_scan);
  154. } else {
  155. // Go back one level.
  156. pop_back(_folders_stack);
  157. _current_dir = _current_dir.get_base_dir();
  158. if (_folders_stack.is_empty()) {
  159. // All folders scanned.
  160. _initial_files_count = _files_to_scan.size();
  161. }
  162. }
  163. } else if (_files_to_scan.size() != 0) {
  164. // Then scan files.
  165. String fpath = _files_to_scan[_files_to_scan.size() - 1];
  166. pop_back(_files_to_scan);
  167. _scan_file(fpath);
  168. } else {
  169. print_verbose("Search complete");
  170. set_process(false);
  171. _current_dir = "";
  172. _searching = false;
  173. emit_signal(SceneStringName(finished));
  174. }
  175. }
  176. float FindInFiles::get_progress() const {
  177. if (_initial_files_count != 0) {
  178. return static_cast<float>(_initial_files_count - _files_to_scan.size()) / static_cast<float>(_initial_files_count);
  179. }
  180. return 0;
  181. }
  182. void FindInFiles::_scan_dir(const String &path, PackedStringArray &out_folders, PackedStringArray &out_files_to_scan) {
  183. Ref<DirAccess> dir = DirAccess::open(path);
  184. if (dir.is_null()) {
  185. print_verbose("Cannot open directory! " + path);
  186. return;
  187. }
  188. dir->list_dir_begin();
  189. // Limit to 100,000 iterations to avoid an infinite loop just in case
  190. // (this technically limits results to 100,000 files per folder).
  191. for (int i = 0; i < 100'000; ++i) {
  192. String file = dir->get_next();
  193. if (file.is_empty()) {
  194. break;
  195. }
  196. // If there is a .gdignore file in the directory, clear all the files/folders
  197. // to be searched on this path and skip searching the directory.
  198. if (file == ".gdignore") {
  199. out_folders.clear();
  200. out_files_to_scan.clear();
  201. break;
  202. }
  203. // Ignore special directories (such as those beginning with . and the project data directory).
  204. String project_data_dir_name = ProjectSettings::get_singleton()->get_project_data_dir_name();
  205. if (file.begins_with(".") || file == project_data_dir_name) {
  206. continue;
  207. }
  208. if (dir->current_is_hidden()) {
  209. continue;
  210. }
  211. if (dir->current_is_dir()) {
  212. out_folders.push_back(file);
  213. } else {
  214. String file_ext = file.get_extension();
  215. if (_extension_filter.has(file_ext)) {
  216. String file_path = path.path_join(file);
  217. bool case_sensitive = dir->is_case_sensitive(path);
  218. if (!_exclude_wildcards.is_empty() && _is_file_matched(_exclude_wildcards, file_path, case_sensitive)) {
  219. continue;
  220. }
  221. if (_include_wildcards.is_empty() || _is_file_matched(_include_wildcards, file_path, case_sensitive)) {
  222. out_files_to_scan.push_back(file_path);
  223. }
  224. }
  225. }
  226. }
  227. }
  228. void FindInFiles::_scan_file(const String &fpath) {
  229. Ref<FileAccess> f = FileAccess::open(fpath, FileAccess::READ);
  230. if (f.is_null()) {
  231. print_verbose(String("Cannot open file ") + fpath);
  232. return;
  233. }
  234. int line_number = 0;
  235. while (!f->eof_reached()) {
  236. // Line number starts at 1.
  237. ++line_number;
  238. int begin = 0;
  239. int end = 0;
  240. String line = f->get_line();
  241. while (find_next(line, _pattern, end, _match_case, _whole_words, begin, end)) {
  242. emit_signal(SNAME(SIGNAL_RESULT_FOUND), fpath, line_number, begin, end, line);
  243. }
  244. }
  245. }
  246. bool FindInFiles::_is_file_matched(const HashSet<String> &p_wildcards, const String &p_file_path, bool p_case_sensitive) const {
  247. const String file_path = "/" + p_file_path.replace_char('\\', '/') + "/";
  248. for (const String &wildcard : p_wildcards) {
  249. if (p_case_sensitive && file_path.match(wildcard)) {
  250. return true;
  251. } else if (!p_case_sensitive && file_path.matchn(wildcard)) {
  252. return true;
  253. }
  254. }
  255. return false;
  256. }
  257. void FindInFiles::_bind_methods() {
  258. ADD_SIGNAL(MethodInfo(SIGNAL_RESULT_FOUND,
  259. PropertyInfo(Variant::STRING, "path"),
  260. PropertyInfo(Variant::INT, "line_number"),
  261. PropertyInfo(Variant::INT, "begin"),
  262. PropertyInfo(Variant::INT, "end"),
  263. PropertyInfo(Variant::STRING, "text")));
  264. ADD_SIGNAL(MethodInfo("finished"));
  265. }
  266. //-----------------------------------------------------------------------------
  267. const char *FindInFilesDialog::SIGNAL_FIND_REQUESTED = "find_requested";
  268. const char *FindInFilesDialog::SIGNAL_REPLACE_REQUESTED = "replace_requested";
  269. FindInFilesDialog::FindInFilesDialog() {
  270. set_min_size(Size2(500 * EDSCALE, 0));
  271. set_title(TTR("Find in Files"));
  272. VBoxContainer *vbc = memnew(VBoxContainer);
  273. vbc->set_anchor_and_offset(SIDE_LEFT, Control::ANCHOR_BEGIN, 8 * EDSCALE);
  274. vbc->set_anchor_and_offset(SIDE_TOP, Control::ANCHOR_BEGIN, 8 * EDSCALE);
  275. vbc->set_anchor_and_offset(SIDE_RIGHT, Control::ANCHOR_END, -8 * EDSCALE);
  276. vbc->set_anchor_and_offset(SIDE_BOTTOM, Control::ANCHOR_END, -8 * EDSCALE);
  277. add_child(vbc);
  278. GridContainer *gc = memnew(GridContainer);
  279. gc->set_columns(2);
  280. vbc->add_child(gc);
  281. Label *find_label = memnew(Label);
  282. find_label->set_text(TTR("Find:"));
  283. gc->add_child(find_label);
  284. _search_text_line_edit = memnew(LineEdit);
  285. _search_text_line_edit->set_h_size_flags(Control::SIZE_EXPAND_FILL);
  286. _search_text_line_edit->set_accessibility_name(TTRC("Find:"));
  287. _search_text_line_edit->connect(SceneStringName(text_changed), callable_mp(this, &FindInFilesDialog::_on_search_text_modified));
  288. _search_text_line_edit->connect(SceneStringName(text_submitted), callable_mp(this, &FindInFilesDialog::_on_search_text_submitted));
  289. gc->add_child(_search_text_line_edit);
  290. _replace_label = memnew(Label);
  291. _replace_label->set_text(TTR("Replace:"));
  292. _replace_label->hide();
  293. gc->add_child(_replace_label);
  294. _replace_text_line_edit = memnew(LineEdit);
  295. _replace_text_line_edit->set_h_size_flags(Control::SIZE_EXPAND_FILL);
  296. _replace_text_line_edit->set_accessibility_name(TTRC("Replace:"));
  297. _replace_text_line_edit->connect(SceneStringName(text_submitted), callable_mp(this, &FindInFilesDialog::_on_replace_text_submitted));
  298. _replace_text_line_edit->hide();
  299. gc->add_child(_replace_text_line_edit);
  300. gc->add_child(memnew(Control)); // Space to maintain the grid alignment.
  301. {
  302. HBoxContainer *hbc = memnew(HBoxContainer);
  303. _whole_words_checkbox = memnew(CheckBox);
  304. _whole_words_checkbox->set_text(TTR("Whole Words"));
  305. hbc->add_child(_whole_words_checkbox);
  306. _match_case_checkbox = memnew(CheckBox);
  307. _match_case_checkbox->set_text(TTR("Match Case"));
  308. hbc->add_child(_match_case_checkbox);
  309. gc->add_child(hbc);
  310. }
  311. Label *folder_label = memnew(Label);
  312. folder_label->set_text(TTR("Folder:"));
  313. gc->add_child(folder_label);
  314. {
  315. HBoxContainer *hbc = memnew(HBoxContainer);
  316. Label *prefix_label = memnew(Label);
  317. prefix_label->set_text("res://");
  318. hbc->add_child(prefix_label);
  319. _folder_line_edit = memnew(LineEdit);
  320. _folder_line_edit->set_h_size_flags(Control::SIZE_EXPAND_FILL);
  321. _folder_line_edit->connect(SceneStringName(text_submitted), callable_mp(this, &FindInFilesDialog::_on_search_text_submitted));
  322. _folder_line_edit->set_accessibility_name(TTRC("Folder:"));
  323. hbc->add_child(_folder_line_edit);
  324. Button *folder_button = memnew(Button);
  325. folder_button->set_accessibility_name(TTRC("Select Folder"));
  326. folder_button->set_text("...");
  327. folder_button->connect(SceneStringName(pressed), callable_mp(this, &FindInFilesDialog::_on_folder_button_pressed));
  328. hbc->add_child(folder_button);
  329. _folder_dialog = memnew(FileDialog);
  330. _folder_dialog->set_file_mode(FileDialog::FILE_MODE_OPEN_DIR);
  331. _folder_dialog->connect("dir_selected", callable_mp(this, &FindInFilesDialog::_on_folder_selected));
  332. add_child(_folder_dialog);
  333. gc->add_child(hbc);
  334. }
  335. Label *includes_label = memnew(Label);
  336. includes_label->set_text(TTR("Includes:"));
  337. includes_label->set_tooltip_text(TTR("Include the files with the following expressions. Use \",\" to separate."));
  338. includes_label->set_mouse_filter(Control::MOUSE_FILTER_PASS);
  339. gc->add_child(includes_label);
  340. _includes_line_edit = memnew(LineEdit);
  341. _includes_line_edit->set_h_size_flags(Control::SIZE_EXPAND_FILL);
  342. _includes_line_edit->set_placeholder(TTR("example: scripts,scenes/*/test.gd"));
  343. _includes_line_edit->set_accessibility_name(TTRC("Includes:"));
  344. _includes_line_edit->connect(SceneStringName(text_submitted), callable_mp(this, &FindInFilesDialog::_on_search_text_submitted));
  345. gc->add_child(_includes_line_edit);
  346. Label *excludes_label = memnew(Label);
  347. excludes_label->set_text(TTR("Excludes:"));
  348. excludes_label->set_tooltip_text(TTR("Exclude the files with the following expressions. Use \",\" to separate."));
  349. excludes_label->set_mouse_filter(Control::MOUSE_FILTER_PASS);
  350. gc->add_child(excludes_label);
  351. _excludes_line_edit = memnew(LineEdit);
  352. _excludes_line_edit->set_h_size_flags(Control::SIZE_EXPAND_FILL);
  353. _excludes_line_edit->set_placeholder(TTR("example: res://addons,scenes/test/*.gd"));
  354. _excludes_line_edit->set_accessibility_name(TTRC("Excludes:"));
  355. _excludes_line_edit->connect(SceneStringName(text_submitted), callable_mp(this, &FindInFilesDialog::_on_search_text_submitted));
  356. gc->add_child(_excludes_line_edit);
  357. Label *filter_label = memnew(Label);
  358. filter_label->set_text(TTR("Filters:"));
  359. filter_label->set_tooltip_text(TTR("Include the files with the following extensions. Add or remove them in ProjectSettings."));
  360. filter_label->set_mouse_filter(Control::MOUSE_FILTER_PASS);
  361. gc->add_child(filter_label);
  362. _filters_container = memnew(HBoxContainer);
  363. gc->add_child(_filters_container);
  364. _find_button = add_button(TTR("Find..."), false, "find");
  365. _find_button->set_disabled(true);
  366. _replace_button = add_button(TTR("Replace..."), false, "replace");
  367. _replace_button->set_disabled(true);
  368. Button *cancel_button = get_ok_button();
  369. cancel_button->set_text(TTR("Cancel"));
  370. _mode = SEARCH_MODE;
  371. }
  372. void FindInFilesDialog::set_search_text(const String &text) {
  373. if (_mode == SEARCH_MODE) {
  374. if (!text.is_empty()) {
  375. _search_text_line_edit->set_text(text);
  376. _on_search_text_modified(text);
  377. }
  378. callable_mp((Control *)_search_text_line_edit, &Control::grab_focus).call_deferred();
  379. _search_text_line_edit->select_all();
  380. } else if (_mode == REPLACE_MODE) {
  381. if (!text.is_empty()) {
  382. _search_text_line_edit->set_text(text);
  383. callable_mp((Control *)_replace_text_line_edit, &Control::grab_focus).call_deferred();
  384. _replace_text_line_edit->select_all();
  385. _on_search_text_modified(text);
  386. } else {
  387. callable_mp((Control *)_search_text_line_edit, &Control::grab_focus).call_deferred();
  388. _search_text_line_edit->select_all();
  389. }
  390. }
  391. }
  392. void FindInFilesDialog::set_replace_text(const String &text) {
  393. _replace_text_line_edit->set_text(text);
  394. }
  395. void FindInFilesDialog::set_find_in_files_mode(FindInFilesMode p_mode) {
  396. if (_mode == p_mode) {
  397. return;
  398. }
  399. _mode = p_mode;
  400. if (p_mode == SEARCH_MODE) {
  401. set_title(TTR("Find in Files"));
  402. _replace_label->hide();
  403. _replace_text_line_edit->hide();
  404. } else if (p_mode == REPLACE_MODE) {
  405. set_title(TTR("Replace in Files"));
  406. _replace_label->show();
  407. _replace_text_line_edit->show();
  408. }
  409. // Recalculate the dialog size after hiding child controls.
  410. set_size(Size2(get_size().x, 0));
  411. }
  412. String FindInFilesDialog::get_search_text() const {
  413. return _search_text_line_edit->get_text();
  414. }
  415. String FindInFilesDialog::get_replace_text() const {
  416. return _replace_text_line_edit->get_text();
  417. }
  418. bool FindInFilesDialog::is_match_case() const {
  419. return _match_case_checkbox->is_pressed();
  420. }
  421. bool FindInFilesDialog::is_whole_words() const {
  422. return _whole_words_checkbox->is_pressed();
  423. }
  424. String FindInFilesDialog::get_folder() const {
  425. String text = _folder_line_edit->get_text();
  426. return text.strip_edges();
  427. }
  428. HashSet<String> FindInFilesDialog::get_filter() const {
  429. // Could check the _filters_preferences but it might not have been generated yet.
  430. HashSet<String> filters;
  431. for (int i = 0; i < _filters_container->get_child_count(); ++i) {
  432. CheckBox *cb = static_cast<CheckBox *>(_filters_container->get_child(i));
  433. if (cb->is_pressed()) {
  434. filters.insert(cb->get_text());
  435. }
  436. }
  437. return filters;
  438. }
  439. HashSet<String> FindInFilesDialog::get_includes() const {
  440. HashSet<String> includes;
  441. String text = _includes_line_edit->get_text();
  442. if (text.is_empty()) {
  443. return includes;
  444. }
  445. PackedStringArray wildcards = text.split(",", false);
  446. for (const String &wildcard : wildcards) {
  447. includes.insert(validate_filter_wildcard(wildcard));
  448. }
  449. return includes;
  450. }
  451. HashSet<String> FindInFilesDialog::get_excludes() const {
  452. HashSet<String> excludes;
  453. String text = _excludes_line_edit->get_text();
  454. if (text.is_empty()) {
  455. return excludes;
  456. }
  457. PackedStringArray wildcards = text.split(",", false);
  458. for (const String &wildcard : wildcards) {
  459. excludes.insert(validate_filter_wildcard(wildcard));
  460. }
  461. return excludes;
  462. }
  463. void FindInFilesDialog::_notification(int p_what) {
  464. switch (p_what) {
  465. case NOTIFICATION_VISIBILITY_CHANGED: {
  466. if (is_visible()) {
  467. // Extensions might have changed in the meantime, we clean them and instance them again.
  468. for (int i = 0; i < _filters_container->get_child_count(); i++) {
  469. _filters_container->get_child(i)->queue_free();
  470. }
  471. Array exts = GLOBAL_GET("editor/script/search_in_file_extensions");
  472. for (int i = 0; i < exts.size(); ++i) {
  473. CheckBox *cb = memnew(CheckBox);
  474. cb->set_text(exts[i]);
  475. if (!_filters_preferences.has(exts[i])) {
  476. _filters_preferences[exts[i]] = true;
  477. }
  478. cb->set_pressed(_filters_preferences[exts[i]]);
  479. _filters_container->add_child(cb);
  480. }
  481. }
  482. } break;
  483. }
  484. }
  485. void FindInFilesDialog::_on_folder_button_pressed() {
  486. _folder_dialog->popup_file_dialog();
  487. }
  488. void FindInFilesDialog::custom_action(const String &p_action) {
  489. for (int i = 0; i < _filters_container->get_child_count(); ++i) {
  490. CheckBox *cb = static_cast<CheckBox *>(_filters_container->get_child(i));
  491. _filters_preferences[cb->get_text()] = cb->is_pressed();
  492. }
  493. if (p_action == "find") {
  494. emit_signal(SNAME(SIGNAL_FIND_REQUESTED));
  495. hide();
  496. } else if (p_action == "replace") {
  497. emit_signal(SNAME(SIGNAL_REPLACE_REQUESTED));
  498. hide();
  499. }
  500. }
  501. void FindInFilesDialog::_on_search_text_modified(const String &text) {
  502. ERR_FAIL_NULL(_find_button);
  503. ERR_FAIL_NULL(_replace_button);
  504. _find_button->set_disabled(get_search_text().is_empty());
  505. _replace_button->set_disabled(get_search_text().is_empty());
  506. }
  507. void FindInFilesDialog::_on_search_text_submitted(const String &text) {
  508. // This allows to trigger a global search without leaving the keyboard.
  509. if (!_find_button->is_disabled()) {
  510. if (_mode == SEARCH_MODE) {
  511. custom_action("find");
  512. }
  513. }
  514. if (!_replace_button->is_disabled()) {
  515. if (_mode == REPLACE_MODE) {
  516. custom_action("replace");
  517. }
  518. }
  519. }
  520. void FindInFilesDialog::_on_replace_text_submitted(const String &text) {
  521. // This allows to trigger a global search without leaving the keyboard.
  522. if (!_replace_button->is_disabled()) {
  523. if (_mode == REPLACE_MODE) {
  524. custom_action("replace");
  525. }
  526. }
  527. }
  528. void FindInFilesDialog::_on_folder_selected(String path) {
  529. int i = path.find("://");
  530. if (i != -1) {
  531. path = path.substr(i + 3);
  532. }
  533. _folder_line_edit->set_text(path);
  534. }
  535. String FindInFilesDialog::validate_filter_wildcard(const String &p_expression) const {
  536. String ret = p_expression.replace_char('\\', '/');
  537. if (ret.begins_with("./")) {
  538. // Relative to the project root.
  539. ret = "res://" + ret.trim_prefix("./");
  540. }
  541. if (ret.begins_with(".")) {
  542. // To match extension.
  543. ret = "*" + ret;
  544. }
  545. if (!ret.begins_with("*")) {
  546. ret = "*/" + ret.trim_prefix("/");
  547. }
  548. if (!ret.ends_with("*")) {
  549. ret = ret.trim_suffix("/") + "/*";
  550. }
  551. return ret;
  552. }
  553. void FindInFilesDialog::_bind_methods() {
  554. ADD_SIGNAL(MethodInfo(SIGNAL_FIND_REQUESTED));
  555. ADD_SIGNAL(MethodInfo(SIGNAL_REPLACE_REQUESTED));
  556. }
  557. //-----------------------------------------------------------------------------
  558. const char *FindInFilesPanel::SIGNAL_RESULT_SELECTED = "result_selected";
  559. const char *FindInFilesPanel::SIGNAL_FILES_MODIFIED = "files_modified";
  560. const char *FindInFilesPanel::SIGNAL_CLOSE_BUTTON_CLICKED = "close_button_clicked";
  561. FindInFilesPanel::FindInFilesPanel() {
  562. _finder = memnew(FindInFiles);
  563. _finder->connect(FindInFiles::SIGNAL_RESULT_FOUND, callable_mp(this, &FindInFilesPanel::_on_result_found));
  564. _finder->connect(SceneStringName(finished), callable_mp(this, &FindInFilesPanel::_on_finished));
  565. add_child(_finder);
  566. VBoxContainer *vbc = memnew(VBoxContainer);
  567. vbc->set_anchor_and_offset(SIDE_LEFT, ANCHOR_BEGIN, 0);
  568. vbc->set_anchor_and_offset(SIDE_TOP, ANCHOR_BEGIN, 0);
  569. vbc->set_anchor_and_offset(SIDE_RIGHT, ANCHOR_END, 0);
  570. vbc->set_anchor_and_offset(SIDE_BOTTOM, ANCHOR_END, 0);
  571. add_child(vbc);
  572. {
  573. HBoxContainer *hbc = memnew(HBoxContainer);
  574. Label *find_label = memnew(Label);
  575. find_label->set_text(TTR("Find:"));
  576. hbc->add_child(find_label);
  577. _search_text_label = memnew(Label);
  578. _search_text_label->set_focus_mode(FOCUS_ACCESSIBILITY);
  579. hbc->add_child(_search_text_label);
  580. _progress_bar = memnew(ProgressBar);
  581. _progress_bar->set_h_size_flags(SIZE_EXPAND_FILL);
  582. _progress_bar->set_v_size_flags(SIZE_SHRINK_CENTER);
  583. hbc->add_child(_progress_bar);
  584. set_progress_visible(false);
  585. _status_label = memnew(Label);
  586. _status_label->set_focus_mode(FOCUS_ACCESSIBILITY);
  587. hbc->add_child(_status_label);
  588. _refresh_button = memnew(Button);
  589. _refresh_button->set_text(TTR("Refresh"));
  590. _refresh_button->connect(SceneStringName(pressed), callable_mp(this, &FindInFilesPanel::_on_refresh_button_clicked));
  591. _refresh_button->hide();
  592. hbc->add_child(_refresh_button);
  593. _cancel_button = memnew(Button);
  594. _cancel_button->set_text(TTR("Cancel"));
  595. _cancel_button->connect(SceneStringName(pressed), callable_mp(this, &FindInFilesPanel::_on_cancel_button_clicked));
  596. _cancel_button->hide();
  597. hbc->add_child(_cancel_button);
  598. _close_button = memnew(Button);
  599. _close_button->set_text(TTR("Close"));
  600. _close_button->connect(SceneStringName(pressed), callable_mp(this, &FindInFilesPanel::_on_close_button_clicked));
  601. hbc->add_child(_close_button);
  602. vbc->add_child(hbc);
  603. }
  604. _results_display = memnew(Tree);
  605. _results_display->set_accessibility_name(TTRC("Search Results"));
  606. _results_display->set_auto_translate_mode(AUTO_TRANSLATE_MODE_DISABLED);
  607. _results_display->set_v_size_flags(SIZE_EXPAND_FILL);
  608. _results_display->connect(SceneStringName(item_selected), callable_mp(this, &FindInFilesPanel::_on_result_selected));
  609. _results_display->connect("item_edited", callable_mp(this, &FindInFilesPanel::_on_item_edited));
  610. _results_display->connect("button_clicked", callable_mp(this, &FindInFilesPanel::_on_button_clicked));
  611. _results_display->set_hide_root(true);
  612. _results_display->set_select_mode(Tree::SELECT_ROW);
  613. _results_display->set_allow_rmb_select(true);
  614. _results_display->set_allow_reselect(true);
  615. _results_display->add_theme_constant_override("inner_item_margin_left", 0);
  616. _results_display->add_theme_constant_override("inner_item_margin_right", 0);
  617. _results_display->create_item(); // Root
  618. vbc->add_child(_results_display);
  619. {
  620. _replace_container = memnew(HBoxContainer);
  621. Label *replace_label = memnew(Label);
  622. replace_label->set_text(TTR("Replace:"));
  623. _replace_container->add_child(replace_label);
  624. _replace_line_edit = memnew(LineEdit);
  625. _replace_line_edit->set_accessibility_name(TTRC("Replace:"));
  626. _replace_line_edit->set_h_size_flags(SIZE_EXPAND_FILL);
  627. _replace_line_edit->connect(SceneStringName(text_changed), callable_mp(this, &FindInFilesPanel::_on_replace_text_changed));
  628. _replace_container->add_child(_replace_line_edit);
  629. _replace_all_button = memnew(Button);
  630. _replace_all_button->set_text(TTR("Replace all (no undo)"));
  631. _replace_all_button->connect(SceneStringName(pressed), callable_mp(this, &FindInFilesPanel::_on_replace_all_clicked));
  632. _replace_container->add_child(_replace_all_button);
  633. _replace_container->hide();
  634. vbc->add_child(_replace_container);
  635. }
  636. }
  637. void FindInFilesPanel::set_with_replace(bool with_replace) {
  638. _with_replace = with_replace;
  639. _replace_container->set_visible(with_replace);
  640. if (with_replace) {
  641. // Results show checkboxes on their left so they can be opted out.
  642. _results_display->set_columns(2);
  643. _results_display->set_column_expand(0, false);
  644. _results_display->set_column_custom_minimum_width(0, 48 * EDSCALE);
  645. } else {
  646. // Results are single-cell items.
  647. _results_display->set_column_expand(0, true);
  648. _results_display->set_columns(1);
  649. }
  650. }
  651. void FindInFilesPanel::set_replace_text(const String &text) {
  652. _replace_line_edit->set_text(text);
  653. }
  654. void FindInFilesPanel::clear() {
  655. _file_items.clear();
  656. _result_items.clear();
  657. _results_display->clear();
  658. _results_display->create_item(); // Root
  659. }
  660. void FindInFilesPanel::start_search() {
  661. clear();
  662. _status_label->set_text(TTR("Searching..."));
  663. _search_text_label->set_text(_finder->get_search_text());
  664. set_process(true);
  665. set_progress_visible(true);
  666. _finder->start();
  667. update_replace_buttons();
  668. _refresh_button->hide();
  669. _cancel_button->show();
  670. }
  671. void FindInFilesPanel::stop_search() {
  672. _finder->stop();
  673. _status_label->set_text("");
  674. update_replace_buttons();
  675. set_progress_visible(false);
  676. _refresh_button->show();
  677. _cancel_button->hide();
  678. }
  679. void FindInFilesPanel::_notification(int p_what) {
  680. switch (p_what) {
  681. case NOTIFICATION_THEME_CHANGED: {
  682. _search_text_label->add_theme_font_override(SceneStringName(font), get_theme_font(SNAME("source"), EditorStringName(EditorFonts)));
  683. _search_text_label->add_theme_font_size_override(SceneStringName(font_size), get_theme_font_size(SNAME("source_size"), EditorStringName(EditorFonts)));
  684. _results_display->add_theme_font_override(SceneStringName(font), get_theme_font(SNAME("source"), EditorStringName(EditorFonts)));
  685. _results_display->add_theme_font_size_override(SceneStringName(font_size), get_theme_font_size(SNAME("source_size"), EditorStringName(EditorFonts)));
  686. // Rebuild search tree.
  687. if (!_finder->get_search_text().is_empty()) {
  688. start_search();
  689. }
  690. } break;
  691. case NOTIFICATION_PROCESS: {
  692. _progress_bar->set_as_ratio(_finder->get_progress());
  693. } break;
  694. }
  695. }
  696. void FindInFilesPanel::_on_result_found(const String &fpath, int line_number, int begin, int end, String text) {
  697. TreeItem *file_item;
  698. Ref<Texture2D> remove_texture = get_editor_theme_icon(SNAME("Close"));
  699. HashMap<String, TreeItem *>::Iterator E = _file_items.find(fpath);
  700. if (!E) {
  701. file_item = _results_display->create_item();
  702. file_item->set_text(0, fpath);
  703. file_item->set_metadata(0, fpath);
  704. file_item->add_button(0, remove_texture, -1, false, TTR("Remove result"));
  705. // The width of this column is restrained to checkboxes,
  706. // but that doesn't make sense for the parent items,
  707. // so we override their width so they can expand to full width.
  708. file_item->set_expand_right(0, true);
  709. _file_items[fpath] = file_item;
  710. } else {
  711. file_item = E->value;
  712. }
  713. Color file_item_color = _results_display->get_theme_color(SceneStringName(font_color)) * Color(1, 1, 1, 0.67);
  714. file_item->set_custom_color(0, file_item_color);
  715. file_item->set_selectable(0, false);
  716. int text_index = _with_replace ? 1 : 0;
  717. TreeItem *item = _results_display->create_item(file_item);
  718. // Do this first because it resets properties of the cell...
  719. item->set_cell_mode(text_index, TreeItem::CELL_MODE_CUSTOM);
  720. // Trim result item line.
  721. int old_text_size = text.size();
  722. text = text.strip_edges(true, false);
  723. int chars_removed = old_text_size - text.size();
  724. String start = vformat("%3s: ", line_number);
  725. item->set_text(text_index, start + text);
  726. item->set_custom_draw_callback(text_index, callable_mp(this, &FindInFilesPanel::draw_result_text));
  727. Result r;
  728. r.line_number = line_number;
  729. r.begin = begin;
  730. r.end = end;
  731. r.begin_trimmed = begin - chars_removed + start.size() - 1;
  732. _result_items[item] = r;
  733. if (_with_replace) {
  734. item->set_cell_mode(0, TreeItem::CELL_MODE_CHECK);
  735. item->set_checked(0, true);
  736. item->set_editable(0, true);
  737. item->add_button(1, remove_texture, -1, false, TTR("Remove result"));
  738. } else {
  739. item->add_button(0, remove_texture, -1, false, TTR("Remove result"));
  740. }
  741. }
  742. void FindInFilesPanel::draw_result_text(Object *item_obj, Rect2 rect) {
  743. TreeItem *item = Object::cast_to<TreeItem>(item_obj);
  744. if (!item) {
  745. return;
  746. }
  747. HashMap<TreeItem *, Result>::Iterator E = _result_items.find(item);
  748. if (!E) {
  749. return;
  750. }
  751. Result r = E->value;
  752. String item_text = item->get_text(_with_replace ? 1 : 0);
  753. Ref<Font> font = _results_display->get_theme_font(SceneStringName(font));
  754. int font_size = _results_display->get_theme_font_size(SceneStringName(font_size));
  755. Rect2 match_rect = rect;
  756. match_rect.position.x += font->get_string_size(item_text.left(r.begin_trimmed), HORIZONTAL_ALIGNMENT_LEFT, -1, font_size).x - 1;
  757. match_rect.size.x = font->get_string_size(_search_text_label->get_text(), HORIZONTAL_ALIGNMENT_LEFT, -1, font_size).x + 1;
  758. match_rect.position.y += 1 * EDSCALE;
  759. match_rect.size.y -= 2 * EDSCALE;
  760. _results_display->draw_rect(match_rect, get_theme_color(SNAME("accent_color"), EditorStringName(Editor)) * Color(1, 1, 1, 0.33), false, 2.0);
  761. _results_display->draw_rect(match_rect, get_theme_color(SNAME("accent_color"), EditorStringName(Editor)) * Color(1, 1, 1, 0.17), true);
  762. // Text is drawn by Tree already.
  763. }
  764. void FindInFilesPanel::_on_item_edited() {
  765. TreeItem *item = _results_display->get_selected();
  766. // Change opacity to half if checkbox is checked, otherwise full.
  767. Color use_color = _results_display->get_theme_color(SceneStringName(font_color));
  768. if (!item->is_checked(0)) {
  769. use_color.a *= 0.5;
  770. }
  771. item->set_custom_color(1, use_color);
  772. }
  773. void FindInFilesPanel::_on_finished() {
  774. update_matches_text();
  775. update_replace_buttons();
  776. set_progress_visible(false);
  777. _refresh_button->show();
  778. _cancel_button->hide();
  779. }
  780. void FindInFilesPanel::_on_refresh_button_clicked() {
  781. start_search();
  782. }
  783. void FindInFilesPanel::_on_cancel_button_clicked() {
  784. stop_search();
  785. }
  786. void FindInFilesPanel::_on_close_button_clicked() {
  787. emit_signal(SNAME(SIGNAL_CLOSE_BUTTON_CLICKED));
  788. }
  789. void FindInFilesPanel::_on_result_selected() {
  790. TreeItem *item = _results_display->get_selected();
  791. HashMap<TreeItem *, Result>::Iterator E = _result_items.find(item);
  792. if (!E) {
  793. return;
  794. }
  795. Result r = E->value;
  796. TreeItem *file_item = item->get_parent();
  797. String fpath = file_item->get_metadata(0);
  798. emit_signal(SNAME(SIGNAL_RESULT_SELECTED), fpath, r.line_number, r.begin, r.end);
  799. }
  800. void FindInFilesPanel::_on_replace_text_changed(const String &text) {
  801. update_replace_buttons();
  802. }
  803. void FindInFilesPanel::_on_replace_all_clicked() {
  804. String replace_text = get_replace_text();
  805. PackedStringArray modified_files;
  806. for (KeyValue<String, TreeItem *> &E : _file_items) {
  807. TreeItem *file_item = E.value;
  808. String fpath = file_item->get_metadata(0);
  809. Vector<Result> locations;
  810. for (TreeItem *item = file_item->get_first_child(); item; item = item->get_next()) {
  811. if (!item->is_checked(0)) {
  812. continue;
  813. }
  814. HashMap<TreeItem *, Result>::Iterator F = _result_items.find(item);
  815. ERR_FAIL_COND(!F);
  816. locations.push_back(F->value);
  817. }
  818. if (locations.size() != 0) {
  819. // Results are sorted by file, so we can batch replaces.
  820. apply_replaces_in_file(fpath, locations, replace_text);
  821. modified_files.push_back(fpath);
  822. }
  823. }
  824. // Hide replace bar so we can't trigger the action twice without doing a new search.
  825. _replace_container->hide();
  826. emit_signal(SNAME(SIGNAL_FILES_MODIFIED), modified_files);
  827. }
  828. void FindInFilesPanel::_on_button_clicked(TreeItem *p_item, int p_column, int p_id, int p_mouse_button_index) {
  829. const String file_path = p_item->get_text(0);
  830. _result_items.erase(p_item);
  831. if (_file_items.find(file_path)) {
  832. TreeItem *file_result = _file_items.get(file_path);
  833. int match_count = file_result->get_child_count();
  834. for (int i = 0; i < match_count; i++) {
  835. TreeItem *child_item = file_result->get_child(i);
  836. _result_items.erase(child_item);
  837. }
  838. file_result->clear_children();
  839. _file_items.erase(file_path);
  840. }
  841. TreeItem *item_parent = p_item->get_parent();
  842. if (item_parent && item_parent->get_child_count() < 2) {
  843. _file_items.erase(item_parent->get_text(0));
  844. get_tree()->queue_delete(item_parent);
  845. }
  846. get_tree()->queue_delete(p_item);
  847. update_matches_text();
  848. }
  849. // Same as get_line, but preserves line ending characters.
  850. class ConservativeGetLine {
  851. public:
  852. String get_line(Ref<FileAccess> f) {
  853. _line_buffer.clear();
  854. char32_t c = f->get_8();
  855. while (!f->eof_reached()) {
  856. if (c == '\n') {
  857. _line_buffer.push_back(c);
  858. _line_buffer.push_back(0);
  859. return String::utf8(_line_buffer.ptr());
  860. } else if (c == '\0') {
  861. _line_buffer.push_back(c);
  862. return String::utf8(_line_buffer.ptr());
  863. } else if (c != '\r') {
  864. _line_buffer.push_back(c);
  865. }
  866. c = f->get_8();
  867. }
  868. _line_buffer.push_back(0);
  869. return String::utf8(_line_buffer.ptr());
  870. }
  871. private:
  872. Vector<char> _line_buffer;
  873. };
  874. void FindInFilesPanel::apply_replaces_in_file(const String &fpath, const Vector<Result> &locations, const String &new_text) {
  875. // If the file is already open, I assume the editor will reload it.
  876. // If there are unsaved changes, the user will be asked on focus,
  877. // however that means either losing changes or losing replaces.
  878. Ref<FileAccess> f = FileAccess::open(fpath, FileAccess::READ);
  879. ERR_FAIL_COND_MSG(f.is_null(), "Cannot open file from path '" + fpath + "'.");
  880. String buffer;
  881. int current_line = 1;
  882. ConservativeGetLine conservative;
  883. String line = conservative.get_line(f);
  884. String search_text = _finder->get_search_text();
  885. int offset = 0;
  886. for (int i = 0; i < locations.size(); ++i) {
  887. int repl_line_number = locations[i].line_number;
  888. while (current_line < repl_line_number) {
  889. buffer += line;
  890. line = conservative.get_line(f);
  891. ++current_line;
  892. offset = 0;
  893. }
  894. int repl_begin = locations[i].begin + offset;
  895. int repl_end = locations[i].end + offset;
  896. int _;
  897. if (!find_next(line, search_text, repl_begin, _finder->is_match_case(), _finder->is_whole_words(), _, _)) {
  898. // Make sure the replace is still valid in case the file was tampered with.
  899. 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)));
  900. continue;
  901. }
  902. line = line.left(repl_begin) + new_text + line.substr(repl_end);
  903. // Keep an offset in case there are successive replaces in the same line.
  904. offset += new_text.length() - (repl_end - repl_begin);
  905. }
  906. buffer += line;
  907. while (!f->eof_reached()) {
  908. buffer += conservative.get_line(f);
  909. }
  910. // Now the modified contents are in the buffer, rewrite the file with our changes.
  911. Error err = f->reopen(fpath, FileAccess::WRITE);
  912. ERR_FAIL_COND_MSG(err != OK, "Cannot create file in path '" + fpath + "'.");
  913. f->store_string(buffer);
  914. }
  915. String FindInFilesPanel::get_replace_text() {
  916. return _replace_line_edit->get_text();
  917. }
  918. void FindInFilesPanel::update_replace_buttons() {
  919. bool disabled = _finder->is_searching();
  920. _replace_all_button->set_disabled(disabled);
  921. }
  922. void FindInFilesPanel::update_matches_text() {
  923. String results_text;
  924. int result_count = _result_items.size();
  925. int file_count = _file_items.size();
  926. if (result_count == 1 && file_count == 1) {
  927. results_text = vformat(TTR("%d match in %d file"), result_count, file_count);
  928. } else if (result_count != 1 && file_count == 1) {
  929. results_text = vformat(TTR("%d matches in %d file"), result_count, file_count);
  930. } else {
  931. results_text = vformat(TTR("%d matches in %d files"), result_count, file_count);
  932. }
  933. _status_label->set_text(results_text);
  934. }
  935. void FindInFilesPanel::set_progress_visible(bool p_visible) {
  936. _progress_bar->set_self_modulate(Color(1, 1, 1, p_visible ? 1 : 0));
  937. }
  938. void FindInFilesPanel::_bind_methods() {
  939. ClassDB::bind_method("_on_result_found", &FindInFilesPanel::_on_result_found);
  940. ClassDB::bind_method("_on_finished", &FindInFilesPanel::_on_finished);
  941. ADD_SIGNAL(MethodInfo(SIGNAL_RESULT_SELECTED,
  942. PropertyInfo(Variant::STRING, "path"),
  943. PropertyInfo(Variant::INT, "line_number"),
  944. PropertyInfo(Variant::INT, "begin"),
  945. PropertyInfo(Variant::INT, "end")));
  946. ADD_SIGNAL(MethodInfo(SIGNAL_FILES_MODIFIED, PropertyInfo(Variant::STRING, "paths")));
  947. ADD_SIGNAL(MethodInfo(SIGNAL_CLOSE_BUTTON_CLICKED));
  948. }