find_in_files.cpp 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532
  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/gui/editor_file_dialog.h"
  37. #include "editor/settings/editor_command_palette.h"
  38. #include "editor/themes/editor_scale.h"
  39. #include "scene/gui/box_container.h"
  40. #include "scene/gui/button.h"
  41. #include "scene/gui/check_box.h"
  42. #include "scene/gui/check_button.h"
  43. #include "scene/gui/grid_container.h"
  44. #include "scene/gui/label.h"
  45. #include "scene/gui/line_edit.h"
  46. #include "scene/gui/progress_bar.h"
  47. #include "scene/gui/tab_container.h"
  48. #include "scene/gui/tree.h"
  49. const char *FindInFiles::SIGNAL_RESULT_FOUND = "result_found";
  50. // TODO: Would be nice in Vector and Vectors.
  51. template <typename T>
  52. inline void pop_back(T &container) {
  53. container.resize(container.size() - 1);
  54. }
  55. static bool find_next(const String &line, const 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_ascii_identifier_char(line[begin - 1]))) {
  67. continue;
  68. }
  69. if (end < line.size() && (is_ascii_identifier_char(line[end]))) {
  70. continue;
  71. }
  72. }
  73. return true;
  74. }
  75. }
  76. //--------------------------------------------------------------------------------
  77. void FindInFiles::set_search_text(const String &p_pattern) {
  78. _pattern = p_pattern;
  79. }
  80. void FindInFiles::set_whole_words(bool p_whole_word) {
  81. _whole_words = p_whole_word;
  82. }
  83. void FindInFiles::set_match_case(bool p_match_case) {
  84. _match_case = p_match_case;
  85. }
  86. void FindInFiles::set_folder(const String &folder) {
  87. _root_dir = folder;
  88. }
  89. void FindInFiles::set_filter(const HashSet<String> &exts) {
  90. _extension_filter = exts;
  91. }
  92. void FindInFiles::set_includes(const HashSet<String> &p_include_wildcards) {
  93. _include_wildcards = p_include_wildcards;
  94. }
  95. void FindInFiles::set_excludes(const HashSet<String> &p_exclude_wildcards) {
  96. _exclude_wildcards = p_exclude_wildcards;
  97. }
  98. void FindInFiles::_notification(int p_what) {
  99. switch (p_what) {
  100. case NOTIFICATION_PROCESS: {
  101. _process();
  102. } break;
  103. }
  104. }
  105. void FindInFiles::start() {
  106. if (_pattern.is_empty()) {
  107. print_verbose("Nothing to search, pattern is empty");
  108. emit_signal(SceneStringName(finished));
  109. return;
  110. }
  111. if (_extension_filter.is_empty()) {
  112. print_verbose("Nothing to search, filter matches no files");
  113. emit_signal(SceneStringName(finished));
  114. return;
  115. }
  116. // Init search.
  117. _current_dir = "";
  118. PackedStringArray init_folder;
  119. init_folder.push_back(_root_dir);
  120. _folders_stack.clear();
  121. _folders_stack.push_back(init_folder);
  122. _initial_files_count = 0;
  123. _searching = true;
  124. set_process(true);
  125. }
  126. void FindInFiles::stop() {
  127. _searching = false;
  128. _current_dir = "";
  129. set_process(false);
  130. }
  131. void FindInFiles::_process() {
  132. // This part can be moved to a thread if needed.
  133. OS &os = *OS::get_singleton();
  134. uint64_t time_before = os.get_ticks_msec();
  135. while (is_processing()) {
  136. _iterate();
  137. uint64_t elapsed = (os.get_ticks_msec() - time_before);
  138. if (elapsed > 8) { // Process again after waiting 8 ticks.
  139. break;
  140. }
  141. }
  142. }
  143. void FindInFiles::_iterate() {
  144. if (_folders_stack.size() != 0) {
  145. // Scan folders first so we can build a list of files and have progress info later.
  146. PackedStringArray &folders_to_scan = _folders_stack.write[_folders_stack.size() - 1];
  147. if (folders_to_scan.size() != 0) {
  148. // Scan one folder below.
  149. String folder_name = folders_to_scan[folders_to_scan.size() - 1];
  150. pop_back(folders_to_scan);
  151. _current_dir = _current_dir.path_join(folder_name);
  152. PackedStringArray sub_dirs;
  153. PackedStringArray files_to_scan;
  154. _scan_dir("res://" + _current_dir, sub_dirs, files_to_scan);
  155. _folders_stack.push_back(sub_dirs);
  156. _files_to_scan.append_array(files_to_scan);
  157. } else {
  158. // Go back one level.
  159. pop_back(_folders_stack);
  160. _current_dir = _current_dir.get_base_dir();
  161. if (_folders_stack.is_empty()) {
  162. // All folders scanned.
  163. _initial_files_count = _files_to_scan.size();
  164. }
  165. }
  166. } else if (_files_to_scan.size() != 0) {
  167. // Then scan files.
  168. String fpath = _files_to_scan[_files_to_scan.size() - 1];
  169. pop_back(_files_to_scan);
  170. _scan_file(fpath);
  171. } else {
  172. print_verbose("Search complete");
  173. set_process(false);
  174. _current_dir = "";
  175. _searching = false;
  176. emit_signal(SceneStringName(finished));
  177. }
  178. }
  179. float FindInFiles::get_progress() const {
  180. if (_initial_files_count != 0) {
  181. return static_cast<float>(_initial_files_count - _files_to_scan.size()) / static_cast<float>(_initial_files_count);
  182. }
  183. return 0;
  184. }
  185. void FindInFiles::_scan_dir(const String &path, PackedStringArray &out_folders, PackedStringArray &out_files_to_scan) {
  186. Ref<DirAccess> dir = DirAccess::open(path);
  187. if (dir.is_null()) {
  188. print_verbose("Cannot open directory! " + path);
  189. return;
  190. }
  191. dir->list_dir_begin();
  192. // Limit to 100,000 iterations to avoid an infinite loop just in case
  193. // (this technically limits results to 100,000 files per folder).
  194. for (int i = 0; i < 100'000; ++i) {
  195. String file = dir->get_next();
  196. if (file.is_empty()) {
  197. break;
  198. }
  199. // If there is a .gdignore file in the directory, clear all the files/folders
  200. // to be searched on this path and skip searching the directory.
  201. if (file == ".gdignore") {
  202. out_folders.clear();
  203. out_files_to_scan.clear();
  204. break;
  205. }
  206. // Ignore special directories (such as those beginning with . and the project data directory).
  207. String project_data_dir_name = ProjectSettings::get_singleton()->get_project_data_dir_name();
  208. if (file.begins_with(".") || file == project_data_dir_name) {
  209. continue;
  210. }
  211. if (dir->current_is_hidden()) {
  212. continue;
  213. }
  214. if (dir->current_is_dir()) {
  215. out_folders.push_back(file);
  216. } else {
  217. String file_ext = file.get_extension();
  218. if (_extension_filter.has(file_ext)) {
  219. String file_path = path.path_join(file);
  220. bool case_sensitive = dir->is_case_sensitive(path);
  221. if (!_exclude_wildcards.is_empty() && _is_file_matched(_exclude_wildcards, file_path, case_sensitive)) {
  222. continue;
  223. }
  224. if (_include_wildcards.is_empty() || _is_file_matched(_include_wildcards, file_path, case_sensitive)) {
  225. out_files_to_scan.push_back(file_path);
  226. }
  227. }
  228. }
  229. }
  230. }
  231. void FindInFiles::_scan_file(const String &fpath) {
  232. Ref<FileAccess> f = FileAccess::open(fpath, FileAccess::READ);
  233. if (f.is_null()) {
  234. print_verbose(String("Cannot open file ") + fpath);
  235. return;
  236. }
  237. int line_number = 0;
  238. while (!f->eof_reached()) {
  239. // Line number starts at 1.
  240. ++line_number;
  241. int begin = 0;
  242. int end = 0;
  243. String line = f->get_line();
  244. while (find_next(line, _pattern, end, _match_case, _whole_words, begin, end)) {
  245. emit_signal(SNAME(SIGNAL_RESULT_FOUND), fpath, line_number, begin, end, line);
  246. }
  247. }
  248. }
  249. bool FindInFiles::_is_file_matched(const HashSet<String> &p_wildcards, const String &p_file_path, bool p_case_sensitive) const {
  250. const String file_path = "/" + p_file_path.replace_char('\\', '/') + "/";
  251. for (const String &wildcard : p_wildcards) {
  252. if (p_case_sensitive && file_path.match(wildcard)) {
  253. return true;
  254. } else if (!p_case_sensitive && file_path.matchn(wildcard)) {
  255. return true;
  256. }
  257. }
  258. return false;
  259. }
  260. void FindInFiles::_bind_methods() {
  261. ADD_SIGNAL(MethodInfo(SIGNAL_RESULT_FOUND,
  262. PropertyInfo(Variant::STRING, "path"),
  263. PropertyInfo(Variant::INT, "line_number"),
  264. PropertyInfo(Variant::INT, "begin"),
  265. PropertyInfo(Variant::INT, "end"),
  266. PropertyInfo(Variant::STRING, "text")));
  267. ADD_SIGNAL(MethodInfo("finished"));
  268. }
  269. //-----------------------------------------------------------------------------
  270. const char *FindInFilesDialog::SIGNAL_FIND_REQUESTED = "find_requested";
  271. const char *FindInFilesDialog::SIGNAL_REPLACE_REQUESTED = "replace_requested";
  272. FindInFilesDialog::FindInFilesDialog() {
  273. set_min_size(Size2(500 * EDSCALE, 0));
  274. set_title(TTRC("Find in Files"));
  275. VBoxContainer *vbc = memnew(VBoxContainer);
  276. vbc->set_anchor_and_offset(SIDE_LEFT, Control::ANCHOR_BEGIN, 8 * EDSCALE);
  277. vbc->set_anchor_and_offset(SIDE_TOP, Control::ANCHOR_BEGIN, 8 * EDSCALE);
  278. vbc->set_anchor_and_offset(SIDE_RIGHT, Control::ANCHOR_END, -8 * EDSCALE);
  279. vbc->set_anchor_and_offset(SIDE_BOTTOM, Control::ANCHOR_END, -8 * EDSCALE);
  280. add_child(vbc);
  281. GridContainer *gc = memnew(GridContainer);
  282. gc->set_columns(2);
  283. vbc->add_child(gc);
  284. Label *find_label = memnew(Label);
  285. find_label->set_text(TTRC("Find:"));
  286. gc->add_child(find_label);
  287. _search_text_line_edit = memnew(LineEdit);
  288. _search_text_line_edit->set_h_size_flags(Control::SIZE_EXPAND_FILL);
  289. _search_text_line_edit->set_accessibility_name(TTRC("Find:"));
  290. _search_text_line_edit->connect(SceneStringName(text_changed), callable_mp(this, &FindInFilesDialog::_on_search_text_modified));
  291. _search_text_line_edit->connect(SceneStringName(text_submitted), callable_mp(this, &FindInFilesDialog::_on_search_text_submitted));
  292. gc->add_child(_search_text_line_edit);
  293. _replace_label = memnew(Label);
  294. _replace_label->set_text(TTRC("Replace:"));
  295. _replace_label->hide();
  296. gc->add_child(_replace_label);
  297. _replace_text_line_edit = memnew(LineEdit);
  298. _replace_text_line_edit->set_h_size_flags(Control::SIZE_EXPAND_FILL);
  299. _replace_text_line_edit->set_accessibility_name(TTRC("Replace:"));
  300. _replace_text_line_edit->connect(SceneStringName(text_submitted), callable_mp(this, &FindInFilesDialog::_on_replace_text_submitted));
  301. _replace_text_line_edit->hide();
  302. gc->add_child(_replace_text_line_edit);
  303. gc->add_child(memnew(Control)); // Space to maintain the grid alignment.
  304. {
  305. HBoxContainer *hbc = memnew(HBoxContainer);
  306. _whole_words_checkbox = memnew(CheckBox);
  307. _whole_words_checkbox->set_text(TTRC("Whole Words"));
  308. hbc->add_child(_whole_words_checkbox);
  309. _match_case_checkbox = memnew(CheckBox);
  310. _match_case_checkbox->set_text(TTRC("Match Case"));
  311. hbc->add_child(_match_case_checkbox);
  312. gc->add_child(hbc);
  313. }
  314. Label *folder_label = memnew(Label);
  315. folder_label->set_text(TTRC("Folder:"));
  316. gc->add_child(folder_label);
  317. {
  318. HBoxContainer *hbc = memnew(HBoxContainer);
  319. Label *prefix_label = memnew(Label);
  320. prefix_label->set_text("res://");
  321. prefix_label->set_auto_translate_mode(AUTO_TRANSLATE_MODE_DISABLED);
  322. hbc->add_child(prefix_label);
  323. _folder_line_edit = memnew(LineEdit);
  324. _folder_line_edit->set_h_size_flags(Control::SIZE_EXPAND_FILL);
  325. _folder_line_edit->connect(SceneStringName(text_submitted), callable_mp(this, &FindInFilesDialog::_on_search_text_submitted));
  326. _folder_line_edit->set_accessibility_name(TTRC("Folder:"));
  327. hbc->add_child(_folder_line_edit);
  328. Button *folder_button = memnew(Button);
  329. folder_button->set_accessibility_name(TTRC("Select Folder"));
  330. folder_button->set_text("...");
  331. folder_button->connect(SceneStringName(pressed), callable_mp(this, &FindInFilesDialog::_on_folder_button_pressed));
  332. hbc->add_child(folder_button);
  333. _folder_dialog = memnew(EditorFileDialog);
  334. _folder_dialog->set_file_mode(FileDialog::FILE_MODE_OPEN_DIR);
  335. _folder_dialog->connect("dir_selected", callable_mp(this, &FindInFilesDialog::_on_folder_selected));
  336. add_child(_folder_dialog);
  337. gc->add_child(hbc);
  338. }
  339. Label *includes_label = memnew(Label);
  340. includes_label->set_text(TTRC("Includes:"));
  341. includes_label->set_tooltip_text(TTRC("Include the files with the following expressions. Use \",\" to separate."));
  342. includes_label->set_mouse_filter(Control::MOUSE_FILTER_PASS);
  343. gc->add_child(includes_label);
  344. _includes_line_edit = memnew(LineEdit);
  345. _includes_line_edit->set_h_size_flags(Control::SIZE_EXPAND_FILL);
  346. _includes_line_edit->set_placeholder(TTRC("example: scripts,scenes/*/test.gd"));
  347. _includes_line_edit->set_accessibility_name(TTRC("Includes:"));
  348. _includes_line_edit->connect(SceneStringName(text_submitted), callable_mp(this, &FindInFilesDialog::_on_search_text_submitted));
  349. gc->add_child(_includes_line_edit);
  350. Label *excludes_label = memnew(Label);
  351. excludes_label->set_text(TTRC("Excludes:"));
  352. excludes_label->set_tooltip_text(TTRC("Exclude the files with the following expressions. Use \",\" to separate."));
  353. excludes_label->set_mouse_filter(Control::MOUSE_FILTER_PASS);
  354. gc->add_child(excludes_label);
  355. _excludes_line_edit = memnew(LineEdit);
  356. _excludes_line_edit->set_h_size_flags(Control::SIZE_EXPAND_FILL);
  357. _excludes_line_edit->set_placeholder(TTRC("example: res://addons,scenes/test/*.gd"));
  358. _excludes_line_edit->set_accessibility_name(TTRC("Excludes:"));
  359. _excludes_line_edit->connect(SceneStringName(text_submitted), callable_mp(this, &FindInFilesDialog::_on_search_text_submitted));
  360. gc->add_child(_excludes_line_edit);
  361. Label *filter_label = memnew(Label);
  362. filter_label->set_text(TTRC("Filters:"));
  363. filter_label->set_tooltip_text(TTRC("Include the files with the following extensions. Add or remove them in ProjectSettings."));
  364. filter_label->set_mouse_filter(Control::MOUSE_FILTER_PASS);
  365. gc->add_child(filter_label);
  366. _filters_container = memnew(HBoxContainer);
  367. gc->add_child(_filters_container);
  368. _find_button = add_button(TTRC("Find..."), false, "find");
  369. _find_button->set_disabled(true);
  370. _replace_button = add_button(TTRC("Replace..."), false, "replace");
  371. _replace_button->set_disabled(true);
  372. Button *cancel_button = get_ok_button();
  373. cancel_button->set_text(TTRC("Cancel"));
  374. _mode = SEARCH_MODE;
  375. }
  376. void FindInFilesDialog::set_search_text(const String &text) {
  377. if (_mode == SEARCH_MODE) {
  378. if (!text.is_empty()) {
  379. _search_text_line_edit->set_text(text);
  380. _on_search_text_modified(text);
  381. }
  382. callable_mp((Control *)_search_text_line_edit, &Control::grab_focus).call_deferred(false);
  383. _search_text_line_edit->select_all();
  384. } else if (_mode == REPLACE_MODE) {
  385. if (!text.is_empty()) {
  386. _search_text_line_edit->set_text(text);
  387. callable_mp((Control *)_replace_text_line_edit, &Control::grab_focus).call_deferred(false);
  388. _replace_text_line_edit->select_all();
  389. _on_search_text_modified(text);
  390. } else {
  391. callable_mp((Control *)_search_text_line_edit, &Control::grab_focus).call_deferred(false);
  392. _search_text_line_edit->select_all();
  393. }
  394. }
  395. }
  396. void FindInFilesDialog::set_replace_text(const String &text) {
  397. _replace_text_line_edit->set_text(text);
  398. }
  399. void FindInFilesDialog::set_find_in_files_mode(FindInFilesMode p_mode) {
  400. if (_mode == p_mode) {
  401. return;
  402. }
  403. _mode = p_mode;
  404. if (p_mode == SEARCH_MODE) {
  405. set_title(TTRC("Find in Files"));
  406. _replace_label->hide();
  407. _replace_text_line_edit->hide();
  408. } else if (p_mode == REPLACE_MODE) {
  409. set_title(TTRC("Replace in Files"));
  410. _replace_label->show();
  411. _replace_text_line_edit->show();
  412. }
  413. // Recalculate the dialog size after hiding child controls.
  414. set_size(Size2(get_size().x, 0));
  415. }
  416. String FindInFilesDialog::get_search_text() const {
  417. return _search_text_line_edit->get_text();
  418. }
  419. String FindInFilesDialog::get_replace_text() const {
  420. return _replace_text_line_edit->get_text();
  421. }
  422. bool FindInFilesDialog::is_match_case() const {
  423. return _match_case_checkbox->is_pressed();
  424. }
  425. bool FindInFilesDialog::is_whole_words() const {
  426. return _whole_words_checkbox->is_pressed();
  427. }
  428. String FindInFilesDialog::get_folder() const {
  429. String text = _folder_line_edit->get_text();
  430. return text.strip_edges();
  431. }
  432. HashSet<String> FindInFilesDialog::get_filter() const {
  433. // Could check the _filters_preferences but it might not have been generated yet.
  434. HashSet<String> filters;
  435. for (int i = 0; i < _filters_container->get_child_count(); ++i) {
  436. CheckBox *cb = static_cast<CheckBox *>(_filters_container->get_child(i));
  437. if (cb->is_pressed()) {
  438. filters.insert(cb->get_text());
  439. }
  440. }
  441. return filters;
  442. }
  443. HashSet<String> FindInFilesDialog::get_includes() const {
  444. HashSet<String> includes;
  445. String text = _includes_line_edit->get_text();
  446. if (text.is_empty()) {
  447. return includes;
  448. }
  449. PackedStringArray wildcards = text.split(",", false);
  450. for (const String &wildcard : wildcards) {
  451. includes.insert(validate_filter_wildcard(wildcard));
  452. }
  453. return includes;
  454. }
  455. HashSet<String> FindInFilesDialog::get_excludes() const {
  456. HashSet<String> excludes;
  457. String text = _excludes_line_edit->get_text();
  458. if (text.is_empty()) {
  459. return excludes;
  460. }
  461. PackedStringArray wildcards = text.split(",", false);
  462. for (const String &wildcard : wildcards) {
  463. excludes.insert(validate_filter_wildcard(wildcard));
  464. }
  465. return excludes;
  466. }
  467. void FindInFilesDialog::_notification(int p_what) {
  468. switch (p_what) {
  469. case NOTIFICATION_VISIBILITY_CHANGED: {
  470. if (is_visible()) {
  471. // Extensions might have changed in the meantime, we clean them and instance them again.
  472. for (int i = 0; i < _filters_container->get_child_count(); i++) {
  473. _filters_container->get_child(i)->queue_free();
  474. }
  475. Array exts = GLOBAL_GET("editor/script/search_in_file_extensions");
  476. for (int i = 0; i < exts.size(); ++i) {
  477. CheckBox *cb = memnew(CheckBox);
  478. cb->set_text(exts[i]);
  479. if (!_filters_preferences.has(exts[i])) {
  480. _filters_preferences[exts[i]] = true;
  481. }
  482. cb->set_pressed(_filters_preferences[exts[i]]);
  483. _filters_container->add_child(cb);
  484. }
  485. }
  486. } break;
  487. }
  488. }
  489. void FindInFilesDialog::_on_folder_button_pressed() {
  490. _folder_dialog->popup_file_dialog();
  491. }
  492. void FindInFilesDialog::custom_action(const String &p_action) {
  493. for (int i = 0; i < _filters_container->get_child_count(); ++i) {
  494. CheckBox *cb = static_cast<CheckBox *>(_filters_container->get_child(i));
  495. _filters_preferences[cb->get_text()] = cb->is_pressed();
  496. }
  497. if (p_action == "find") {
  498. emit_signal(SNAME(SIGNAL_FIND_REQUESTED));
  499. hide();
  500. } else if (p_action == "replace") {
  501. emit_signal(SNAME(SIGNAL_REPLACE_REQUESTED));
  502. hide();
  503. }
  504. }
  505. void FindInFilesDialog::_on_search_text_modified(const String &text) {
  506. ERR_FAIL_NULL(_find_button);
  507. ERR_FAIL_NULL(_replace_button);
  508. _find_button->set_disabled(get_search_text().is_empty());
  509. _replace_button->set_disabled(get_search_text().is_empty());
  510. }
  511. void FindInFilesDialog::_on_search_text_submitted(const String &text) {
  512. // This allows to trigger a global search without leaving the keyboard.
  513. if (!_find_button->is_disabled()) {
  514. if (_mode == SEARCH_MODE) {
  515. custom_action("find");
  516. }
  517. }
  518. if (!_replace_button->is_disabled()) {
  519. if (_mode == REPLACE_MODE) {
  520. custom_action("replace");
  521. }
  522. }
  523. }
  524. void FindInFilesDialog::_on_replace_text_submitted(const String &text) {
  525. // This allows to trigger a global search without leaving the keyboard.
  526. if (!_replace_button->is_disabled()) {
  527. if (_mode == REPLACE_MODE) {
  528. custom_action("replace");
  529. }
  530. }
  531. }
  532. void FindInFilesDialog::_on_folder_selected(String path) {
  533. int i = path.find("://");
  534. if (i != -1) {
  535. path = path.substr(i + 3);
  536. }
  537. _folder_line_edit->set_text(path);
  538. }
  539. String FindInFilesDialog::validate_filter_wildcard(const String &p_expression) const {
  540. String ret = p_expression.replace_char('\\', '/');
  541. if (ret.begins_with("./")) {
  542. // Relative to the project root.
  543. ret = "res://" + ret.trim_prefix("./");
  544. }
  545. if (ret.begins_with(".")) {
  546. // To match extension.
  547. ret = "*" + ret;
  548. }
  549. if (!ret.begins_with("*")) {
  550. ret = "*/" + ret.trim_prefix("/");
  551. }
  552. if (!ret.ends_with("*")) {
  553. ret = ret.trim_suffix("/") + "/*";
  554. }
  555. return ret;
  556. }
  557. void FindInFilesDialog::_bind_methods() {
  558. ADD_SIGNAL(MethodInfo(SIGNAL_FIND_REQUESTED));
  559. ADD_SIGNAL(MethodInfo(SIGNAL_REPLACE_REQUESTED));
  560. }
  561. //-----------------------------------------------------------------------------
  562. const char *FindInFilesPanel::SIGNAL_RESULT_SELECTED = "result_selected";
  563. const char *FindInFilesPanel::SIGNAL_FILES_MODIFIED = "files_modified";
  564. const char *FindInFilesPanel::SIGNAL_CLOSE_BUTTON_CLICKED = "close_button_clicked";
  565. FindInFilesPanel::FindInFilesPanel() {
  566. _finder = memnew(FindInFiles);
  567. _finder->connect(FindInFiles::SIGNAL_RESULT_FOUND, callable_mp(this, &FindInFilesPanel::_on_result_found));
  568. _finder->connect(SceneStringName(finished), callable_mp(this, &FindInFilesPanel::_on_finished));
  569. add_child(_finder);
  570. VBoxContainer *vbc = memnew(VBoxContainer);
  571. vbc->set_anchor_and_offset(SIDE_LEFT, ANCHOR_BEGIN, 0);
  572. vbc->set_anchor_and_offset(SIDE_TOP, ANCHOR_BEGIN, 0);
  573. vbc->set_anchor_and_offset(SIDE_RIGHT, ANCHOR_END, 0);
  574. vbc->set_anchor_and_offset(SIDE_BOTTOM, ANCHOR_END, 0);
  575. add_child(vbc);
  576. {
  577. HBoxContainer *hbc = memnew(HBoxContainer);
  578. hbc->set_alignment(BoxContainer::ALIGNMENT_END);
  579. _find_label = memnew(Label);
  580. _find_label->set_text(TTRC("Find:"));
  581. hbc->add_child(_find_label);
  582. _search_text_label = memnew(Label);
  583. _search_text_label->set_text_overrun_behavior(TextServer::OVERRUN_TRIM_ELLIPSIS);
  584. _search_text_label->set_h_size_flags(Control::SIZE_EXPAND_FILL);
  585. _search_text_label->set_focus_mode(FOCUS_ACCESSIBILITY);
  586. _search_text_label->set_mouse_filter(Control::MOUSE_FILTER_PASS);
  587. _search_text_label->set_auto_translate_mode(AUTO_TRANSLATE_MODE_DISABLED);
  588. hbc->add_child(_search_text_label);
  589. _progress_bar = memnew(ProgressBar);
  590. _progress_bar->set_h_size_flags(SIZE_EXPAND_FILL);
  591. _progress_bar->set_v_size_flags(SIZE_SHRINK_CENTER);
  592. _progress_bar->set_stretch_ratio(2.0);
  593. _progress_bar->set_visible(false);
  594. hbc->add_child(_progress_bar);
  595. _status_label = memnew(Label);
  596. _status_label->set_focus_mode(FOCUS_ACCESSIBILITY);
  597. hbc->add_child(_status_label);
  598. _keep_results_button = memnew(CheckButton);
  599. _keep_results_button->set_text(TTRC("Keep Results"));
  600. _keep_results_button->set_tooltip_text(TTRC("Keep these results and show subsequent results in a new window"));
  601. _keep_results_button->set_pressed(false);
  602. hbc->add_child(_keep_results_button);
  603. _refresh_button = memnew(Button);
  604. _refresh_button->set_text(TTRC("Refresh"));
  605. _refresh_button->connect(SceneStringName(pressed), callable_mp(this, &FindInFilesPanel::_on_refresh_button_clicked));
  606. _refresh_button->hide();
  607. hbc->add_child(_refresh_button);
  608. _cancel_button = memnew(Button);
  609. _cancel_button->set_text(TTRC("Cancel"));
  610. _cancel_button->connect(SceneStringName(pressed), callable_mp(this, &FindInFilesPanel::_on_cancel_button_clicked));
  611. _cancel_button->hide();
  612. hbc->add_child(_cancel_button);
  613. _close_button = memnew(Button);
  614. _close_button->set_text(TTRC("Close"));
  615. _close_button->connect(SceneStringName(pressed), callable_mp(this, &FindInFilesPanel::_on_close_button_clicked));
  616. hbc->add_child(_close_button);
  617. vbc->add_child(hbc);
  618. }
  619. _results_mc = memnew(MarginContainer);
  620. _results_mc->set_theme_type_variation("NoBorderHorizontal");
  621. _results_mc->set_v_size_flags(SIZE_EXPAND_FILL);
  622. vbc->add_child(_results_mc);
  623. _results_display = memnew(Tree);
  624. _results_display->set_accessibility_name(TTRC("Search Results"));
  625. _results_display->set_auto_translate_mode(AUTO_TRANSLATE_MODE_DISABLED);
  626. _results_display->set_scroll_hint_mode(Tree::SCROLL_HINT_MODE_BOTH);
  627. _results_display->connect(SceneStringName(item_selected), callable_mp(this, &FindInFilesPanel::_on_result_selected));
  628. _results_display->connect("item_edited", callable_mp(this, &FindInFilesPanel::_on_item_edited));
  629. _results_display->connect("button_clicked", callable_mp(this, &FindInFilesPanel::_on_button_clicked));
  630. _results_display->set_hide_root(true);
  631. _results_display->set_select_mode(Tree::SELECT_ROW);
  632. _results_display->set_allow_rmb_select(true);
  633. _results_display->set_allow_reselect(true);
  634. _results_display->add_theme_constant_override("inner_item_margin_left", 0);
  635. _results_display->add_theme_constant_override("inner_item_margin_right", 0);
  636. _results_display->create_item(); // Root
  637. _results_mc->add_child(_results_display);
  638. {
  639. _replace_container = memnew(HBoxContainer);
  640. Label *replace_label = memnew(Label);
  641. replace_label->set_text(TTRC("Replace:"));
  642. _replace_container->add_child(replace_label);
  643. _replace_line_edit = memnew(LineEdit);
  644. _replace_line_edit->set_accessibility_name(TTRC("Replace:"));
  645. _replace_line_edit->set_h_size_flags(SIZE_EXPAND_FILL);
  646. _replace_line_edit->connect(SceneStringName(text_changed), callable_mp(this, &FindInFilesPanel::_on_replace_text_changed));
  647. _replace_container->add_child(_replace_line_edit);
  648. _replace_all_button = memnew(Button);
  649. _replace_all_button->set_text(TTRC("Replace all (no undo)"));
  650. _replace_all_button->connect(SceneStringName(pressed), callable_mp(this, &FindInFilesPanel::_on_replace_all_clicked));
  651. _replace_container->add_child(_replace_all_button);
  652. _replace_container->hide();
  653. vbc->add_child(_replace_container);
  654. }
  655. }
  656. void FindInFilesPanel::set_with_replace(bool with_replace) {
  657. _with_replace = with_replace;
  658. _replace_container->set_visible(with_replace);
  659. if (with_replace) {
  660. // Results show checkboxes on their left so they can be opted out.
  661. _results_display->set_columns(2);
  662. _results_display->set_column_expand(0, false);
  663. _results_display->set_column_custom_minimum_width(0, 48 * EDSCALE);
  664. } else {
  665. // Results are single-cell items.
  666. _results_display->set_column_expand(0, true);
  667. _results_display->set_columns(1);
  668. }
  669. }
  670. void FindInFilesPanel::set_replace_text(const String &text) {
  671. _replace_line_edit->set_text(text);
  672. }
  673. bool FindInFilesPanel::is_keep_results() const {
  674. return _keep_results_button->is_pressed();
  675. }
  676. void FindInFilesPanel::set_search_labels_visibility(bool p_visible) {
  677. _find_label->set_visible(p_visible);
  678. _search_text_label->set_visible(p_visible);
  679. _close_button->set_visible(p_visible);
  680. }
  681. void FindInFilesPanel::clear() {
  682. _file_items.clear();
  683. _file_items_results_count.clear();
  684. _result_items.clear();
  685. _results_display->clear();
  686. _results_display->create_item(); // Root
  687. }
  688. void FindInFilesPanel::start_search() {
  689. clear();
  690. _status_label->set_text(TTRC("Searching..."));
  691. _search_text_label->set_text(_finder->get_search_text());
  692. _search_text_label->set_tooltip_text(_finder->get_search_text());
  693. int label_min_width = _search_text_label->get_minimum_size().x + _search_text_label->get_character_bounds(0).size.x;
  694. _search_text_label->set_custom_minimum_size(Size2(label_min_width, 0));
  695. set_process(true);
  696. _progress_bar->set_visible(true);
  697. _finder->start();
  698. update_replace_buttons();
  699. _refresh_button->hide();
  700. _cancel_button->show();
  701. }
  702. void FindInFilesPanel::stop_search() {
  703. _finder->stop();
  704. _status_label->set_text("");
  705. update_replace_buttons();
  706. _progress_bar->set_visible(false);
  707. _refresh_button->show();
  708. _cancel_button->hide();
  709. }
  710. void FindInFilesPanel::update_layout(EditorDock::DockLayout p_layout) {
  711. bool new_floating = (p_layout == EditorDock::DOCK_LAYOUT_FLOATING);
  712. if (_floating == new_floating) {
  713. return;
  714. }
  715. _floating = new_floating;
  716. if (_floating) {
  717. _results_mc->set_theme_type_variation("NoBorderHorizontalBottom");
  718. _results_display->set_scroll_hint_mode(Tree::SCROLL_HINT_MODE_TOP);
  719. } else {
  720. _results_mc->set_theme_type_variation("NoBorderHorizontal");
  721. _results_display->set_scroll_hint_mode(Tree::SCROLL_HINT_MODE_BOTH);
  722. }
  723. }
  724. void FindInFilesPanel::_notification(int p_what) {
  725. switch (p_what) {
  726. case NOTIFICATION_THEME_CHANGED: {
  727. _on_theme_changed();
  728. } break;
  729. case NOTIFICATION_TRANSLATION_CHANGED: {
  730. update_matches_text();
  731. TreeItem *file_item = _results_display->get_root()->get_first_child();
  732. while (file_item) {
  733. if (_with_replace) {
  734. file_item->set_button_tooltip_text(0, file_item->get_button_by_id(0, FIND_BUTTON_REPLACE), TTR("Replace all matches in file"));
  735. }
  736. file_item->set_button_tooltip_text(0, file_item->get_button_by_id(0, FIND_BUTTON_REMOVE), TTR("Remove result"));
  737. TreeItem *result_item = file_item->get_first_child();
  738. while (result_item) {
  739. if (_with_replace) {
  740. result_item->set_button_tooltip_text(1, file_item->get_button_by_id(0, FIND_BUTTON_REPLACE), TTR("Replace"));
  741. result_item->set_button_tooltip_text(1, file_item->get_button_by_id(0, FIND_BUTTON_REMOVE), TTR("Remove result"));
  742. } else {
  743. result_item->set_button_tooltip_text(0, file_item->get_button_by_id(0, FIND_BUTTON_REMOVE), TTR("Remove result"));
  744. }
  745. result_item = result_item->get_next();
  746. }
  747. file_item = file_item->get_next();
  748. }
  749. } break;
  750. case NOTIFICATION_PROCESS: {
  751. _progress_bar->set_as_ratio(_finder->get_progress());
  752. } break;
  753. }
  754. }
  755. void FindInFilesPanel::_on_result_found(const String &fpath, int line_number, int begin, int end, String text) {
  756. TreeItem *file_item;
  757. Ref<Texture2D> remove_texture = get_editor_theme_icon(SNAME("Close"));
  758. Ref<Texture2D> replace_texture = get_editor_theme_icon(SNAME("ReplaceText"));
  759. HashMap<String, TreeItem *>::Iterator E = _file_items.find(fpath);
  760. if (!E) {
  761. file_item = _results_display->create_item();
  762. file_item->set_text(0, fpath);
  763. file_item->set_metadata(0, fpath);
  764. if (_with_replace) {
  765. file_item->add_button(0, replace_texture, FIND_BUTTON_REPLACE, false, TTR("Replace all matches in file"));
  766. }
  767. file_item->add_button(0, remove_texture, FIND_BUTTON_REMOVE, false, TTR("Remove result"));
  768. // The width of this column is restrained to checkboxes,
  769. // but that doesn't make sense for the parent items,
  770. // so we override their width so they can expand to full width.
  771. file_item->set_expand_right(0, true);
  772. _file_items[fpath] = file_item;
  773. _file_items_results_count[file_item] = 1;
  774. } else {
  775. file_item = E->value;
  776. _file_items_results_count[file_item]++;
  777. }
  778. Color file_item_color = _results_display->get_theme_color(SceneStringName(font_color)) * Color(1, 1, 1, 0.67);
  779. file_item->set_custom_color(0, file_item_color);
  780. file_item->set_selectable(0, false);
  781. int text_index = _with_replace ? 1 : 0;
  782. TreeItem *item = _results_display->create_item(file_item);
  783. // Do this first because it resets properties of the cell...
  784. item->set_cell_mode(text_index, TreeItem::CELL_MODE_CUSTOM);
  785. // Trim result item line.
  786. int old_text_size = text.size();
  787. text = text.strip_edges(true, false);
  788. int chars_removed = old_text_size - text.size();
  789. String start = vformat("%3s: ", line_number);
  790. item->set_text(text_index, start + text);
  791. item->set_custom_draw_callback(text_index, callable_mp(this, &FindInFilesPanel::draw_result_text));
  792. Result r;
  793. r.line_number = line_number;
  794. r.begin = begin;
  795. r.end = end;
  796. r.begin_trimmed = begin - chars_removed + start.size() - 1;
  797. _result_items[item] = r;
  798. if (_with_replace) {
  799. item->set_cell_mode(0, TreeItem::CELL_MODE_CHECK);
  800. item->set_checked(0, true);
  801. item->set_editable(0, true);
  802. item->add_button(1, replace_texture, FIND_BUTTON_REPLACE, false, TTR("Replace"));
  803. item->add_button(1, remove_texture, FIND_BUTTON_REMOVE, false, TTR("Remove result"));
  804. } else {
  805. item->add_button(0, remove_texture, FIND_BUTTON_REMOVE, false, TTR("Remove result"));
  806. }
  807. }
  808. void FindInFilesPanel::_on_theme_changed() {
  809. _results_display->add_theme_font_override(SceneStringName(font), get_theme_font(SNAME("source"), EditorStringName(EditorFonts)));
  810. _results_display->add_theme_font_size_override(SceneStringName(font_size), get_theme_font_size(SNAME("source_size"), EditorStringName(EditorFonts)));
  811. Color file_item_color = _results_display->get_theme_color(SceneStringName(font_color)) * Color(1, 1, 1, 0.67);
  812. Ref<Texture2D> remove_texture = get_editor_theme_icon(SNAME("Close"));
  813. Ref<Texture2D> replace_texture = get_editor_theme_icon(SNAME("ReplaceText"));
  814. TreeItem *file_item = _results_display->get_root()->get_first_child();
  815. while (file_item) {
  816. file_item->set_custom_color(0, file_item_color);
  817. if (_with_replace) {
  818. file_item->set_button(0, file_item->get_button_by_id(0, FIND_BUTTON_REPLACE), replace_texture);
  819. }
  820. file_item->set_button(0, file_item->get_button_by_id(0, FIND_BUTTON_REMOVE), remove_texture);
  821. TreeItem *result_item = file_item->get_first_child();
  822. while (result_item) {
  823. if (_with_replace) {
  824. result_item->set_button(1, result_item->get_button_by_id(1, FIND_BUTTON_REPLACE), replace_texture);
  825. result_item->set_button(1, result_item->get_button_by_id(1, FIND_BUTTON_REMOVE), remove_texture);
  826. } else {
  827. result_item->set_button(0, result_item->get_button_by_id(0, FIND_BUTTON_REMOVE), remove_texture);
  828. }
  829. result_item = result_item->get_next();
  830. }
  831. file_item = file_item->get_next();
  832. }
  833. }
  834. void FindInFilesPanel::draw_result_text(Object *item_obj, Rect2 rect) {
  835. TreeItem *item = Object::cast_to<TreeItem>(item_obj);
  836. if (!item) {
  837. return;
  838. }
  839. HashMap<TreeItem *, Result>::Iterator E = _result_items.find(item);
  840. if (!E) {
  841. return;
  842. }
  843. Result r = E->value;
  844. String item_text = item->get_text(_with_replace ? 1 : 0);
  845. Ref<Font> font = _results_display->get_theme_font(SceneStringName(font));
  846. int font_size = _results_display->get_theme_font_size(SceneStringName(font_size));
  847. Rect2 match_rect = rect;
  848. match_rect.position.x += font->get_string_size(item_text.left(r.begin_trimmed), HORIZONTAL_ALIGNMENT_LEFT, -1, font_size).x - 1;
  849. match_rect.size.x = font->get_string_size(_search_text_label->get_text(), HORIZONTAL_ALIGNMENT_LEFT, -1, font_size).x + 1;
  850. match_rect.position.y += 1 * EDSCALE;
  851. match_rect.size.y -= 2 * EDSCALE;
  852. _results_display->draw_rect(match_rect, get_theme_color(SNAME("accent_color"), EditorStringName(Editor)) * Color(1, 1, 1, 0.33), false, 2.0);
  853. _results_display->draw_rect(match_rect, get_theme_color(SNAME("accent_color"), EditorStringName(Editor)) * Color(1, 1, 1, 0.17), true);
  854. // Text is drawn by Tree already.
  855. }
  856. void FindInFilesPanel::_on_item_edited() {
  857. TreeItem *item = _results_display->get_selected();
  858. // Change opacity to half if checkbox is checked, otherwise full.
  859. Color use_color = _results_display->get_theme_color(SceneStringName(font_color));
  860. if (!item->is_checked(0)) {
  861. use_color.a *= 0.5;
  862. }
  863. item->set_custom_color(1, use_color);
  864. }
  865. void FindInFilesPanel::_on_finished() {
  866. update_matches_text();
  867. update_replace_buttons();
  868. _progress_bar->set_visible(false);
  869. _refresh_button->show();
  870. _cancel_button->hide();
  871. }
  872. void FindInFilesPanel::_on_refresh_button_clicked() {
  873. start_search();
  874. }
  875. void FindInFilesPanel::_on_cancel_button_clicked() {
  876. stop_search();
  877. }
  878. void FindInFilesPanel::_on_close_button_clicked() {
  879. emit_signal(SNAME(SIGNAL_CLOSE_BUTTON_CLICKED));
  880. }
  881. void FindInFilesPanel::_on_result_selected() {
  882. TreeItem *item = _results_display->get_selected();
  883. HashMap<TreeItem *, Result>::Iterator E = _result_items.find(item);
  884. if (!E) {
  885. return;
  886. }
  887. Result r = E->value;
  888. TreeItem *file_item = item->get_parent();
  889. String fpath = file_item->get_metadata(0);
  890. emit_signal(SNAME(SIGNAL_RESULT_SELECTED), fpath, r.line_number, r.begin, r.end);
  891. }
  892. void FindInFilesPanel::_on_replace_text_changed(const String &text) {
  893. update_replace_buttons();
  894. }
  895. void FindInFilesPanel::_on_replace_all_clicked() {
  896. String replace_text = get_replace_text();
  897. PackedStringArray modified_files;
  898. for (KeyValue<String, TreeItem *> &E : _file_items) {
  899. TreeItem *file_item = E.value;
  900. String fpath = file_item->get_metadata(0);
  901. Vector<Result> locations;
  902. for (TreeItem *item = file_item->get_first_child(); item; item = item->get_next()) {
  903. if (!item->is_checked(0)) {
  904. continue;
  905. }
  906. HashMap<TreeItem *, Result>::Iterator F = _result_items.find(item);
  907. ERR_FAIL_COND(!F);
  908. locations.push_back(F->value);
  909. }
  910. if (locations.size() != 0) {
  911. // Results are sorted by file, so we can batch replaces.
  912. apply_replaces_in_file(fpath, locations, replace_text);
  913. modified_files.push_back(fpath);
  914. }
  915. }
  916. // Hide replace bar so we can't trigger the action twice without doing a new search.
  917. _replace_container->hide();
  918. emit_signal(SNAME(SIGNAL_FILES_MODIFIED), modified_files);
  919. }
  920. void FindInFilesPanel::_on_button_clicked(TreeItem *p_item, int p_column, int p_id, int p_mouse_button_index) {
  921. const String file_path = p_item->get_metadata(0);
  922. if (p_id == FIND_BUTTON_REPLACE) {
  923. const String replace_text = get_replace_text();
  924. Vector<Result> locations;
  925. PackedStringArray modified_files;
  926. if (_file_items.has(file_path)) {
  927. for (TreeItem *item = p_item->get_first_child(); item; item = item->get_next()) {
  928. HashMap<TreeItem *, Result>::Iterator F = _result_items.find(item);
  929. ERR_FAIL_COND(!F);
  930. locations.push_back(F->value);
  931. }
  932. apply_replaces_in_file(file_path, locations, replace_text);
  933. modified_files.push_back(file_path);
  934. } else {
  935. locations.push_back(_result_items.find(p_item)->value);
  936. const String path = p_item->get_parent()->get_metadata(0);
  937. apply_replaces_in_file(path, locations, replace_text);
  938. modified_files.push_back(path);
  939. }
  940. emit_signal(SNAME(SIGNAL_FILES_MODIFIED), modified_files);
  941. }
  942. _result_items.erase(p_item);
  943. if (_file_items_results_count.has(p_item)) {
  944. int match_count = p_item->get_child_count();
  945. for (int i = 0; i < match_count; i++) {
  946. TreeItem *child_item = p_item->get_child(i);
  947. _result_items.erase(child_item);
  948. }
  949. p_item->clear_children();
  950. _file_items.erase(file_path);
  951. _file_items_results_count.erase(p_item);
  952. }
  953. TreeItem *item_parent = p_item->get_parent();
  954. if (item_parent) {
  955. if (_file_items_results_count.has(item_parent)) {
  956. _file_items_results_count[item_parent]--;
  957. }
  958. if (item_parent->get_child_count() < 2 && item_parent != _results_display->get_root()) {
  959. _file_items.erase(item_parent->get_metadata(0));
  960. get_tree()->queue_delete(item_parent);
  961. }
  962. }
  963. get_tree()->queue_delete(p_item);
  964. update_matches_text();
  965. }
  966. // Same as get_line, but preserves line ending characters.
  967. class ConservativeGetLine {
  968. public:
  969. String get_line(Ref<FileAccess> f) {
  970. _line_buffer.clear();
  971. char32_t c = f->get_8();
  972. while (!f->eof_reached()) {
  973. if (c == '\n') {
  974. _line_buffer.push_back(c);
  975. _line_buffer.push_back(0);
  976. return String::utf8(_line_buffer.ptr());
  977. } else if (c == '\0') {
  978. _line_buffer.push_back(c);
  979. return String::utf8(_line_buffer.ptr());
  980. } else if (c != '\r') {
  981. _line_buffer.push_back(c);
  982. }
  983. c = f->get_8();
  984. }
  985. _line_buffer.push_back(0);
  986. return String::utf8(_line_buffer.ptr());
  987. }
  988. private:
  989. Vector<char> _line_buffer;
  990. };
  991. void FindInFilesPanel::apply_replaces_in_file(const String &fpath, const Vector<Result> &locations, const String &new_text) {
  992. // If the file is already open, I assume the editor will reload it.
  993. // If there are unsaved changes, the user will be asked on focus,
  994. // however that means either losing changes or losing replaces.
  995. Ref<FileAccess> f = FileAccess::open(fpath, FileAccess::READ);
  996. ERR_FAIL_COND_MSG(f.is_null(), "Cannot open file from path '" + fpath + "'.");
  997. String buffer;
  998. int current_line = 1;
  999. ConservativeGetLine conservative;
  1000. String line = conservative.get_line(f);
  1001. String search_text = _finder->get_search_text();
  1002. int offset = 0;
  1003. for (int i = 0; i < locations.size(); ++i) {
  1004. int repl_line_number = locations[i].line_number;
  1005. while (current_line < repl_line_number) {
  1006. buffer += line;
  1007. line = conservative.get_line(f);
  1008. ++current_line;
  1009. offset = 0;
  1010. }
  1011. int repl_begin = locations[i].begin + offset;
  1012. int repl_end = locations[i].end + offset;
  1013. int _;
  1014. if (!find_next(line, search_text, repl_begin, _finder->is_match_case(), _finder->is_whole_words(), _, _)) {
  1015. // Make sure the replace is still valid in case the file was tampered with.
  1016. 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)));
  1017. continue;
  1018. }
  1019. line = line.left(repl_begin) + new_text + line.substr(repl_end);
  1020. // Keep an offset in case there are successive replaces in the same line.
  1021. offset += new_text.length() - (repl_end - repl_begin);
  1022. }
  1023. buffer += line;
  1024. while (!f->eof_reached()) {
  1025. buffer += conservative.get_line(f);
  1026. }
  1027. // Now the modified contents are in the buffer, rewrite the file with our changes.
  1028. Error err = f->reopen(fpath, FileAccess::WRITE);
  1029. ERR_FAIL_COND_MSG(err != OK, "Cannot create file in path '" + fpath + "'.");
  1030. f->store_string(buffer);
  1031. }
  1032. String FindInFilesPanel::get_replace_text() {
  1033. return _replace_line_edit->get_text();
  1034. }
  1035. void FindInFilesPanel::update_replace_buttons() {
  1036. bool disabled = _finder->is_searching();
  1037. _replace_all_button->set_disabled(disabled);
  1038. }
  1039. void FindInFilesPanel::update_matches_text() {
  1040. String results_text;
  1041. int result_count = _result_items.size();
  1042. int file_count = _file_items.size();
  1043. if (result_count == 1 && file_count == 1) {
  1044. results_text = vformat(TTR("%d match in %d file"), result_count, file_count);
  1045. } else if (result_count != 1 && file_count == 1) {
  1046. results_text = vformat(TTR("%d matches in %d file"), result_count, file_count);
  1047. } else {
  1048. results_text = vformat(TTR("%d matches in %d files"), result_count, file_count);
  1049. }
  1050. _status_label->set_text(results_text);
  1051. TreeItem *file_item = _results_display->get_root()->get_first_child();
  1052. while (file_item) {
  1053. int file_matches_count = _file_items_results_count[file_item];
  1054. file_item->set_text(0, (String)file_item->get_metadata(0) + " (" + vformat(TTRN("%d match", "%d matches", file_matches_count), file_matches_count) + ")");
  1055. file_item = file_item->get_next();
  1056. }
  1057. }
  1058. void FindInFilesPanel::_bind_methods() {
  1059. ClassDB::bind_method("_on_result_found", &FindInFilesPanel::_on_result_found);
  1060. ClassDB::bind_method("_on_finished", &FindInFilesPanel::_on_finished);
  1061. ADD_SIGNAL(MethodInfo(SIGNAL_RESULT_SELECTED,
  1062. PropertyInfo(Variant::STRING, "path"),
  1063. PropertyInfo(Variant::INT, "line_number"),
  1064. PropertyInfo(Variant::INT, "begin"),
  1065. PropertyInfo(Variant::INT, "end")));
  1066. ADD_SIGNAL(MethodInfo(SIGNAL_FILES_MODIFIED, PropertyInfo(Variant::STRING, "paths")));
  1067. ADD_SIGNAL(MethodInfo(SIGNAL_CLOSE_BUTTON_CLICKED));
  1068. }
  1069. //-----------------------------------------------------------------------------
  1070. FindInFilesContainer::FindInFilesContainer() {
  1071. set_name(TTRC("Search Results"));
  1072. set_icon_name("Search");
  1073. set_dock_shortcut(ED_SHORTCUT_AND_COMMAND("bottom_panels/toggle_search_results_bottom_panel", TTRC("Toggle Search Results Bottom Panel")));
  1074. set_default_slot(EditorDock::DOCK_SLOT_BOTTOM);
  1075. set_available_layouts(EditorDock::DOCK_LAYOUT_HORIZONTAL | EditorDock::DOCK_LAYOUT_FLOATING);
  1076. set_global(false);
  1077. set_transient(true);
  1078. set_closable(true);
  1079. set_custom_minimum_size(Size2(0, 200 * EDSCALE));
  1080. _tabs = memnew(TabContainer);
  1081. _tabs->set_tabs_visible(false);
  1082. add_child(_tabs);
  1083. _tabs->set_drag_to_rearrange_enabled(true);
  1084. _tabs->get_tab_bar()->set_select_with_rmb(true);
  1085. _tabs->get_tab_bar()->set_tab_close_display_policy(TabBar::CLOSE_BUTTON_SHOW_ACTIVE_ONLY);
  1086. _tabs->get_tab_bar()->connect("tab_close_pressed", callable_mp(this, &FindInFilesContainer::_on_tab_close_pressed));
  1087. _tabs->get_tab_bar()->connect(SceneStringName(gui_input), callable_mp(this, &FindInFilesContainer::_bar_input));
  1088. _tabs_context_menu = memnew(PopupMenu);
  1089. add_child(_tabs_context_menu);
  1090. _tabs_context_menu->add_item(TTRC("Close Tab"), PANEL_CLOSE);
  1091. _tabs_context_menu->add_item(TTRC("Close Other Tabs"), PANEL_CLOSE_OTHERS);
  1092. _tabs_context_menu->add_item(TTRC("Close Tabs to the Right"), PANEL_CLOSE_RIGHT);
  1093. _tabs_context_menu->add_item(TTRC("Close All Tabs"), PANEL_CLOSE_ALL);
  1094. _tabs_context_menu->connect(SceneStringName(id_pressed), callable_mp(this, &FindInFilesContainer::_bar_menu_option));
  1095. EditorNode::get_singleton()->get_gui_base()->connect(SceneStringName(theme_changed), callable_mp(this, &FindInFilesContainer::_on_theme_changed));
  1096. }
  1097. FindInFilesPanel *FindInFilesContainer::_create_new_panel() {
  1098. int index = _tabs->get_current_tab();
  1099. FindInFilesPanel *panel = memnew(FindInFilesPanel);
  1100. _tabs->add_child(panel);
  1101. _tabs->move_child(panel, index + 1); // New panel is added after the current activated panel.
  1102. _tabs->set_current_tab(index + 1);
  1103. _update_bar_visibility();
  1104. panel->connect(FindInFilesPanel::SIGNAL_RESULT_SELECTED, callable_mp(this, &FindInFilesContainer::_on_find_in_files_result_selected));
  1105. panel->connect(FindInFilesPanel::SIGNAL_FILES_MODIFIED, callable_mp(this, &FindInFilesContainer::_on_find_in_files_modified_files));
  1106. panel->connect(FindInFilesPanel::SIGNAL_CLOSE_BUTTON_CLICKED, callable_mp(this, &FindInFilesContainer::_on_find_in_files_close_button_clicked).bind(panel));
  1107. return panel;
  1108. }
  1109. FindInFilesPanel *FindInFilesContainer::_get_current_panel() {
  1110. return Object::cast_to<FindInFilesPanel>(_tabs->get_current_tab_control());
  1111. }
  1112. FindInFilesPanel *FindInFilesContainer::get_panel_for_results(const String &p_label) {
  1113. FindInFilesPanel *panel = nullptr;
  1114. // Prefer the current panel.
  1115. if (_get_current_panel() && !_get_current_panel()->is_keep_results()) {
  1116. panel = _get_current_panel();
  1117. } else {
  1118. // Find the first panel which does not keep results.
  1119. for (int i = 0; i < _tabs->get_tab_count(); i++) {
  1120. FindInFilesPanel *p = Object::cast_to<FindInFilesPanel>(_tabs->get_tab_control(i));
  1121. if (p && !p->is_keep_results()) {
  1122. panel = p;
  1123. _tabs->set_current_tab(i);
  1124. break;
  1125. }
  1126. }
  1127. if (!panel) {
  1128. panel = _create_new_panel();
  1129. }
  1130. }
  1131. _tabs->set_tab_title(_tabs->get_current_tab(), p_label);
  1132. return panel;
  1133. }
  1134. void FindInFilesContainer::_bind_methods() {
  1135. ADD_SIGNAL(MethodInfo("result_selected",
  1136. PropertyInfo(Variant::STRING, "path"),
  1137. PropertyInfo(Variant::INT, "line_number"),
  1138. PropertyInfo(Variant::INT, "begin"),
  1139. PropertyInfo(Variant::INT, "end")));
  1140. ADD_SIGNAL(MethodInfo("files_modified", PropertyInfo(Variant::STRING, "paths")));
  1141. }
  1142. void FindInFilesContainer::_notification(int p_what) {
  1143. switch (p_what) {
  1144. case NOTIFICATION_POSTINITIALIZE: {
  1145. connect("closed", callable_mp(this, &FindInFilesContainer::_on_dock_closed));
  1146. } break;
  1147. }
  1148. }
  1149. void FindInFilesContainer::_on_theme_changed() {
  1150. const Ref<StyleBox> bottom_panel_style = EditorNode::get_singleton()->get_editor_theme()->get_stylebox(SNAME("BottomPanel"), EditorStringName(EditorStyles));
  1151. if (bottom_panel_style.is_valid()) {
  1152. begin_bulk_theme_override();
  1153. add_theme_constant_override("margin_top", -bottom_panel_style->get_margin(SIDE_TOP));
  1154. add_theme_constant_override("margin_left", -bottom_panel_style->get_margin(SIDE_LEFT));
  1155. add_theme_constant_override("margin_right", -bottom_panel_style->get_margin(SIDE_RIGHT));
  1156. add_theme_constant_override("margin_bottom", -bottom_panel_style->get_margin(SIDE_BOTTOM));
  1157. end_bulk_theme_override();
  1158. }
  1159. }
  1160. void FindInFilesContainer::_on_find_in_files_result_selected(const String &p_fpath, int p_line_number, int p_begin, int p_end) {
  1161. emit_signal(SNAME("result_selected"), p_fpath, p_line_number, p_begin, p_end);
  1162. }
  1163. void FindInFilesContainer::_on_find_in_files_modified_files(const PackedStringArray &p_paths) {
  1164. emit_signal(SNAME("files_modified"), p_paths);
  1165. }
  1166. void FindInFilesContainer::_on_find_in_files_close_button_clicked(FindInFilesPanel *p_panel) {
  1167. ERR_FAIL_COND_MSG(p_panel->get_parent() != _tabs, "This panel is not a child!");
  1168. _tabs->remove_child(p_panel);
  1169. p_panel->queue_free();
  1170. _update_bar_visibility();
  1171. if (_tabs->get_tab_count() == 0) {
  1172. close();
  1173. }
  1174. }
  1175. void FindInFilesContainer::update_layout(EditorDock::DockLayout p_layout) {
  1176. for (Node *node : _tabs->iterate_children()) {
  1177. FindInFilesPanel *panel = Object::cast_to<FindInFilesPanel>(node);
  1178. if (panel) {
  1179. panel->update_layout(p_layout);
  1180. }
  1181. }
  1182. }
  1183. void FindInFilesContainer::_on_tab_close_pressed(int p_tab) {
  1184. FindInFilesPanel *panel = Object::cast_to<FindInFilesPanel>(_tabs->get_tab_control(p_tab));
  1185. if (panel) {
  1186. _on_find_in_files_close_button_clicked(panel);
  1187. }
  1188. }
  1189. void FindInFilesContainer::_update_bar_visibility() {
  1190. if (!_update_bar) {
  1191. return;
  1192. }
  1193. // If tab count <= 1, behaves like this is not a TabContainer and the bar is hidden.
  1194. bool bar_visible = _tabs->get_tab_count() > 1;
  1195. _tabs->set_tabs_visible(bar_visible);
  1196. // Hide or show the search labels based on the visibility of the bar, as the search terms are displayed in the title of each tab.
  1197. for (int i = 0; i < _tabs->get_tab_count(); i++) {
  1198. FindInFilesPanel *panel = Object::cast_to<FindInFilesPanel>(_tabs->get_tab_control(i));
  1199. if (panel) {
  1200. panel->set_search_labels_visibility(!bar_visible);
  1201. }
  1202. }
  1203. }
  1204. void FindInFilesContainer::_bar_menu_option(int p_option) {
  1205. int tab_index = _tabs->get_current_tab();
  1206. switch (p_option) {
  1207. case PANEL_CLOSE: {
  1208. _on_tab_close_pressed(tab_index);
  1209. } break;
  1210. case PANEL_CLOSE_OTHERS: {
  1211. _update_bar = false;
  1212. FindInFilesPanel *panel = Object::cast_to<FindInFilesPanel>(_tabs->get_tab_control(tab_index));
  1213. for (int i = _tabs->get_tab_count() - 1; i >= 0; i--) {
  1214. FindInFilesPanel *p = Object::cast_to<FindInFilesPanel>(_tabs->get_tab_control(i));
  1215. if (p != panel) {
  1216. _on_find_in_files_close_button_clicked(p);
  1217. }
  1218. }
  1219. _update_bar = true;
  1220. _update_bar_visibility();
  1221. } break;
  1222. case PANEL_CLOSE_RIGHT: {
  1223. _update_bar = false;
  1224. for (int i = _tabs->get_tab_count() - 1; i > tab_index; i--) {
  1225. _on_tab_close_pressed(i);
  1226. }
  1227. _update_bar = true;
  1228. _update_bar_visibility();
  1229. } break;
  1230. case PANEL_CLOSE_ALL: {
  1231. _update_bar = false;
  1232. for (int i = _tabs->get_tab_count() - 1; i >= 0; i--) {
  1233. _on_tab_close_pressed(i);
  1234. }
  1235. _update_bar = true;
  1236. } break;
  1237. }
  1238. }
  1239. void FindInFilesContainer::_bar_input(const Ref<InputEvent> &p_input) {
  1240. int tab_id = _tabs->get_tab_bar()->get_hovered_tab();
  1241. Ref<InputEventMouseButton> mb = p_input;
  1242. if (tab_id >= 0 && mb.is_valid() && mb->is_pressed() && mb->get_button_index() == MouseButton::RIGHT) {
  1243. _tabs_context_menu->set_item_disabled(_tabs_context_menu->get_item_index(PANEL_CLOSE_RIGHT), tab_id == _tabs->get_tab_count() - 1);
  1244. _tabs_context_menu->set_position(_tabs->get_tab_bar()->get_screen_position() + mb->get_position());
  1245. _tabs_context_menu->reset_size();
  1246. _tabs_context_menu->popup();
  1247. }
  1248. }
  1249. void FindInFilesContainer::_on_dock_closed() {
  1250. while (_tabs->get_tab_count() > 0) {
  1251. Control *tab = _tabs->get_tab_control(0);
  1252. _tabs->remove_child(tab);
  1253. tab->queue_free();
  1254. }
  1255. _update_bar_visibility();
  1256. }