find_in_files.cpp 33 KB

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