2
0

script_text_editor.cpp 118 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215
  1. /**************************************************************************/
  2. /* script_text_editor.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 "script_text_editor.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/io/dir_access.h"
  33. #include "core/io/json.h"
  34. #include "core/math/expression.h"
  35. #include "core/os/keyboard.h"
  36. #include "editor/debugger/editor_debugger_node.h"
  37. #include "editor/doc/editor_help.h"
  38. #include "editor/docks/filesystem_dock.h"
  39. #include "editor/editor_interface.h"
  40. #include "editor/editor_node.h"
  41. #include "editor/editor_string_names.h"
  42. #include "editor/gui/editor_toaster.h"
  43. #include "editor/inspector/editor_context_menu_plugin.h"
  44. #include "editor/inspector/editor_inspector.h"
  45. #include "editor/inspector/multi_node_edit.h"
  46. #include "editor/settings/editor_command_palette.h"
  47. #include "editor/settings/editor_settings.h"
  48. #include "editor/themes/editor_scale.h"
  49. #include "scene/gui/grid_container.h"
  50. #include "scene/gui/menu_button.h"
  51. #include "scene/gui/rich_text_label.h"
  52. #include "scene/gui/slider.h"
  53. #include "scene/gui/split_container.h"
  54. void ConnectionInfoDialog::ok_pressed() {
  55. }
  56. void ConnectionInfoDialog::popup_connections(const String &p_method, const Vector<Node *> &p_nodes) {
  57. method->set_text(p_method);
  58. tree->clear();
  59. TreeItem *root = tree->create_item();
  60. for (int i = 0; i < p_nodes.size(); i++) {
  61. List<Connection> all_connections;
  62. p_nodes[i]->get_signals_connected_to_this(&all_connections);
  63. for (const Connection &connection : all_connections) {
  64. if (connection.callable.get_method() != p_method) {
  65. continue;
  66. }
  67. TreeItem *node_item = tree->create_item(root);
  68. node_item->set_text(0, Object::cast_to<Node>(connection.signal.get_object())->get_name());
  69. node_item->set_icon(0, EditorNode::get_singleton()->get_object_icon(connection.signal.get_object()));
  70. node_item->set_selectable(0, false);
  71. node_item->set_editable(0, false);
  72. node_item->set_text(1, connection.signal.get_name());
  73. Control *p = Object::cast_to<Control>(get_parent());
  74. node_item->set_icon(1, p->get_editor_theme_icon(SNAME("Slot")));
  75. node_item->set_selectable(1, false);
  76. node_item->set_editable(1, false);
  77. node_item->set_text(2, Object::cast_to<Node>(connection.callable.get_object())->get_name());
  78. node_item->set_icon(2, EditorNode::get_singleton()->get_object_icon(connection.callable.get_object()));
  79. node_item->set_selectable(2, false);
  80. node_item->set_editable(2, false);
  81. }
  82. }
  83. popup_centered(Size2(600, 300) * EDSCALE);
  84. }
  85. ConnectionInfoDialog::ConnectionInfoDialog() {
  86. set_title(TTRC("Connections to method:"));
  87. VBoxContainer *vbc = memnew(VBoxContainer);
  88. vbc->set_anchor_and_offset(SIDE_LEFT, Control::ANCHOR_BEGIN, 8 * EDSCALE);
  89. vbc->set_anchor_and_offset(SIDE_TOP, Control::ANCHOR_BEGIN, 8 * EDSCALE);
  90. vbc->set_anchor_and_offset(SIDE_RIGHT, Control::ANCHOR_END, -8 * EDSCALE);
  91. vbc->set_anchor_and_offset(SIDE_BOTTOM, Control::ANCHOR_END, -8 * EDSCALE);
  92. add_child(vbc);
  93. method = memnew(Label);
  94. method->set_focus_mode(Control::FOCUS_ACCESSIBILITY);
  95. method->set_auto_translate_mode(AUTO_TRANSLATE_MODE_DISABLED);
  96. method->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_CENTER);
  97. vbc->add_child(method);
  98. tree = memnew(Tree);
  99. tree->set_auto_translate_mode(AUTO_TRANSLATE_MODE_DISABLED);
  100. tree->set_columns(3);
  101. tree->set_hide_root(true);
  102. tree->set_column_titles_visible(true);
  103. tree->set_column_title(0, TTRC("Source"));
  104. tree->set_column_title(1, TTRC("Signal"));
  105. tree->set_column_title(2, TTRC("Target"));
  106. vbc->add_child(tree);
  107. tree->set_v_size_flags(Control::SIZE_EXPAND_FILL);
  108. tree->set_allow_rmb_select(true);
  109. }
  110. ////////////////////////////////////////////////////////////////////////////////
  111. Vector<String> ScriptTextEditor::get_functions() {
  112. CodeEdit *te = code_editor->get_text_editor();
  113. String text = te->get_text();
  114. List<String> fnc;
  115. if (script->get_language()->validate(text, script->get_path(), &fnc)) {
  116. //if valid rewrite functions to latest
  117. functions.clear();
  118. for (const String &E : fnc) {
  119. functions.push_back(E);
  120. }
  121. }
  122. return functions;
  123. }
  124. void ScriptTextEditor::apply_code() {
  125. if (script.is_null()) {
  126. return;
  127. }
  128. script->set_source_code(code_editor->get_text_editor()->get_text());
  129. script->update_exports();
  130. if (!pending_dragged_exports.is_empty()) {
  131. _assign_dragged_export_variables();
  132. }
  133. code_editor->get_text_editor()->get_syntax_highlighter()->update_cache();
  134. }
  135. Ref<Resource> ScriptTextEditor::get_edited_resource() const {
  136. return script;
  137. }
  138. void ScriptTextEditor::set_edited_resource(const Ref<Resource> &p_res) {
  139. ERR_FAIL_COND(script.is_valid());
  140. ERR_FAIL_COND(p_res.is_null());
  141. script = p_res;
  142. code_editor->get_text_editor()->set_text(script->get_source_code());
  143. code_editor->get_text_editor()->clear_undo_history();
  144. code_editor->get_text_editor()->tag_saved_version();
  145. emit_signal(SNAME("name_changed"));
  146. code_editor->update_line_and_column();
  147. }
  148. void ScriptTextEditor::enable_editor(Control *p_shortcut_context) {
  149. if (editor_enabled) {
  150. return;
  151. }
  152. editor_enabled = true;
  153. _enable_code_editor();
  154. _validate_script();
  155. if (pending_state != Variant()) {
  156. code_editor->set_edit_state(pending_state);
  157. pending_state = Variant();
  158. }
  159. if (p_shortcut_context) {
  160. for (int i = 0; i < edit_hb->get_child_count(); ++i) {
  161. Control *c = cast_to<Control>(edit_hb->get_child(i));
  162. if (c) {
  163. c->set_shortcut_context(p_shortcut_context);
  164. }
  165. }
  166. }
  167. }
  168. void ScriptTextEditor::_load_theme_settings() {
  169. CodeEdit *text_edit = code_editor->get_text_editor();
  170. Color updated_warning_line_color = EDITOR_GET("text_editor/theme/highlighting/warning_color");
  171. Color updated_marked_line_color = EDITOR_GET("text_editor/theme/highlighting/mark_color");
  172. Color updated_safe_line_number_color = EDITOR_GET("text_editor/theme/highlighting/safe_line_number_color");
  173. Color updated_folded_code_region_color = EDITOR_GET("text_editor/theme/highlighting/folded_code_region_color");
  174. bool warning_line_color_updated = updated_warning_line_color != warning_line_color;
  175. bool marked_line_color_updated = updated_marked_line_color != marked_line_color;
  176. bool safe_line_number_color_updated = updated_safe_line_number_color != safe_line_number_color;
  177. bool folded_code_region_color_updated = updated_folded_code_region_color != folded_code_region_color;
  178. if (safe_line_number_color_updated || warning_line_color_updated || marked_line_color_updated || folded_code_region_color_updated) {
  179. safe_line_number_color = updated_safe_line_number_color;
  180. for (int i = 0; i < text_edit->get_line_count(); i++) {
  181. if (warning_line_color_updated && text_edit->get_line_background_color(i) == warning_line_color) {
  182. text_edit->set_line_background_color(i, updated_warning_line_color);
  183. }
  184. if (marked_line_color_updated && text_edit->get_line_background_color(i) == marked_line_color) {
  185. text_edit->set_line_background_color(i, updated_marked_line_color);
  186. }
  187. if (safe_line_number_color_updated && text_edit->get_line_gutter_item_color(i, line_number_gutter) != default_line_number_color) {
  188. text_edit->set_line_gutter_item_color(i, line_number_gutter, safe_line_number_color);
  189. }
  190. if (folded_code_region_color_updated && text_edit->get_line_background_color(i) == folded_code_region_color) {
  191. text_edit->set_line_background_color(i, updated_folded_code_region_color);
  192. }
  193. }
  194. warning_line_color = updated_warning_line_color;
  195. marked_line_color = updated_marked_line_color;
  196. folded_code_region_color = updated_folded_code_region_color;
  197. }
  198. theme_loaded = true;
  199. if (script.is_valid()) {
  200. _set_theme_for_script();
  201. }
  202. }
  203. void ScriptTextEditor::_set_theme_for_script() {
  204. if (!theme_loaded) {
  205. return;
  206. }
  207. CodeEdit *text_edit = code_editor->get_text_editor();
  208. text_edit->get_syntax_highlighter()->update_cache();
  209. Vector<String> strings = script->get_language()->get_string_delimiters();
  210. text_edit->clear_string_delimiters();
  211. for (const String &string : strings) {
  212. String beg = string.get_slicec(' ', 0);
  213. String end = string.get_slice_count(" ") > 1 ? string.get_slicec(' ', 1) : String();
  214. if (!text_edit->has_string_delimiter(beg)) {
  215. text_edit->add_string_delimiter(beg, end, end.is_empty());
  216. }
  217. if (!end.is_empty() && !text_edit->has_auto_brace_completion_open_key(beg)) {
  218. text_edit->add_auto_brace_completion_pair(beg, end);
  219. }
  220. }
  221. text_edit->clear_comment_delimiters();
  222. for (const String &comment : script->get_language()->get_comment_delimiters()) {
  223. String beg = comment.get_slicec(' ', 0);
  224. String end = comment.get_slice_count(" ") > 1 ? comment.get_slicec(' ', 1) : String();
  225. text_edit->add_comment_delimiter(beg, end, end.is_empty());
  226. if (!end.is_empty() && !text_edit->has_auto_brace_completion_open_key(beg)) {
  227. text_edit->add_auto_brace_completion_pair(beg, end);
  228. }
  229. }
  230. for (const String &doc_comment : script->get_language()->get_doc_comment_delimiters()) {
  231. String beg = doc_comment.get_slicec(' ', 0);
  232. String end = doc_comment.get_slice_count(" ") > 1 ? doc_comment.get_slicec(' ', 1) : String();
  233. text_edit->add_comment_delimiter(beg, end, end.is_empty());
  234. if (!end.is_empty() && !text_edit->has_auto_brace_completion_open_key(beg)) {
  235. text_edit->add_auto_brace_completion_pair(beg, end);
  236. }
  237. }
  238. }
  239. void ScriptTextEditor::_show_errors_panel(bool p_show) {
  240. errors_panel->set_visible(p_show);
  241. }
  242. void ScriptTextEditor::_show_warnings_panel(bool p_show) {
  243. warnings_panel->set_visible(p_show);
  244. }
  245. void ScriptTextEditor::_warning_clicked(const Variant &p_line) {
  246. if (p_line.get_type() == Variant::INT) {
  247. goto_line_centered(p_line.operator int64_t());
  248. } else if (p_line.get_type() == Variant::DICTIONARY) {
  249. Dictionary meta = p_line.operator Dictionary();
  250. const int line = meta["line"].operator int64_t() - 1;
  251. const String code = meta["code"].operator String();
  252. const String quote_style = EDITOR_GET("text_editor/completion/use_single_quotes") ? "'" : "\"";
  253. CodeEdit *text_editor = code_editor->get_text_editor();
  254. String prev_line = line > 0 ? text_editor->get_line(line - 1) : "";
  255. if (prev_line.contains("@warning_ignore")) {
  256. const int closing_bracket_idx = prev_line.find_char(')');
  257. const String text_to_insert = ", " + code.quote(quote_style);
  258. text_editor->insert_text(text_to_insert, line - 1, closing_bracket_idx);
  259. } else {
  260. const int indent = text_editor->get_indent_level(line) / text_editor->get_indent_size();
  261. String annotation_indent;
  262. if (!text_editor->is_indent_using_spaces()) {
  263. annotation_indent = String("\t").repeat(indent);
  264. } else {
  265. annotation_indent = String(" ").repeat(text_editor->get_indent_size() * indent);
  266. }
  267. text_editor->insert_line_at(line, annotation_indent + "@warning_ignore(" + code.quote(quote_style) + ")");
  268. }
  269. _validate_script();
  270. }
  271. }
  272. void ScriptTextEditor::_error_clicked(const Variant &p_line) {
  273. if (p_line.get_type() == Variant::INT) {
  274. goto_line_centered(p_line.operator int64_t());
  275. } else if (p_line.get_type() == Variant::DICTIONARY) {
  276. Dictionary meta = p_line.operator Dictionary();
  277. const String path = meta["path"].operator String();
  278. const int line = meta["line"].operator int64_t();
  279. const int column = meta["column"].operator int64_t();
  280. if (path.is_empty()) {
  281. goto_line_centered(line, column);
  282. } else {
  283. Ref<Resource> scr = ResourceLoader::load(path);
  284. if (scr.is_null()) {
  285. EditorNode::get_singleton()->show_warning(TTR("Could not load file at:") + "\n\n" + path, TTR("Error!"));
  286. } else {
  287. int corrected_column = column;
  288. const String line_text = code_editor->get_text_editor()->get_line(line);
  289. const int indent_size = code_editor->get_text_editor()->get_indent_size();
  290. if (indent_size > 1) {
  291. const int tab_count = line_text.length() - line_text.lstrip("\t").length();
  292. corrected_column -= tab_count * (indent_size - 1);
  293. }
  294. ScriptEditor::get_singleton()->edit(scr, line, corrected_column);
  295. }
  296. }
  297. }
  298. }
  299. void ScriptTextEditor::reload_text() {
  300. ERR_FAIL_COND(script.is_null());
  301. CodeEdit *te = code_editor->get_text_editor();
  302. int column = te->get_caret_column();
  303. int row = te->get_caret_line();
  304. int h = te->get_h_scroll();
  305. int v = te->get_v_scroll();
  306. te->set_text(script->get_source_code());
  307. te->set_caret_line(row);
  308. te->set_caret_column(column);
  309. te->set_h_scroll(h);
  310. te->set_v_scroll(v);
  311. te->tag_saved_version();
  312. code_editor->update_line_and_column();
  313. if (editor_enabled) {
  314. _validate_script();
  315. }
  316. }
  317. void ScriptTextEditor::add_callback(const String &p_function, const PackedStringArray &p_args) {
  318. ScriptLanguage *language = script->get_language();
  319. if (!language->can_make_function()) {
  320. return;
  321. }
  322. code_editor->get_text_editor()->begin_complex_operation();
  323. code_editor->get_text_editor()->remove_secondary_carets();
  324. code_editor->get_text_editor()->deselect();
  325. String code = code_editor->get_text_editor()->get_text();
  326. int pos = language->find_function(p_function, code);
  327. if (pos == -1) {
  328. // Function does not exist, create it at the end of the file.
  329. int last_line = code_editor->get_text_editor()->get_line_count() - 1;
  330. String func = language->make_function("", p_function, p_args);
  331. code_editor->get_text_editor()->insert_text("\n\n" + func, last_line, code_editor->get_text_editor()->get_line(last_line).length());
  332. pos = last_line + 3;
  333. }
  334. // Put caret on the line after the function, after the indent.
  335. int indent_column = 1;
  336. if (EDITOR_GET("text_editor/behavior/indent/type")) {
  337. indent_column = EDITOR_GET("text_editor/behavior/indent/size");
  338. }
  339. code_editor->get_text_editor()->set_caret_line(pos, true, true, -1);
  340. code_editor->get_text_editor()->set_caret_column(indent_column);
  341. code_editor->get_text_editor()->end_complex_operation();
  342. }
  343. bool ScriptTextEditor::show_members_overview() {
  344. return true;
  345. }
  346. bool ScriptTextEditor::_is_valid_color_info(const Dictionary &p_info) {
  347. if (p_info.get_valid("color").get_type() != Variant::COLOR) {
  348. return false;
  349. }
  350. if (!p_info.get_valid("color_end").is_num() || !p_info.get_valid("color_mode").is_num()) {
  351. return false;
  352. }
  353. return true;
  354. }
  355. Array ScriptTextEditor::_inline_object_parse(const String &p_text) {
  356. Array result;
  357. int i_end_previous = 0;
  358. int i_start = p_text.find("Color");
  359. while (i_start != -1) {
  360. // Ignore words that just have "Color" in them.
  361. if (i_start != 0 && ('_' + p_text.substr(i_start - 1, 1)).is_valid_ascii_identifier()) {
  362. i_end_previous = MAX(i_end_previous, i_start);
  363. i_start = p_text.find("Color", i_start + 1);
  364. continue;
  365. }
  366. const int i_par_start = p_text.find_char('(', i_start + 5);
  367. const int i_par_end = p_text.find_char(')', i_start + 5);
  368. if (i_par_start == -1 || i_par_end == -1) {
  369. i_end_previous = MAX(i_end_previous, i_start);
  370. i_start = p_text.find("Color", i_start + 1);
  371. continue;
  372. }
  373. Dictionary color_info;
  374. color_info["column"] = i_start;
  375. color_info["width_ratio"] = 1.0;
  376. color_info["color_end"] = i_par_end;
  377. const String fn_name = p_text.substr(i_start + 5, i_par_start - i_start - 5);
  378. const String s_params = p_text.substr(i_par_start + 1, i_par_end - i_par_start - 1);
  379. bool has_added_color = false;
  380. if (fn_name.is_empty()) {
  381. String stripped = s_params.strip_edges(true, true);
  382. if (stripped.length() > 1 && (stripped[0] == '"' || stripped[0] == '\'')) {
  383. // String constructor.
  384. const char32_t string_delimiter = stripped[0];
  385. if (stripped[stripped.length() - 1] == string_delimiter) {
  386. const String color_string = stripped.substr(1, stripped.length() - 2);
  387. if (!color_string.contains_char(string_delimiter)) {
  388. color_info["color"] = Color::from_string(color_string, Color());
  389. color_info["color_mode"] = MODE_STRING;
  390. has_added_color = true;
  391. }
  392. }
  393. } else if (stripped.length() == 10 && stripped.begins_with("0x")) {
  394. // Hex constructor.
  395. const String color_string = stripped.substr(2);
  396. if (color_string.is_valid_hex_number(false)) {
  397. color_info["color"] = Color::from_string(color_string, Color());
  398. color_info["color_mode"] = MODE_HEX;
  399. has_added_color = true;
  400. }
  401. } else if (stripped.is_empty()) {
  402. // Empty Color() constructor.
  403. color_info["color"] = Color();
  404. color_info["color_mode"] = MODE_RGB;
  405. has_added_color = true;
  406. }
  407. }
  408. // Float & int parameters.
  409. if (!has_added_color && s_params.size() > 0) {
  410. const PackedStringArray s_params_split = s_params.split(",", false, 4);
  411. PackedFloat64Array params;
  412. bool valid_floats = true;
  413. for (const String &s_param : s_params_split) {
  414. // Only allow float literals, expressions won't be evaluated and could get replaced.
  415. if (!s_param.strip_edges().is_valid_float()) {
  416. valid_floats = false;
  417. break;
  418. }
  419. params.push_back(s_param.to_float());
  420. }
  421. if (valid_floats && params.size() == 3) {
  422. if (fn_name == ".from_rgba8") {
  423. params.push_back(255);
  424. } else {
  425. params.push_back(1.0);
  426. }
  427. }
  428. if (valid_floats && params.size() == 4) {
  429. has_added_color = true;
  430. if (fn_name == ".from_ok_hsl") {
  431. color_info["color"] = Color::from_ok_hsl(params[0], params[1], params[2], params[3]);
  432. color_info["color_mode"] = MODE_OKHSL;
  433. } else if (fn_name == ".from_hsv") {
  434. color_info["color"] = Color::from_hsv(params[0], params[1], params[2], params[3]);
  435. color_info["color_mode"] = MODE_HSV;
  436. } else if (fn_name == ".from_rgba8") {
  437. color_info["color"] = Color::from_rgba8(int(params[0]), int(params[1]), int(params[2]), int(params[3]));
  438. color_info["color_mode"] = MODE_RGB8;
  439. } else if (fn_name.is_empty()) {
  440. color_info["color"] = Color(params[0], params[1], params[2], params[3]);
  441. color_info["color_mode"] = MODE_RGB;
  442. } else {
  443. has_added_color = false;
  444. }
  445. }
  446. }
  447. if (has_added_color) {
  448. result.push_back(color_info);
  449. i_end_previous = i_par_end + 1;
  450. }
  451. i_end_previous = MAX(i_end_previous, i_start);
  452. i_start = p_text.find("Color", i_start + 1);
  453. }
  454. return result;
  455. }
  456. void ScriptTextEditor::_inline_object_draw(const Dictionary &p_info, const Rect2 &p_rect) {
  457. if (_is_valid_color_info(p_info)) {
  458. Rect2 col_rect = p_rect.grow(-4);
  459. if (color_alpha_texture.is_null()) {
  460. color_alpha_texture = inline_color_picker->get_theme_icon("sample_bg", "ColorPicker");
  461. }
  462. RID text_ci = code_editor->get_text_editor()->get_text_canvas_item();
  463. RS::get_singleton()->canvas_item_add_rect(text_ci, p_rect.grow(-3), Color(1, 1, 1));
  464. color_alpha_texture->draw_rect(text_ci, col_rect);
  465. RS::get_singleton()->canvas_item_add_rect(text_ci, col_rect, Color(p_info["color"]));
  466. }
  467. }
  468. void ScriptTextEditor::_inline_object_handle_click(const Dictionary &p_info, const Rect2 &p_rect) {
  469. if (_is_valid_color_info(p_info)) {
  470. inline_color_picker->set_pick_color(p_info["color"]);
  471. inline_color_line = p_info["line"];
  472. inline_color_start = p_info["column"];
  473. inline_color_end = p_info["color_end"];
  474. // Reset tooltip hover timer.
  475. code_editor->get_text_editor()->set_symbol_tooltip_on_hover_enabled(false);
  476. code_editor->get_text_editor()->set_symbol_tooltip_on_hover_enabled(true);
  477. _update_color_constructor_options();
  478. inline_color_options->select(p_info["color_mode"]);
  479. EditorNode::get_singleton()->setup_color_picker(inline_color_picker);
  480. // Move popup above the line if it's too low.
  481. float_t view_h = get_viewport_rect().size.y;
  482. float_t pop_h = inline_color_popup->get_contents_minimum_size().y;
  483. float_t pop_y = p_rect.get_end().y;
  484. float_t pop_x = p_rect.position.x;
  485. if (pop_y + pop_h > view_h) {
  486. pop_y = p_rect.position.y - pop_h;
  487. }
  488. // Move popup to the right if it's too high.
  489. if (pop_y < 0) {
  490. pop_x = p_rect.get_end().x;
  491. }
  492. inline_color_popup->popup(Rect2(pop_x, pop_y, 0, 0));
  493. }
  494. }
  495. String ScriptTextEditor::_picker_color_stringify(const Color &p_color, COLOR_MODE p_mode) {
  496. String result;
  497. String fname;
  498. Vector<String> str_params;
  499. switch (p_mode) {
  500. case ScriptTextEditor::MODE_STRING: {
  501. str_params.push_back("\"" + p_color.to_html() + "\"");
  502. } break;
  503. case ScriptTextEditor::MODE_HEX: {
  504. str_params.push_back("0x" + p_color.to_html());
  505. } break;
  506. case ScriptTextEditor::MODE_RGB: {
  507. str_params = {
  508. String::num(p_color.r, 3),
  509. String::num(p_color.g, 3),
  510. String::num(p_color.b, 3),
  511. String::num(p_color.a, 3)
  512. };
  513. } break;
  514. case ScriptTextEditor::MODE_HSV: {
  515. str_params = {
  516. String::num(p_color.get_h(), 3),
  517. String::num(p_color.get_s(), 3),
  518. String::num(p_color.get_v(), 3),
  519. String::num(p_color.a, 3)
  520. };
  521. fname = ".from_hsv";
  522. } break;
  523. case ScriptTextEditor::MODE_OKHSL: {
  524. str_params = {
  525. String::num(p_color.get_ok_hsl_h(), 3),
  526. String::num(p_color.get_ok_hsl_s(), 3),
  527. String::num(p_color.get_ok_hsl_l(), 3),
  528. String::num(p_color.a, 3)
  529. };
  530. fname = ".from_ok_hsl";
  531. } break;
  532. case ScriptTextEditor::MODE_RGB8: {
  533. str_params = {
  534. itos(p_color.get_r8()),
  535. itos(p_color.get_g8()),
  536. itos(p_color.get_b8()),
  537. itos(p_color.get_a8())
  538. };
  539. fname = ".from_rgba8";
  540. } break;
  541. default: {
  542. } break;
  543. }
  544. result = "Color" + fname + "(" + String(", ").join(str_params) + ")";
  545. return result;
  546. }
  547. void ScriptTextEditor::_picker_color_changed(const Color &p_color) {
  548. _update_color_constructor_options();
  549. _update_color_text();
  550. }
  551. void ScriptTextEditor::_update_color_constructor_options() {
  552. int item_count = inline_color_options->get_item_count();
  553. // Update or add each constructor as an option.
  554. for (int i = 0; i < MODE_MAX; i++) {
  555. String option_text = _picker_color_stringify(inline_color_picker->get_pick_color(), (COLOR_MODE)i);
  556. if (i >= item_count) {
  557. inline_color_options->add_item(option_text);
  558. } else {
  559. inline_color_options->set_item_text(i, option_text);
  560. }
  561. }
  562. }
  563. void ScriptTextEditor::_update_background_color() {
  564. // Clear background lines.
  565. CodeEdit *te = code_editor->get_text_editor();
  566. for (int i = 0; i < te->get_line_count(); i++) {
  567. bool is_folded_code_region = te->is_line_code_region_start(i) && te->is_line_folded(i);
  568. te->set_line_background_color(i, is_folded_code_region ? folded_code_region_color : Color(0, 0, 0, 0));
  569. }
  570. // Set the warning background.
  571. if (warning_line_color.a != 0.0) {
  572. for (const ScriptLanguage::Warning &warning : warnings) {
  573. int warning_start_line = CLAMP(warning.start_line - 1, 0, te->get_line_count() - 1);
  574. int warning_end_line = CLAMP(warning.end_line - 1, 0, te->get_line_count() - 1);
  575. int folded_line_header = te->get_folded_line_header(warning_start_line);
  576. // If the warning highlight is too long, only highlight the start line.
  577. const int warning_max_lines = 20;
  578. te->set_line_background_color(folded_line_header, warning_line_color);
  579. if (warning_end_line - warning_start_line < warning_max_lines) {
  580. for (int i = warning_start_line + 1; i <= warning_end_line; i++) {
  581. te->set_line_background_color(i, warning_line_color);
  582. }
  583. }
  584. }
  585. }
  586. // Set the error background.
  587. if (marked_line_color.a != 0.0) {
  588. for (const ScriptLanguage::ScriptError &error : errors) {
  589. int error_line = CLAMP(error.line - 1, 0, te->get_line_count() - 1);
  590. int folded_line_header = te->get_folded_line_header(error_line);
  591. te->set_line_background_color(folded_line_header, marked_line_color);
  592. }
  593. }
  594. }
  595. void ScriptTextEditor::_update_color_text() {
  596. if (inline_color_line < 0) {
  597. return;
  598. }
  599. String result = inline_color_options->get_item_text(inline_color_options->get_selected_id());
  600. code_editor->get_text_editor()->begin_complex_operation();
  601. code_editor->get_text_editor()->remove_text(inline_color_line, inline_color_start, inline_color_line, inline_color_end + 1);
  602. inline_color_end = inline_color_start + result.size() - 2;
  603. code_editor->get_text_editor()->insert_text(result, inline_color_line, inline_color_start);
  604. code_editor->get_text_editor()->end_complex_operation();
  605. }
  606. void ScriptTextEditor::update_settings() {
  607. code_editor->get_text_editor()->set_gutter_draw(connection_gutter, EDITOR_GET("text_editor/appearance/gutters/show_info_gutter"));
  608. if (EDITOR_GET("text_editor/appearance/enable_inline_color_picker")) {
  609. code_editor->get_text_editor()->set_inline_object_handlers(
  610. callable_mp(this, &ScriptTextEditor::_inline_object_parse),
  611. callable_mp(this, &ScriptTextEditor::_inline_object_draw),
  612. callable_mp(this, &ScriptTextEditor::_inline_object_handle_click));
  613. } else {
  614. code_editor->get_text_editor()->set_inline_object_handlers(Callable(), Callable(), Callable());
  615. }
  616. code_editor->update_editor_settings();
  617. }
  618. bool ScriptTextEditor::is_unsaved() {
  619. const bool unsaved =
  620. code_editor->get_text_editor()->get_version() != code_editor->get_text_editor()->get_saved_version() ||
  621. script->get_path().is_empty(); // In memory.
  622. return unsaved;
  623. }
  624. Variant ScriptTextEditor::get_edit_state() {
  625. if (pending_state != Variant()) {
  626. return pending_state;
  627. }
  628. return code_editor->get_edit_state();
  629. }
  630. void ScriptTextEditor::set_edit_state(const Variant &p_state) {
  631. if (editor_enabled) {
  632. code_editor->set_edit_state(p_state);
  633. } else {
  634. // The editor is not fully initialized, so the state can't be loaded properly.
  635. pending_state = p_state;
  636. }
  637. Dictionary state = p_state;
  638. if (state.has("syntax_highlighter")) {
  639. int idx = highlighter_menu->get_item_idx_from_text(state["syntax_highlighter"]);
  640. if (idx >= 0) {
  641. _change_syntax_highlighter(idx);
  642. }
  643. }
  644. if (editor_enabled) {
  645. #ifndef ANDROID_ENABLED
  646. ensure_focus();
  647. #endif
  648. }
  649. }
  650. Variant ScriptTextEditor::get_navigation_state() {
  651. return code_editor->get_navigation_state();
  652. }
  653. Variant ScriptTextEditor::get_previous_state() {
  654. return code_editor->get_previous_state();
  655. }
  656. void ScriptTextEditor::store_previous_state() {
  657. return code_editor->store_previous_state();
  658. }
  659. void ScriptTextEditor::_convert_case(CodeTextEditor::CaseStyle p_case) {
  660. code_editor->convert_case(p_case);
  661. }
  662. void ScriptTextEditor::trim_trailing_whitespace() {
  663. code_editor->trim_trailing_whitespace();
  664. }
  665. void ScriptTextEditor::trim_final_newlines() {
  666. code_editor->trim_final_newlines();
  667. }
  668. void ScriptTextEditor::insert_final_newline() {
  669. code_editor->insert_final_newline();
  670. }
  671. void ScriptTextEditor::convert_indent() {
  672. code_editor->get_text_editor()->convert_indent();
  673. }
  674. void ScriptTextEditor::tag_saved_version() {
  675. code_editor->get_text_editor()->tag_saved_version();
  676. edited_file_data.last_modified_time = FileAccess::get_modified_time(edited_file_data.path);
  677. }
  678. void ScriptTextEditor::goto_line(int p_line, int p_column) {
  679. code_editor->goto_line(p_line, p_column);
  680. }
  681. void ScriptTextEditor::goto_line_selection(int p_line, int p_begin, int p_end) {
  682. code_editor->goto_line_selection(p_line, p_begin, p_end);
  683. }
  684. void ScriptTextEditor::goto_line_centered(int p_line, int p_column) {
  685. code_editor->goto_line_centered(p_line, p_column);
  686. }
  687. void ScriptTextEditor::set_executing_line(int p_line) {
  688. code_editor->set_executing_line(p_line);
  689. }
  690. void ScriptTextEditor::clear_executing_line() {
  691. code_editor->clear_executing_line();
  692. }
  693. void ScriptTextEditor::ensure_focus() {
  694. code_editor->get_text_editor()->grab_focus();
  695. }
  696. String ScriptTextEditor::get_name() {
  697. String name;
  698. name = script->get_path().get_file();
  699. if (name.is_empty()) {
  700. // This appears for newly created built-in scripts before saving the scene.
  701. name = TTR("[unsaved]");
  702. } else if (script->is_built_in()) {
  703. const String &script_name = script->get_name();
  704. if (!script_name.is_empty()) {
  705. // If the built-in script has a custom resource name defined,
  706. // display the built-in script name as follows: `ResourceName (scene_file.tscn)`
  707. name = vformat("%s (%s)", script_name, name.get_slice("::", 0));
  708. }
  709. }
  710. if (is_unsaved()) {
  711. name += "(*)";
  712. }
  713. return name;
  714. }
  715. Ref<Texture2D> ScriptTextEditor::get_theme_icon() {
  716. if (get_parent_control()) {
  717. String icon_name = script->get_class();
  718. if (script->is_built_in()) {
  719. icon_name += "Internal";
  720. }
  721. if (get_parent_control()->has_theme_icon(icon_name, EditorStringName(EditorIcons))) {
  722. return get_parent_control()->get_editor_theme_icon(icon_name);
  723. } else if (get_parent_control()->has_theme_icon(script->get_class(), EditorStringName(EditorIcons))) {
  724. return get_parent_control()->get_editor_theme_icon(script->get_class());
  725. }
  726. }
  727. Ref<Texture2D> extension_language_icon = EditorNode::get_editor_data().extension_class_get_icon(script->get_class());
  728. Ref<Texture2D> extension_language_alt_icon;
  729. if (script->is_built_in()) {
  730. extension_language_alt_icon = EditorNode::get_editor_data().extension_class_get_icon(script->get_class() + "Internal");
  731. }
  732. if (extension_language_alt_icon.is_valid()) {
  733. return extension_language_alt_icon;
  734. } else if (extension_language_icon.is_valid()) {
  735. return extension_language_icon;
  736. }
  737. return Ref<Texture2D>();
  738. }
  739. void ScriptTextEditor::_validate_script() {
  740. CodeEdit *te = code_editor->get_text_editor();
  741. String text = te->get_text();
  742. List<String> fnc;
  743. warnings.clear();
  744. errors.clear();
  745. depended_errors.clear();
  746. safe_lines.clear();
  747. if (!script->get_language()->validate(text, script->get_path(), &fnc, &errors, &warnings, &safe_lines)) {
  748. List<ScriptLanguage::ScriptError>::Element *E = errors.front();
  749. while (E) {
  750. List<ScriptLanguage::ScriptError>::Element *next_E = E->next();
  751. if ((E->get().path.is_empty() && !script->get_path().is_empty()) || E->get().path != script->get_path()) {
  752. depended_errors[E->get().path].push_back(E->get());
  753. E->erase();
  754. }
  755. E = next_E;
  756. }
  757. if (errors.size() > 0) {
  758. const int line = errors.front()->get().line;
  759. const int column = errors.front()->get().column;
  760. const String message = errors.front()->get().message.replace("[", "[lb]");
  761. const String error_text = vformat(TTR("Error at ([hint=Line %d, column %d]%d, %d[/hint]):"), line, column, line, column) + " " + message;
  762. code_editor->set_error(error_text);
  763. code_editor->set_error_pos(line - 1, column - 1);
  764. }
  765. script_is_valid = false;
  766. } else {
  767. code_editor->set_error("");
  768. if (!script->is_tool()) {
  769. script->set_source_code(text);
  770. script->update_exports();
  771. te->get_syntax_highlighter()->update_cache();
  772. }
  773. functions.clear();
  774. for (const String &E : fnc) {
  775. functions.push_back(E);
  776. }
  777. script_is_valid = true;
  778. }
  779. _update_connected_methods();
  780. _update_warnings();
  781. _update_errors();
  782. _update_background_color();
  783. if (!pending_dragged_exports.is_empty()) {
  784. _assign_dragged_export_variables();
  785. }
  786. emit_signal(SNAME("name_changed"));
  787. emit_signal(SNAME("edited_script_changed"));
  788. }
  789. void ScriptTextEditor::_update_warnings() {
  790. int warning_nb = warnings.size();
  791. warnings_panel->clear();
  792. bool has_connections_table = false;
  793. // Add missing connections.
  794. if (GLOBAL_GET("debug/gdscript/warnings/enable")) {
  795. Node *base = get_tree()->get_edited_scene_root();
  796. if (base && missing_connections.size() > 0) {
  797. has_connections_table = true;
  798. warnings_panel->push_table(1);
  799. for (const Connection &connection : missing_connections) {
  800. String base_path = base->get_name();
  801. String source_path = base == connection.signal.get_object() ? base_path : base_path + "/" + String(base->get_path_to(Object::cast_to<Node>(connection.signal.get_object())));
  802. String target_path = base == connection.callable.get_object() ? base_path : base_path + "/" + String(base->get_path_to(Object::cast_to<Node>(connection.callable.get_object())));
  803. warnings_panel->push_cell();
  804. warnings_panel->push_color(warnings_panel->get_theme_color(SNAME("warning_color"), EditorStringName(Editor)));
  805. warnings_panel->add_text(vformat(TTR("Missing connected method '%s' for signal '%s' from node '%s' to node '%s'."), connection.callable.get_method(), connection.signal.get_name(), source_path, target_path));
  806. warnings_panel->pop(); // Color.
  807. warnings_panel->pop(); // Cell.
  808. }
  809. warnings_panel->pop(); // Table.
  810. warning_nb += missing_connections.size();
  811. }
  812. }
  813. code_editor->set_warning_count(warning_nb);
  814. if (has_connections_table) {
  815. warnings_panel->add_newline();
  816. }
  817. // Add script warnings.
  818. warnings_panel->push_table(3);
  819. for (const ScriptLanguage::Warning &w : warnings) {
  820. Dictionary ignore_meta;
  821. ignore_meta["line"] = w.start_line;
  822. ignore_meta["code"] = w.string_code.to_lower();
  823. warnings_panel->push_cell();
  824. warnings_panel->push_meta(ignore_meta);
  825. warnings_panel->push_color(
  826. warnings_panel->get_theme_color(SNAME("accent_color"), EditorStringName(Editor)).lerp(warnings_panel->get_theme_color(SNAME("mono_color"), EditorStringName(Editor)), 0.5f));
  827. warnings_panel->add_text(TTR("[Ignore]"));
  828. warnings_panel->pop(); // Color.
  829. warnings_panel->pop(); // Meta ignore.
  830. warnings_panel->pop(); // Cell.
  831. warnings_panel->push_cell();
  832. warnings_panel->push_meta(w.start_line - 1);
  833. warnings_panel->push_color(warnings_panel->get_theme_color(SNAME("warning_color"), EditorStringName(Editor)));
  834. warnings_panel->add_text(vformat(TTR("Line %d (%s):"), w.start_line, w.string_code));
  835. warnings_panel->pop(); // Color.
  836. warnings_panel->pop(); // Meta goto.
  837. warnings_panel->pop(); // Cell.
  838. warnings_panel->push_cell();
  839. warnings_panel->add_text(w.message);
  840. warnings_panel->add_newline();
  841. warnings_panel->pop(); // Cell.
  842. }
  843. warnings_panel->pop(); // Table.
  844. }
  845. void ScriptTextEditor::_update_errors() {
  846. code_editor->set_error_count(errors.size());
  847. errors_panel->clear();
  848. errors_panel->push_table(2);
  849. for (const ScriptLanguage::ScriptError &err : errors) {
  850. Dictionary click_meta;
  851. click_meta["line"] = err.line;
  852. click_meta["column"] = err.column;
  853. errors_panel->push_cell();
  854. errors_panel->push_meta(err.line - 1);
  855. errors_panel->push_color(warnings_panel->get_theme_color(SNAME("error_color"), EditorStringName(Editor)));
  856. errors_panel->add_text(vformat(TTR("Line %d:"), err.line));
  857. errors_panel->pop(); // Color.
  858. errors_panel->pop(); // Meta goto.
  859. errors_panel->pop(); // Cell.
  860. errors_panel->push_cell();
  861. errors_panel->add_text(err.message);
  862. errors_panel->add_newline();
  863. errors_panel->pop(); // Cell.
  864. }
  865. errors_panel->pop(); // Table
  866. for (const KeyValue<String, List<ScriptLanguage::ScriptError>> &KV : depended_errors) {
  867. Dictionary click_meta;
  868. click_meta["path"] = KV.key;
  869. click_meta["line"] = 1;
  870. errors_panel->add_newline();
  871. errors_panel->add_newline();
  872. errors_panel->push_meta(click_meta);
  873. errors_panel->add_text(vformat(R"(%s:)", KV.key));
  874. errors_panel->pop(); // Meta goto.
  875. errors_panel->add_newline();
  876. errors_panel->push_indent(1);
  877. errors_panel->push_table(2);
  878. String filename = KV.key.get_file();
  879. for (const ScriptLanguage::ScriptError &err : KV.value) {
  880. click_meta["line"] = err.line;
  881. click_meta["column"] = err.column;
  882. errors_panel->push_cell();
  883. errors_panel->push_meta(click_meta);
  884. errors_panel->push_color(errors_panel->get_theme_color(SNAME("error_color"), EditorStringName(Editor)));
  885. errors_panel->add_text(vformat(TTR("Line %d:"), err.line));
  886. errors_panel->pop(); // Color.
  887. errors_panel->pop(); // Meta goto.
  888. errors_panel->pop(); // Cell.
  889. errors_panel->push_cell();
  890. errors_panel->add_text(err.message);
  891. errors_panel->pop(); // Cell.
  892. }
  893. errors_panel->pop(); // Table
  894. errors_panel->pop(); // Indent.
  895. }
  896. bool highlight_safe = EDITOR_GET("text_editor/appearance/gutters/highlight_type_safe_lines");
  897. bool last_is_safe = false;
  898. CodeEdit *te = code_editor->get_text_editor();
  899. for (int i = 0; i < te->get_line_count(); i++) {
  900. if (highlight_safe) {
  901. if (safe_lines.has(i + 1)) {
  902. te->set_line_gutter_item_color(i, line_number_gutter, safe_line_number_color);
  903. last_is_safe = true;
  904. } else if (last_is_safe && (te->is_in_comment(i) != -1 || te->get_line(i).strip_edges().is_empty())) {
  905. te->set_line_gutter_item_color(i, line_number_gutter, safe_line_number_color);
  906. } else {
  907. te->set_line_gutter_item_color(i, line_number_gutter, default_line_number_color);
  908. last_is_safe = false;
  909. }
  910. } else {
  911. te->set_line_gutter_item_color(i, 1, default_line_number_color);
  912. }
  913. }
  914. }
  915. void ScriptTextEditor::_update_bookmark_list() {
  916. bookmarks_menu->clear();
  917. bookmarks_menu->reset_size();
  918. bookmarks_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/toggle_bookmark"), BOOKMARK_TOGGLE);
  919. bookmarks_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/remove_all_bookmarks"), BOOKMARK_REMOVE_ALL);
  920. bookmarks_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/goto_next_bookmark"), BOOKMARK_GOTO_NEXT);
  921. bookmarks_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/goto_previous_bookmark"), BOOKMARK_GOTO_PREV);
  922. PackedInt32Array bookmark_list = code_editor->get_text_editor()->get_bookmarked_lines();
  923. if (bookmark_list.is_empty()) {
  924. return;
  925. }
  926. bookmarks_menu->add_separator();
  927. for (int i = 0; i < bookmark_list.size(); i++) {
  928. // Strip edges to remove spaces or tabs.
  929. // Also replace any tabs by spaces, since we can't print tabs in the menu.
  930. String line = code_editor->get_text_editor()->get_line(bookmark_list[i]).replace("\t", " ").strip_edges();
  931. // Limit the size of the line if too big.
  932. if (line.length() > 50) {
  933. line = line.substr(0, 50);
  934. }
  935. bookmarks_menu->add_item(String::num_int64(bookmark_list[i] + 1) + " - `" + line + "`");
  936. bookmarks_menu->set_item_metadata(-1, bookmark_list[i]);
  937. }
  938. }
  939. void ScriptTextEditor::_bookmark_item_pressed(int p_idx) {
  940. if (p_idx < 4) { // Any item before the separator.
  941. _edit_option(bookmarks_menu->get_item_id(p_idx));
  942. } else {
  943. code_editor->goto_line_centered(bookmarks_menu->get_item_metadata(p_idx));
  944. }
  945. }
  946. static Vector<Node *> _find_all_node_for_script(Node *p_base, Node *p_current, const Ref<Script> &p_script) {
  947. Vector<Node *> nodes;
  948. if (p_current->get_owner() != p_base && p_base != p_current) {
  949. return nodes;
  950. }
  951. Ref<Script> c = p_current->get_script();
  952. if (c == p_script) {
  953. nodes.push_back(p_current);
  954. }
  955. for (int i = 0; i < p_current->get_child_count(); i++) {
  956. Vector<Node *> found = _find_all_node_for_script(p_base, p_current->get_child(i), p_script);
  957. nodes.append_array(found);
  958. }
  959. return nodes;
  960. }
  961. static Node *_find_node_for_script(Node *p_base, Node *p_current, const Ref<Script> &p_script) {
  962. if (p_current->get_owner() != p_base && p_base != p_current) {
  963. return nullptr;
  964. }
  965. Ref<Script> c = p_current->get_script();
  966. if (c == p_script) {
  967. return p_current;
  968. }
  969. for (int i = 0; i < p_current->get_child_count(); i++) {
  970. Node *found = _find_node_for_script(p_base, p_current->get_child(i), p_script);
  971. if (found) {
  972. return found;
  973. }
  974. }
  975. return nullptr;
  976. }
  977. static void _find_changed_scripts_for_external_editor(Node *p_base, Node *p_current, HashSet<Ref<Script>> &r_scripts) {
  978. if (p_current->get_owner() != p_base && p_base != p_current) {
  979. return;
  980. }
  981. Ref<Script> c = p_current->get_script();
  982. if (c.is_valid()) {
  983. r_scripts.insert(c);
  984. }
  985. for (int i = 0; i < p_current->get_child_count(); i++) {
  986. _find_changed_scripts_for_external_editor(p_base, p_current->get_child(i), r_scripts);
  987. }
  988. }
  989. void ScriptEditor::_update_modified_scripts_for_external_editor(Ref<Script> p_for_script) {
  990. bool use_external_editor = bool(EDITOR_GET("text_editor/external/use_external_editor"));
  991. ERR_FAIL_NULL(get_tree());
  992. HashSet<Ref<Script>> scripts;
  993. Node *base = get_tree()->get_edited_scene_root();
  994. if (base) {
  995. _find_changed_scripts_for_external_editor(base, base, scripts);
  996. }
  997. for (const Ref<Script> &E : scripts) {
  998. Ref<Script> scr = E;
  999. if (!use_external_editor && !scr->get_language()->overrides_external_editor()) {
  1000. continue; // We're not using an external editor for this script.
  1001. }
  1002. if (p_for_script.is_valid() && p_for_script != scr) {
  1003. continue;
  1004. }
  1005. if (scr->is_built_in()) {
  1006. continue; //internal script, who cares, though weird
  1007. }
  1008. uint64_t last_date = scr->get_last_modified_time();
  1009. uint64_t date = FileAccess::get_modified_time(scr->get_path());
  1010. if (last_date != date) {
  1011. Ref<Script> rel_scr = ResourceLoader::load(scr->get_path(), scr->get_class(), ResourceFormatLoader::CACHE_MODE_IGNORE);
  1012. ERR_CONTINUE(rel_scr.is_null());
  1013. scr->set_source_code(rel_scr->get_source_code());
  1014. scr->set_last_modified_time(rel_scr->get_last_modified_time());
  1015. scr->update_exports();
  1016. trigger_live_script_reload(scr->get_path());
  1017. }
  1018. }
  1019. }
  1020. void ScriptTextEditor::_code_complete_scripts(void *p_ud, const String &p_code, List<ScriptLanguage::CodeCompletionOption> *r_options, bool &r_force) {
  1021. ScriptTextEditor *ste = (ScriptTextEditor *)p_ud;
  1022. ste->_code_complete_script(p_code, r_options, r_force);
  1023. }
  1024. void ScriptTextEditor::_code_complete_script(const String &p_code, List<ScriptLanguage::CodeCompletionOption> *r_options, bool &r_force) {
  1025. if (color_panel->is_visible()) {
  1026. return;
  1027. }
  1028. Node *base = get_tree()->get_edited_scene_root();
  1029. if (base) {
  1030. base = _find_node_for_script(base, base, script);
  1031. }
  1032. String hint;
  1033. Error err = script->get_language()->complete_code(p_code, script->get_path(), base, r_options, r_force, hint);
  1034. if (err == OK) {
  1035. code_editor->get_text_editor()->set_code_hint(hint);
  1036. }
  1037. }
  1038. void ScriptTextEditor::_update_breakpoint_list() {
  1039. breakpoints_menu->clear();
  1040. breakpoints_menu->reset_size();
  1041. breakpoints_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/toggle_breakpoint"), DEBUG_TOGGLE_BREAKPOINT);
  1042. breakpoints_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/remove_all_breakpoints"), DEBUG_REMOVE_ALL_BREAKPOINTS);
  1043. breakpoints_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/goto_next_breakpoint"), DEBUG_GOTO_NEXT_BREAKPOINT);
  1044. breakpoints_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/goto_previous_breakpoint"), DEBUG_GOTO_PREV_BREAKPOINT);
  1045. PackedInt32Array breakpoint_list = code_editor->get_text_editor()->get_breakpointed_lines();
  1046. if (breakpoint_list.is_empty()) {
  1047. return;
  1048. }
  1049. breakpoints_menu->add_separator();
  1050. for (int i = 0; i < breakpoint_list.size(); i++) {
  1051. // Strip edges to remove spaces or tabs.
  1052. // Also replace any tabs by spaces, since we can't print tabs in the menu.
  1053. String line = code_editor->get_text_editor()->get_line(breakpoint_list[i]).replace("\t", " ").strip_edges();
  1054. // Limit the size of the line if too big.
  1055. if (line.length() > 50) {
  1056. line = line.substr(0, 50);
  1057. }
  1058. breakpoints_menu->add_item(String::num_int64(breakpoint_list[i] + 1) + " - `" + line + "`");
  1059. breakpoints_menu->set_item_metadata(-1, breakpoint_list[i]);
  1060. }
  1061. }
  1062. void ScriptTextEditor::_breakpoint_item_pressed(int p_idx) {
  1063. if (p_idx < 4) { // Any item before the separator.
  1064. _edit_option(breakpoints_menu->get_item_id(p_idx));
  1065. } else {
  1066. code_editor->goto_line_centered(breakpoints_menu->get_item_metadata(p_idx));
  1067. }
  1068. }
  1069. void ScriptTextEditor::_breakpoint_toggled(int p_row) {
  1070. const CodeEdit *ce = code_editor->get_text_editor();
  1071. bool enabled = p_row < ce->get_line_count() && ce->is_line_breakpointed(p_row);
  1072. EditorDebuggerNode::get_singleton()->set_breakpoint(script->get_path(), p_row + 1, enabled);
  1073. }
  1074. void ScriptTextEditor::_on_caret_moved() {
  1075. if (code_editor->is_previewing_navigation_change()) {
  1076. return;
  1077. }
  1078. int current_line = code_editor->get_text_editor()->get_caret_line();
  1079. if (Math::abs(current_line - previous_line) >= 10) {
  1080. Dictionary nav_state = get_navigation_state();
  1081. nav_state["row"] = previous_line;
  1082. nav_state["scroll_position"] = -1;
  1083. emit_signal(SNAME("request_save_previous_state"), nav_state);
  1084. store_previous_state();
  1085. }
  1086. previous_line = current_line;
  1087. }
  1088. void ScriptTextEditor::_lookup_symbol(const String &p_symbol, int p_row, int p_column) {
  1089. Node *base = get_tree()->get_edited_scene_root();
  1090. if (base) {
  1091. base = _find_node_for_script(base, base, script);
  1092. }
  1093. ScriptLanguage::LookupResult result;
  1094. String code_text = code_editor->get_text_editor()->get_text_with_cursor_char(p_row, p_column);
  1095. Error lc_error = script->get_language()->lookup_code(code_text, p_symbol, script->get_path(), base, result);
  1096. if (ScriptServer::is_global_class(p_symbol)) {
  1097. EditorNode::get_singleton()->load_resource(ScriptServer::get_global_class_path(p_symbol));
  1098. } else if (p_symbol.is_resource_file() || p_symbol.begins_with("uid://")) {
  1099. if (DirAccess::dir_exists_absolute(p_symbol)) {
  1100. FileSystemDock::get_singleton()->navigate_to_path(p_symbol);
  1101. } else {
  1102. EditorNode::get_singleton()->load_scene_or_resource(p_symbol);
  1103. }
  1104. } else if (lc_error == OK) {
  1105. _goto_line(p_row);
  1106. if (!result.class_name.is_empty() && EditorHelp::get_doc_data()->class_list.has(result.class_name) && !EditorHelp::get_doc_data()->class_list[result.class_name].is_script_doc) {
  1107. switch (result.type) {
  1108. case ScriptLanguage::LOOKUP_RESULT_CLASS: {
  1109. emit_signal(SNAME("go_to_help"), "class_name:" + result.class_name);
  1110. } break;
  1111. case ScriptLanguage::LOOKUP_RESULT_CLASS_CONSTANT: {
  1112. StringName cname = result.class_name;
  1113. while (ClassDB::class_exists(cname)) {
  1114. if (ClassDB::has_integer_constant(cname, result.class_member, true)) {
  1115. result.class_name = cname;
  1116. break;
  1117. }
  1118. cname = ClassDB::get_parent_class(cname);
  1119. }
  1120. emit_signal(SNAME("go_to_help"), "class_constant:" + result.class_name + ":" + result.class_member);
  1121. } break;
  1122. case ScriptLanguage::LOOKUP_RESULT_CLASS_PROPERTY: {
  1123. StringName cname = result.class_name;
  1124. while (ClassDB::class_exists(cname)) {
  1125. if (ClassDB::has_property(cname, result.class_member, true)) {
  1126. result.class_name = cname;
  1127. break;
  1128. }
  1129. cname = ClassDB::get_parent_class(cname);
  1130. }
  1131. emit_signal(SNAME("go_to_help"), "class_property:" + result.class_name + ":" + result.class_member);
  1132. } break;
  1133. case ScriptLanguage::LOOKUP_RESULT_CLASS_METHOD: {
  1134. StringName cname = result.class_name;
  1135. while (ClassDB::class_exists(cname)) {
  1136. if (ClassDB::has_method(cname, result.class_member, true)) {
  1137. result.class_name = cname;
  1138. break;
  1139. }
  1140. cname = ClassDB::get_parent_class(cname);
  1141. }
  1142. emit_signal(SNAME("go_to_help"), "class_method:" + result.class_name + ":" + result.class_member);
  1143. } break;
  1144. case ScriptLanguage::LOOKUP_RESULT_CLASS_SIGNAL: {
  1145. StringName cname = result.class_name;
  1146. while (ClassDB::class_exists(cname)) {
  1147. if (ClassDB::has_signal(cname, result.class_member, true)) {
  1148. result.class_name = cname;
  1149. break;
  1150. }
  1151. cname = ClassDB::get_parent_class(cname);
  1152. }
  1153. emit_signal(SNAME("go_to_help"), "class_signal:" + result.class_name + ":" + result.class_member);
  1154. } break;
  1155. case ScriptLanguage::LOOKUP_RESULT_CLASS_ENUM: {
  1156. StringName cname = result.class_name;
  1157. while (ClassDB::class_exists(cname)) {
  1158. if (ClassDB::has_enum(cname, result.class_member, true)) {
  1159. result.class_name = cname;
  1160. break;
  1161. }
  1162. cname = ClassDB::get_parent_class(cname);
  1163. }
  1164. emit_signal(SNAME("go_to_help"), "class_enum:" + result.class_name + ":" + result.class_member);
  1165. } break;
  1166. case ScriptLanguage::LOOKUP_RESULT_CLASS_ANNOTATION: {
  1167. emit_signal(SNAME("go_to_help"), "class_annotation:" + result.class_name + ":" + result.class_member);
  1168. } break;
  1169. case ScriptLanguage::LOOKUP_RESULT_CLASS_TBD_GLOBALSCOPE: { // Deprecated.
  1170. emit_signal(SNAME("go_to_help"), "class_global:" + result.class_name + ":" + result.class_member);
  1171. } break;
  1172. case ScriptLanguage::LOOKUP_RESULT_SCRIPT_LOCATION:
  1173. case ScriptLanguage::LOOKUP_RESULT_LOCAL_CONSTANT:
  1174. case ScriptLanguage::LOOKUP_RESULT_LOCAL_VARIABLE:
  1175. case ScriptLanguage::LOOKUP_RESULT_MAX: {
  1176. // Nothing to do.
  1177. } break;
  1178. }
  1179. } else if (result.location >= 0) {
  1180. if (result.script.is_valid()) {
  1181. emit_signal(SNAME("request_open_script_at_line"), result.script, result.location - 1);
  1182. } else {
  1183. emit_signal(SNAME("request_save_history"));
  1184. goto_line_centered(result.location - 1);
  1185. }
  1186. }
  1187. } else if (ProjectSettings::get_singleton()->has_autoload(p_symbol)) {
  1188. // Check for Autoload scenes.
  1189. const ProjectSettings::AutoloadInfo &info = ProjectSettings::get_singleton()->get_autoload(p_symbol);
  1190. if (info.is_singleton) {
  1191. EditorNode::get_singleton()->load_scene(info.path);
  1192. }
  1193. } else if (p_symbol.is_relative_path()) {
  1194. // Every symbol other than absolute path is relative path so keep this condition at last.
  1195. String path = _get_absolute_path(p_symbol);
  1196. if (FileAccess::exists(path)) {
  1197. EditorNode::get_singleton()->load_scene_or_resource(path);
  1198. }
  1199. }
  1200. }
  1201. void ScriptTextEditor::_validate_symbol(const String &p_symbol) {
  1202. CodeEdit *text_edit = code_editor->get_text_editor();
  1203. Node *base = get_tree()->get_edited_scene_root();
  1204. if (base) {
  1205. base = _find_node_for_script(base, base, script);
  1206. }
  1207. ScriptLanguage::LookupResult result;
  1208. String lc_text = code_editor->get_text_editor()->get_text_for_symbol_lookup();
  1209. Error lc_error = script->get_language()->lookup_code(lc_text, p_symbol, script->get_path(), base, result);
  1210. bool is_singleton = ProjectSettings::get_singleton()->has_autoload(p_symbol) && ProjectSettings::get_singleton()->get_autoload(p_symbol).is_singleton;
  1211. if (lc_error == OK || is_singleton || ScriptServer::is_global_class(p_symbol) || p_symbol.is_resource_file() || p_symbol.begins_with("uid://")) {
  1212. text_edit->set_symbol_lookup_word_as_valid(true);
  1213. } else if (p_symbol.is_relative_path()) {
  1214. String path = _get_absolute_path(p_symbol);
  1215. if (FileAccess::exists(path)) {
  1216. text_edit->set_symbol_lookup_word_as_valid(true);
  1217. } else {
  1218. text_edit->set_symbol_lookup_word_as_valid(false);
  1219. }
  1220. } else {
  1221. text_edit->set_symbol_lookup_word_as_valid(false);
  1222. }
  1223. }
  1224. void ScriptTextEditor::_show_symbol_tooltip(const String &p_symbol, int p_row, int p_column) {
  1225. if (!EDITOR_GET("text_editor/behavior/documentation/enable_tooltips").booleanize()) {
  1226. return;
  1227. }
  1228. if (p_symbol.begins_with("res://") || p_symbol.begins_with("uid://")) {
  1229. EditorHelpBitTooltip::show_tooltip(code_editor->get_text_editor(), "resource||" + p_symbol);
  1230. return;
  1231. }
  1232. Node *base = get_tree()->get_edited_scene_root();
  1233. if (base) {
  1234. base = _find_node_for_script(base, base, script);
  1235. }
  1236. ScriptLanguage::LookupResult result;
  1237. String doc_symbol;
  1238. const String code_text = code_editor->get_text_editor()->get_text_with_cursor_char(p_row, p_column);
  1239. const Error lc_error = script->get_language()->lookup_code(code_text, p_symbol, script->get_path(), base, result);
  1240. if (lc_error == OK) {
  1241. switch (result.type) {
  1242. case ScriptLanguage::LOOKUP_RESULT_CLASS: {
  1243. doc_symbol = "class|" + result.class_name + "|";
  1244. } break;
  1245. case ScriptLanguage::LOOKUP_RESULT_CLASS_CONSTANT: {
  1246. StringName cname = result.class_name;
  1247. while (ClassDB::class_exists(cname)) {
  1248. if (ClassDB::has_integer_constant(cname, result.class_member, true)) {
  1249. result.class_name = cname;
  1250. break;
  1251. }
  1252. cname = ClassDB::get_parent_class(cname);
  1253. }
  1254. doc_symbol = "constant|" + result.class_name + "|" + result.class_member;
  1255. } break;
  1256. case ScriptLanguage::LOOKUP_RESULT_CLASS_PROPERTY: {
  1257. StringName cname = result.class_name;
  1258. while (ClassDB::class_exists(cname)) {
  1259. if (ClassDB::has_property(cname, result.class_member, true)) {
  1260. result.class_name = cname;
  1261. break;
  1262. }
  1263. cname = ClassDB::get_parent_class(cname);
  1264. }
  1265. doc_symbol = "property|" + result.class_name + "|" + result.class_member;
  1266. } break;
  1267. case ScriptLanguage::LOOKUP_RESULT_CLASS_METHOD: {
  1268. StringName cname = result.class_name;
  1269. while (ClassDB::class_exists(cname)) {
  1270. if (ClassDB::has_method(cname, result.class_member, true)) {
  1271. result.class_name = cname;
  1272. break;
  1273. }
  1274. cname = ClassDB::get_parent_class(cname);
  1275. }
  1276. doc_symbol = "method|" + result.class_name + "|" + result.class_member;
  1277. } break;
  1278. case ScriptLanguage::LOOKUP_RESULT_CLASS_SIGNAL: {
  1279. StringName cname = result.class_name;
  1280. while (ClassDB::class_exists(cname)) {
  1281. if (ClassDB::has_signal(cname, result.class_member, true)) {
  1282. result.class_name = cname;
  1283. break;
  1284. }
  1285. cname = ClassDB::get_parent_class(cname);
  1286. }
  1287. doc_symbol = "signal|" + result.class_name + "|" + result.class_member;
  1288. } break;
  1289. case ScriptLanguage::LOOKUP_RESULT_CLASS_ENUM: {
  1290. StringName cname = result.class_name;
  1291. while (ClassDB::class_exists(cname)) {
  1292. if (ClassDB::has_enum(cname, result.class_member, true)) {
  1293. result.class_name = cname;
  1294. break;
  1295. }
  1296. cname = ClassDB::get_parent_class(cname);
  1297. }
  1298. doc_symbol = "enum|" + result.class_name + "|" + result.class_member;
  1299. } break;
  1300. case ScriptLanguage::LOOKUP_RESULT_CLASS_ANNOTATION: {
  1301. doc_symbol = "annotation|" + result.class_name + "|" + result.class_member;
  1302. } break;
  1303. case ScriptLanguage::LOOKUP_RESULT_LOCAL_CONSTANT:
  1304. case ScriptLanguage::LOOKUP_RESULT_LOCAL_VARIABLE: {
  1305. const String item_type = (result.type == ScriptLanguage::LOOKUP_RESULT_LOCAL_CONSTANT) ? "local_constant" : "local_variable";
  1306. Dictionary item_data;
  1307. item_data["description"] = result.description;
  1308. item_data["is_deprecated"] = result.is_deprecated;
  1309. item_data["deprecated_message"] = result.deprecated_message;
  1310. item_data["is_experimental"] = result.is_experimental;
  1311. item_data["experimental_message"] = result.experimental_message;
  1312. item_data["doc_type"] = result.doc_type;
  1313. item_data["enumeration"] = result.enumeration;
  1314. item_data["is_bitfield"] = result.is_bitfield;
  1315. item_data["value"] = result.value;
  1316. doc_symbol = item_type + "||" + p_symbol + "|" + JSON::stringify(item_data);
  1317. } break;
  1318. case ScriptLanguage::LOOKUP_RESULT_SCRIPT_LOCATION:
  1319. case ScriptLanguage::LOOKUP_RESULT_CLASS_TBD_GLOBALSCOPE: // Deprecated.
  1320. case ScriptLanguage::LOOKUP_RESULT_MAX: {
  1321. // Nothing to do.
  1322. } break;
  1323. }
  1324. }
  1325. // NOTE: See also `ScriptEditor::_get_debug_tooltip()` for documentation tooltips disabled.
  1326. String debug_value = EditorDebuggerNode::get_singleton()->get_var_value(p_symbol);
  1327. if (!debug_value.is_empty()) {
  1328. constexpr int DISPLAY_LIMIT = 1024;
  1329. if (debug_value.size() > DISPLAY_LIMIT) {
  1330. debug_value = debug_value.left(DISPLAY_LIMIT) + "... " + TTR("(truncated)");
  1331. }
  1332. debug_value = TTR("Current value: ") + debug_value.replace("[", "[lb]");
  1333. }
  1334. if (!doc_symbol.is_empty() || !debug_value.is_empty()) {
  1335. EditorHelpBitTooltip::show_tooltip(code_editor->get_text_editor(), doc_symbol, debug_value, true);
  1336. }
  1337. }
  1338. String ScriptTextEditor::_get_absolute_path(const String &rel_path) {
  1339. String base_path = script->get_path().get_base_dir();
  1340. String path = base_path.path_join(rel_path);
  1341. return path.replace("///", "//").simplify_path();
  1342. }
  1343. void ScriptTextEditor::update_toggle_files_button() {
  1344. code_editor->update_toggle_files_button();
  1345. }
  1346. void ScriptTextEditor::_update_connected_methods() {
  1347. CodeEdit *text_edit = code_editor->get_text_editor();
  1348. text_edit->set_gutter_width(connection_gutter, text_edit->get_line_height());
  1349. for (int i = 0; i < text_edit->get_line_count(); i++) {
  1350. text_edit->set_line_gutter_metadata(i, connection_gutter, Dictionary());
  1351. text_edit->set_line_gutter_icon(i, connection_gutter, nullptr);
  1352. text_edit->set_line_gutter_clickable(i, connection_gutter, false);
  1353. }
  1354. missing_connections.clear();
  1355. if (!script_is_valid) {
  1356. return;
  1357. }
  1358. Node *base = get_tree()->get_edited_scene_root();
  1359. if (!base) {
  1360. return;
  1361. }
  1362. // Add connection icons to methods.
  1363. Vector<Node *> nodes = _find_all_node_for_script(base, base, script);
  1364. HashSet<StringName> methods_found;
  1365. for (int i = 0; i < nodes.size(); i++) {
  1366. List<Connection> signal_connections;
  1367. nodes[i]->get_signals_connected_to_this(&signal_connections);
  1368. for (const Connection &connection : signal_connections) {
  1369. if (!(connection.flags & CONNECT_PERSIST)) {
  1370. continue;
  1371. }
  1372. // As deleted nodes are still accessible via the undo/redo system, check if they're still on the tree.
  1373. Node *source = Object::cast_to<Node>(connection.signal.get_object());
  1374. if (source && !source->is_inside_tree()) {
  1375. continue;
  1376. }
  1377. const StringName method = connection.callable.get_method();
  1378. if (methods_found.has(method)) {
  1379. continue;
  1380. }
  1381. if (!ClassDB::has_method(script->get_instance_base_type(), method)) {
  1382. int line = -1;
  1383. for (int j = 0; j < functions.size(); j++) {
  1384. String name = functions[j].get_slicec(':', 0);
  1385. if (name == method) {
  1386. Dictionary line_meta;
  1387. line_meta["type"] = "connection";
  1388. line_meta["method"] = method;
  1389. line = functions[j].get_slicec(':', 1).to_int() - 1;
  1390. text_edit->set_line_gutter_metadata(line, connection_gutter, line_meta);
  1391. text_edit->set_line_gutter_icon(line, connection_gutter, get_parent_control()->get_editor_theme_icon(SNAME("Slot")));
  1392. text_edit->set_line_gutter_clickable(line, connection_gutter, true);
  1393. methods_found.insert(method);
  1394. break;
  1395. }
  1396. }
  1397. if (line >= 0) {
  1398. continue;
  1399. }
  1400. // There is a chance that the method is inherited from another script.
  1401. bool found_inherited_function = false;
  1402. Ref<Script> inherited_script = script->get_base_script();
  1403. while (inherited_script.is_valid()) {
  1404. if (inherited_script->has_method(method)) {
  1405. found_inherited_function = true;
  1406. break;
  1407. }
  1408. inherited_script = inherited_script->get_base_script();
  1409. }
  1410. if (!found_inherited_function) {
  1411. missing_connections.push_back(connection);
  1412. }
  1413. }
  1414. }
  1415. }
  1416. // Add override icons to methods.
  1417. methods_found.clear();
  1418. for (int i = 0; i < functions.size(); i++) {
  1419. String raw_name = functions[i].get_slicec(':', 0);
  1420. StringName name = StringName(raw_name);
  1421. if (methods_found.has(name)) {
  1422. continue;
  1423. }
  1424. // Account for inner classes by stripping the class names from the method,
  1425. // starting from the right since our inner class might be inside of another inner class.
  1426. int pos = raw_name.rfind_char('.');
  1427. if (pos != -1) {
  1428. name = raw_name.substr(pos + 1);
  1429. }
  1430. String found_base_class;
  1431. StringName base_class = script->get_instance_base_type();
  1432. Ref<Script> inherited_script = script->get_base_script();
  1433. while (inherited_script.is_valid()) {
  1434. if (inherited_script->has_method(name)) {
  1435. found_base_class = "script:" + inherited_script->get_path();
  1436. break;
  1437. }
  1438. base_class = inherited_script->get_instance_base_type();
  1439. inherited_script = inherited_script->get_base_script();
  1440. }
  1441. if (found_base_class.is_empty()) {
  1442. while (base_class) {
  1443. List<MethodInfo> methods;
  1444. ClassDB::get_method_list(base_class, &methods, true);
  1445. for (const MethodInfo &mi : methods) {
  1446. if (mi.name == name) {
  1447. found_base_class = "builtin:" + base_class;
  1448. break;
  1449. }
  1450. }
  1451. ClassDB::ClassInfo *base_class_ptr = ClassDB::classes.getptr(base_class)->inherits_ptr;
  1452. if (base_class_ptr == nullptr) {
  1453. break;
  1454. }
  1455. base_class = base_class_ptr->name;
  1456. }
  1457. }
  1458. if (!found_base_class.is_empty()) {
  1459. int line = functions[i].get_slicec(':', 1).to_int() - 1;
  1460. Dictionary line_meta = text_edit->get_line_gutter_metadata(line, connection_gutter);
  1461. if (line_meta.is_empty()) {
  1462. // Add override icon to gutter.
  1463. line_meta["type"] = "inherits";
  1464. line_meta["method"] = name;
  1465. line_meta["base_class"] = found_base_class;
  1466. text_edit->set_line_gutter_icon(line, connection_gutter, get_parent_control()->get_editor_theme_icon(SNAME("MethodOverride")));
  1467. text_edit->set_line_gutter_clickable(line, connection_gutter, true);
  1468. } else {
  1469. // If method is also connected to signal, then merge icons and keep the click behavior of the slot.
  1470. text_edit->set_line_gutter_icon(line, connection_gutter, get_parent_control()->get_editor_theme_icon(SNAME("MethodOverrideAndSlot")));
  1471. }
  1472. methods_found.insert(StringName(raw_name));
  1473. }
  1474. }
  1475. }
  1476. void ScriptTextEditor::_update_gutter_indexes() {
  1477. for (int i = 0; i < code_editor->get_text_editor()->get_gutter_count(); i++) {
  1478. if (code_editor->get_text_editor()->get_gutter_name(i) == "connection_gutter") {
  1479. connection_gutter = i;
  1480. continue;
  1481. }
  1482. if (code_editor->get_text_editor()->get_gutter_name(i) == "line_numbers") {
  1483. line_number_gutter = i;
  1484. continue;
  1485. }
  1486. }
  1487. }
  1488. void ScriptTextEditor::_gutter_clicked(int p_line, int p_gutter) {
  1489. if (p_gutter != connection_gutter) {
  1490. return;
  1491. }
  1492. Dictionary meta = code_editor->get_text_editor()->get_line_gutter_metadata(p_line, p_gutter);
  1493. String type = meta.get("type", "");
  1494. if (type.is_empty()) {
  1495. return;
  1496. }
  1497. // All types currently need a method name.
  1498. String method = meta.get("method", "");
  1499. if (method.is_empty()) {
  1500. return;
  1501. }
  1502. if (type == "connection") {
  1503. Node *base = get_tree()->get_edited_scene_root();
  1504. if (!base) {
  1505. return;
  1506. }
  1507. Vector<Node *> nodes = _find_all_node_for_script(base, base, script);
  1508. connection_info_dialog->popup_connections(method, nodes);
  1509. } else if (type == "inherits") {
  1510. String base_class_raw = meta["base_class"];
  1511. PackedStringArray base_class_split = base_class_raw.split(":", true, 1);
  1512. if (base_class_split[0] == "script") {
  1513. // Go to function declaration.
  1514. Ref<Script> base_script = ResourceLoader::load(base_class_split[1]);
  1515. ERR_FAIL_COND(base_script.is_null());
  1516. emit_signal(SNAME("go_to_method"), base_script, method);
  1517. } else if (base_class_split[0] == "builtin") {
  1518. // Open method documentation.
  1519. emit_signal(SNAME("go_to_help"), "class_method:" + base_class_split[1] + ":" + method);
  1520. }
  1521. }
  1522. }
  1523. void ScriptTextEditor::_edit_option(int p_op) {
  1524. CodeEdit *tx = code_editor->get_text_editor();
  1525. tx->apply_ime();
  1526. switch (p_op) {
  1527. case EDIT_UNDO: {
  1528. tx->undo();
  1529. callable_mp((Control *)tx, &Control::grab_focus).call_deferred(false);
  1530. } break;
  1531. case EDIT_REDO: {
  1532. tx->redo();
  1533. callable_mp((Control *)tx, &Control::grab_focus).call_deferred(false);
  1534. } break;
  1535. case EDIT_CUT: {
  1536. tx->cut();
  1537. callable_mp((Control *)tx, &Control::grab_focus).call_deferred(false);
  1538. } break;
  1539. case EDIT_COPY: {
  1540. tx->copy();
  1541. callable_mp((Control *)tx, &Control::grab_focus).call_deferred(false);
  1542. } break;
  1543. case EDIT_PASTE: {
  1544. tx->paste();
  1545. callable_mp((Control *)tx, &Control::grab_focus).call_deferred(false);
  1546. } break;
  1547. case EDIT_SELECT_ALL: {
  1548. tx->select_all();
  1549. callable_mp((Control *)tx, &Control::grab_focus).call_deferred(false);
  1550. } break;
  1551. case EDIT_MOVE_LINE_UP: {
  1552. code_editor->get_text_editor()->move_lines_up();
  1553. } break;
  1554. case EDIT_MOVE_LINE_DOWN: {
  1555. code_editor->get_text_editor()->move_lines_down();
  1556. } break;
  1557. case EDIT_INDENT: {
  1558. Ref<Script> scr = script;
  1559. if (scr.is_null()) {
  1560. return;
  1561. }
  1562. tx->indent_lines();
  1563. } break;
  1564. case EDIT_UNINDENT: {
  1565. Ref<Script> scr = script;
  1566. if (scr.is_null()) {
  1567. return;
  1568. }
  1569. tx->unindent_lines();
  1570. } break;
  1571. case EDIT_DELETE_LINE: {
  1572. code_editor->get_text_editor()->delete_lines();
  1573. } break;
  1574. case EDIT_DUPLICATE_SELECTION: {
  1575. code_editor->get_text_editor()->duplicate_selection();
  1576. } break;
  1577. case EDIT_DUPLICATE_LINES: {
  1578. code_editor->get_text_editor()->duplicate_lines();
  1579. } break;
  1580. case EDIT_TOGGLE_FOLD_LINE: {
  1581. tx->toggle_foldable_lines_at_carets();
  1582. } break;
  1583. case EDIT_FOLD_ALL_LINES: {
  1584. tx->fold_all_lines();
  1585. } break;
  1586. case EDIT_UNFOLD_ALL_LINES: {
  1587. tx->unfold_all_lines();
  1588. } break;
  1589. case EDIT_CREATE_CODE_REGION: {
  1590. tx->create_code_region();
  1591. } break;
  1592. case EDIT_TOGGLE_COMMENT: {
  1593. _edit_option_toggle_inline_comment();
  1594. } break;
  1595. case EDIT_COMPLETE: {
  1596. tx->request_code_completion(true);
  1597. } break;
  1598. case EDIT_AUTO_INDENT: {
  1599. String text = tx->get_text();
  1600. Ref<Script> scr = script;
  1601. if (scr.is_null()) {
  1602. return;
  1603. }
  1604. tx->begin_complex_operation();
  1605. tx->begin_multicaret_edit();
  1606. int begin = tx->get_line_count() - 1, end = 0;
  1607. if (tx->has_selection()) {
  1608. // Auto indent all lines that have a caret or selection on it.
  1609. Vector<Point2i> line_ranges = tx->get_line_ranges_from_carets();
  1610. for (Point2i line_range : line_ranges) {
  1611. scr->get_language()->auto_indent_code(text, line_range.x, line_range.y);
  1612. if (line_range.x < begin) {
  1613. begin = line_range.x;
  1614. }
  1615. if (line_range.y > end) {
  1616. end = line_range.y;
  1617. }
  1618. }
  1619. } else {
  1620. // Auto indent entire text.
  1621. begin = 0;
  1622. end = tx->get_line_count() - 1;
  1623. scr->get_language()->auto_indent_code(text, begin, end);
  1624. }
  1625. // Apply auto indented code.
  1626. Vector<String> lines = text.split("\n");
  1627. for (int i = begin; i <= end; ++i) {
  1628. tx->set_line(i, lines[i]);
  1629. }
  1630. tx->end_multicaret_edit();
  1631. tx->end_complex_operation();
  1632. } break;
  1633. case EDIT_TRIM_TRAILING_WHITESAPCE: {
  1634. trim_trailing_whitespace();
  1635. } break;
  1636. case EDIT_TRIM_FINAL_NEWLINES: {
  1637. trim_final_newlines();
  1638. } break;
  1639. case EDIT_CONVERT_INDENT_TO_SPACES: {
  1640. code_editor->set_indent_using_spaces(true);
  1641. convert_indent();
  1642. } break;
  1643. case EDIT_CONVERT_INDENT_TO_TABS: {
  1644. code_editor->set_indent_using_spaces(false);
  1645. convert_indent();
  1646. } break;
  1647. case EDIT_PICK_COLOR: {
  1648. color_panel->popup();
  1649. } break;
  1650. case EDIT_TO_UPPERCASE: {
  1651. _convert_case(CodeTextEditor::UPPER);
  1652. } break;
  1653. case EDIT_TO_LOWERCASE: {
  1654. _convert_case(CodeTextEditor::LOWER);
  1655. } break;
  1656. case EDIT_CAPITALIZE: {
  1657. _convert_case(CodeTextEditor::CAPITALIZE);
  1658. } break;
  1659. case EDIT_EVALUATE: {
  1660. Expression expression;
  1661. tx->begin_complex_operation();
  1662. for (int caret_idx = 0; caret_idx < tx->get_caret_count(); caret_idx++) {
  1663. Vector<String> lines = tx->get_selected_text(caret_idx).split("\n");
  1664. PackedStringArray results;
  1665. for (int i = 0; i < lines.size(); i++) {
  1666. const String &line = lines[i];
  1667. String whitespace = line.substr(0, line.size() - line.strip_edges(true, false).size()); // Extract the whitespace at the beginning.
  1668. if (expression.parse(line) == OK) {
  1669. Variant result = expression.execute(Array(), Variant(), false, true);
  1670. if (expression.get_error_text().is_empty()) {
  1671. results.push_back(whitespace + result.get_construct_string());
  1672. } else {
  1673. results.push_back(line);
  1674. }
  1675. } else {
  1676. results.push_back(line);
  1677. }
  1678. }
  1679. tx->insert_text_at_caret(String("\n").join(results), caret_idx);
  1680. }
  1681. tx->end_complex_operation();
  1682. } break;
  1683. case EDIT_TOGGLE_WORD_WRAP: {
  1684. TextEdit::LineWrappingMode wrap = code_editor->get_text_editor()->get_line_wrapping_mode();
  1685. code_editor->get_text_editor()->set_line_wrapping_mode(wrap == TextEdit::LINE_WRAPPING_BOUNDARY ? TextEdit::LINE_WRAPPING_NONE : TextEdit::LINE_WRAPPING_BOUNDARY);
  1686. } break;
  1687. case SEARCH_FIND: {
  1688. code_editor->get_find_replace_bar()->popup_search();
  1689. } break;
  1690. case SEARCH_FIND_NEXT: {
  1691. code_editor->get_find_replace_bar()->search_next();
  1692. } break;
  1693. case SEARCH_FIND_PREV: {
  1694. code_editor->get_find_replace_bar()->search_prev();
  1695. } break;
  1696. case SEARCH_REPLACE: {
  1697. code_editor->get_find_replace_bar()->popup_replace();
  1698. } break;
  1699. case SEARCH_IN_FILES: {
  1700. String selected_text = tx->get_selected_text();
  1701. // Yep, because it doesn't make sense to instance this dialog for every single script open...
  1702. // So this will be delegated to the ScriptEditor.
  1703. emit_signal(SNAME("search_in_files_requested"), selected_text);
  1704. } break;
  1705. case REPLACE_IN_FILES: {
  1706. String selected_text = tx->get_selected_text();
  1707. emit_signal(SNAME("replace_in_files_requested"), selected_text);
  1708. } break;
  1709. case SEARCH_LOCATE_FUNCTION: {
  1710. quick_open->popup_dialog(get_functions());
  1711. } break;
  1712. case SEARCH_GOTO_LINE: {
  1713. goto_line_popup->popup_find_line(code_editor);
  1714. } break;
  1715. case BOOKMARK_TOGGLE: {
  1716. code_editor->toggle_bookmark();
  1717. } break;
  1718. case BOOKMARK_GOTO_NEXT: {
  1719. code_editor->goto_next_bookmark();
  1720. } break;
  1721. case BOOKMARK_GOTO_PREV: {
  1722. code_editor->goto_prev_bookmark();
  1723. } break;
  1724. case BOOKMARK_REMOVE_ALL: {
  1725. code_editor->remove_all_bookmarks();
  1726. } break;
  1727. case DEBUG_TOGGLE_BREAKPOINT: {
  1728. Vector<int> sorted_carets = tx->get_sorted_carets();
  1729. int last_line = -1;
  1730. for (const int &c : sorted_carets) {
  1731. int from = tx->get_selection_from_line(c);
  1732. from += from == last_line ? 1 : 0;
  1733. int to = tx->get_selection_to_line(c);
  1734. if (to < from) {
  1735. continue;
  1736. }
  1737. // Check first if there's any lines with breakpoints in the selection.
  1738. bool selection_has_breakpoints = false;
  1739. for (int line = from; line <= to; line++) {
  1740. if (tx->is_line_breakpointed(line)) {
  1741. selection_has_breakpoints = true;
  1742. break;
  1743. }
  1744. }
  1745. // Set breakpoint on caret or remove all bookmarks from the selection.
  1746. if (!selection_has_breakpoints) {
  1747. if (tx->get_caret_line(c) != last_line) {
  1748. tx->set_line_as_breakpoint(tx->get_caret_line(c), true);
  1749. }
  1750. } else {
  1751. for (int line = from; line <= to; line++) {
  1752. tx->set_line_as_breakpoint(line, false);
  1753. }
  1754. }
  1755. last_line = to;
  1756. }
  1757. } break;
  1758. case DEBUG_REMOVE_ALL_BREAKPOINTS: {
  1759. PackedInt32Array bpoints = tx->get_breakpointed_lines();
  1760. for (int i = 0; i < bpoints.size(); i++) {
  1761. int line = bpoints[i];
  1762. bool dobreak = !tx->is_line_breakpointed(line);
  1763. tx->set_line_as_breakpoint(line, dobreak);
  1764. EditorDebuggerNode::get_singleton()->set_breakpoint(script->get_path(), line + 1, dobreak);
  1765. }
  1766. } break;
  1767. case DEBUG_GOTO_NEXT_BREAKPOINT: {
  1768. PackedInt32Array bpoints = tx->get_breakpointed_lines();
  1769. if (bpoints.is_empty()) {
  1770. return;
  1771. }
  1772. int current_line = tx->get_caret_line();
  1773. int bpoint_idx = 0;
  1774. if (current_line < (int)bpoints[bpoints.size() - 1]) {
  1775. while (bpoint_idx < bpoints.size() && bpoints[bpoint_idx] <= current_line) {
  1776. bpoint_idx++;
  1777. }
  1778. }
  1779. code_editor->goto_line_centered(bpoints[bpoint_idx]);
  1780. } break;
  1781. case DEBUG_GOTO_PREV_BREAKPOINT: {
  1782. PackedInt32Array bpoints = tx->get_breakpointed_lines();
  1783. if (bpoints.is_empty()) {
  1784. return;
  1785. }
  1786. int current_line = tx->get_caret_line();
  1787. int bpoint_idx = bpoints.size() - 1;
  1788. if (current_line > (int)bpoints[0]) {
  1789. while (bpoint_idx >= 0 && bpoints[bpoint_idx] >= current_line) {
  1790. bpoint_idx--;
  1791. }
  1792. }
  1793. code_editor->goto_line_centered(bpoints[bpoint_idx]);
  1794. } break;
  1795. case HELP_CONTEXTUAL: {
  1796. String text = tx->get_selected_text(0);
  1797. if (text.is_empty()) {
  1798. text = tx->get_word_under_caret(0);
  1799. }
  1800. if (!text.is_empty()) {
  1801. emit_signal(SNAME("request_help"), text);
  1802. }
  1803. } break;
  1804. case LOOKUP_SYMBOL: {
  1805. String text = tx->get_word_under_caret(0);
  1806. if (text.is_empty()) {
  1807. text = tx->get_selected_text(0);
  1808. }
  1809. if (!text.is_empty()) {
  1810. _lookup_symbol(text, tx->get_caret_line(0), tx->get_caret_column(0));
  1811. }
  1812. } break;
  1813. case EDIT_EMOJI_AND_SYMBOL: {
  1814. code_editor->get_text_editor()->show_emoji_and_symbol_picker();
  1815. } break;
  1816. default: {
  1817. if (p_op >= EditorContextMenuPlugin::BASE_ID) {
  1818. EditorContextMenuPluginManager::get_singleton()->activate_custom_option(EditorContextMenuPlugin::CONTEXT_SLOT_SCRIPT_EDITOR_CODE, p_op, tx);
  1819. }
  1820. }
  1821. }
  1822. }
  1823. void ScriptTextEditor::_edit_option_toggle_inline_comment() {
  1824. if (script.is_null()) {
  1825. return;
  1826. }
  1827. String delimiter = "#";
  1828. for (const String &script_delimiter : script->get_language()->get_comment_delimiters()) {
  1829. if (!script_delimiter.contains_char(' ')) {
  1830. delimiter = script_delimiter;
  1831. break;
  1832. }
  1833. }
  1834. code_editor->toggle_inline_comment(delimiter);
  1835. }
  1836. void ScriptTextEditor::add_syntax_highlighter(Ref<EditorSyntaxHighlighter> p_highlighter) {
  1837. ERR_FAIL_COND(p_highlighter.is_null());
  1838. highlighters[p_highlighter->_get_name()] = p_highlighter;
  1839. highlighter_menu->add_radio_check_item(p_highlighter->_get_name());
  1840. }
  1841. void ScriptTextEditor::set_syntax_highlighter(Ref<EditorSyntaxHighlighter> p_highlighter) {
  1842. ERR_FAIL_COND(p_highlighter.is_null());
  1843. HashMap<String, Ref<EditorSyntaxHighlighter>>::Iterator el = highlighters.begin();
  1844. while (el) {
  1845. int highlighter_index = highlighter_menu->get_item_idx_from_text(el->key);
  1846. highlighter_menu->set_item_checked(highlighter_index, el->value == p_highlighter);
  1847. ++el;
  1848. }
  1849. CodeEdit *te = code_editor->get_text_editor();
  1850. p_highlighter->_set_edited_resource(script);
  1851. te->set_syntax_highlighter(p_highlighter);
  1852. }
  1853. void ScriptTextEditor::_change_syntax_highlighter(int p_idx) {
  1854. set_syntax_highlighter(highlighters[highlighter_menu->get_item_text(p_idx)]);
  1855. }
  1856. void ScriptTextEditor::_notification(int p_what) {
  1857. switch (p_what) {
  1858. case NOTIFICATION_TRANSLATION_CHANGED: {
  1859. if (is_ready() && is_visible_in_tree()) {
  1860. _update_errors();
  1861. _update_warnings();
  1862. }
  1863. } break;
  1864. case NOTIFICATION_THEME_CHANGED:
  1865. if (!editor_enabled) {
  1866. break;
  1867. }
  1868. if (is_visible_in_tree()) {
  1869. _update_warnings();
  1870. _update_errors();
  1871. _update_background_color();
  1872. }
  1873. [[fallthrough]];
  1874. case NOTIFICATION_ENTER_TREE: {
  1875. code_editor->get_text_editor()->set_gutter_width(connection_gutter, code_editor->get_text_editor()->get_line_height());
  1876. Ref<Font> code_font = get_theme_font("font", "CodeEdit");
  1877. inline_color_options->add_theme_font_override("font", code_font);
  1878. inline_color_options->get_popup()->add_theme_font_override("font", code_font);
  1879. } break;
  1880. }
  1881. }
  1882. Control *ScriptTextEditor::get_edit_menu() {
  1883. return edit_hb;
  1884. }
  1885. void ScriptTextEditor::clear_edit_menu() {
  1886. if (editor_enabled) {
  1887. memdelete(edit_hb);
  1888. }
  1889. }
  1890. void ScriptTextEditor::set_find_replace_bar(FindReplaceBar *p_bar) {
  1891. code_editor->set_find_replace_bar(p_bar);
  1892. }
  1893. void ScriptTextEditor::reload(bool p_soft) {
  1894. CodeEdit *te = code_editor->get_text_editor();
  1895. Ref<Script> scr = script;
  1896. if (scr.is_null()) {
  1897. return;
  1898. }
  1899. scr->set_source_code(te->get_text());
  1900. bool soft = p_soft || ClassDB::is_parent_class(scr->get_instance_base_type(), "EditorPlugin"); // Always soft-reload editor plugins.
  1901. scr->get_language()->reload_tool_script(scr, soft);
  1902. }
  1903. PackedInt32Array ScriptTextEditor::get_breakpoints() {
  1904. return code_editor->get_text_editor()->get_breakpointed_lines();
  1905. }
  1906. void ScriptTextEditor::set_breakpoint(int p_line, bool p_enabled) {
  1907. code_editor->get_text_editor()->set_line_as_breakpoint(p_line, p_enabled);
  1908. }
  1909. void ScriptTextEditor::clear_breakpoints() {
  1910. code_editor->get_text_editor()->clear_breakpointed_lines();
  1911. }
  1912. void ScriptTextEditor::set_tooltip_request_func(const Callable &p_toolip_callback) {
  1913. Variant args[1] = { this };
  1914. const Variant *argp[] = { &args[0] };
  1915. code_editor->get_text_editor()->set_tooltip_request_func(p_toolip_callback.bindp(argp, 1));
  1916. }
  1917. void ScriptTextEditor::set_debugger_active(bool p_active) {
  1918. }
  1919. Control *ScriptTextEditor::get_base_editor() const {
  1920. return code_editor->get_text_editor();
  1921. }
  1922. CodeTextEditor *ScriptTextEditor::get_code_editor() const {
  1923. return code_editor;
  1924. }
  1925. Variant ScriptTextEditor::get_drag_data_fw(const Point2 &p_point, Control *p_from) {
  1926. return Variant();
  1927. }
  1928. bool ScriptTextEditor::can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const {
  1929. Dictionary d = p_data;
  1930. if (d.has("type") &&
  1931. (String(d["type"]) == "resource" ||
  1932. String(d["type"]) == "files" ||
  1933. String(d["type"]) == "nodes" ||
  1934. String(d["type"]) == "obj_property" ||
  1935. String(d["type"]) == "files_and_dirs")) {
  1936. return true;
  1937. }
  1938. return false;
  1939. }
  1940. static Node *_find_script_node(Node *p_current_node, const Ref<Script> &script) {
  1941. if (p_current_node->get_script() == script) {
  1942. return p_current_node;
  1943. }
  1944. for (int i = 0; i < p_current_node->get_child_count(); i++) {
  1945. Node *n = _find_script_node(p_current_node->get_child(i), script);
  1946. if (n) {
  1947. return n;
  1948. }
  1949. }
  1950. return nullptr;
  1951. }
  1952. static String _quote_drop_data(const String &str) {
  1953. // This function prepares a string for being "dropped" into the script editor.
  1954. // The string can be a resource path, node path or property name.
  1955. const bool using_single_quotes = EDITOR_GET("text_editor/completion/use_single_quotes");
  1956. String escaped = str.c_escape();
  1957. // If string is double quoted, there is no need to escape single quotes.
  1958. // We can revert the extra escaping added in c_escape().
  1959. if (!using_single_quotes) {
  1960. escaped = escaped.replace("\\'", "\'");
  1961. }
  1962. return escaped.quote(using_single_quotes ? "'" : "\"");
  1963. }
  1964. static String _get_dropped_resource_as_member(const Ref<Resource> &p_resource, bool p_create_field, bool p_allow_uid) {
  1965. String path = p_resource->get_path();
  1966. if (p_allow_uid) {
  1967. ResourceUID::ID id = ResourceLoader::get_resource_uid(path);
  1968. if (id != ResourceUID::INVALID_ID) {
  1969. path = ResourceUID::get_singleton()->id_to_text(id);
  1970. }
  1971. }
  1972. const bool is_script = ClassDB::is_parent_class(p_resource->get_class(), "Script");
  1973. if (!p_create_field) {
  1974. return vformat("preload(%s)", _quote_drop_data(path));
  1975. }
  1976. String variable_name = p_resource->get_name();
  1977. if (variable_name.is_empty()) {
  1978. variable_name = p_resource->get_path().get_file().get_basename();
  1979. }
  1980. if (is_script) {
  1981. variable_name = variable_name.to_pascal_case().validate_unicode_identifier();
  1982. } else {
  1983. variable_name = variable_name.to_snake_case().to_upper().validate_unicode_identifier();
  1984. }
  1985. return vformat("const %s = preload(%s)", variable_name, _quote_drop_data(path));
  1986. }
  1987. String ScriptTextEditor::_get_dropped_resource_as_exported_member(const Ref<Resource> &p_resource, const Vector<ObjectID> &p_script_instance_obj_ids) {
  1988. String variable_name = p_resource->get_name();
  1989. if (variable_name.is_empty()) {
  1990. variable_name = p_resource->get_path().get_file().get_basename();
  1991. }
  1992. variable_name = variable_name.to_snake_case().validate_unicode_identifier();
  1993. StringName class_name = p_resource->get_class();
  1994. Ref<Script> resource_script = p_resource->get_script();
  1995. if (resource_script.is_valid()) {
  1996. StringName global_resource_script_name = resource_script->get_global_name();
  1997. if (!global_resource_script_name.is_empty()) {
  1998. class_name = global_resource_script_name;
  1999. }
  2000. }
  2001. for (ObjectID obj_id : p_script_instance_obj_ids) {
  2002. pending_dragged_exports.push_back(DraggedExport{ obj_id, variable_name, p_resource, class_name });
  2003. }
  2004. return vformat("@export var %s: %s", variable_name, class_name);
  2005. }
  2006. void ScriptTextEditor::drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) {
  2007. Dictionary d = p_data;
  2008. CodeEdit *te = code_editor->get_text_editor();
  2009. Point2i pos = (p_point == Vector2(Math::INF, Math::INF)) ? Point2i(te->get_caret_line(0), te->get_caret_column(0)) : te->get_line_column_at_pos(p_point);
  2010. int drop_at_line = pos.y;
  2011. int drop_at_column = pos.x;
  2012. int selection_index = te->get_selection_at_line_column(drop_at_line, drop_at_column);
  2013. bool is_empty_line = false;
  2014. if (selection_index >= 0) {
  2015. // Dropped on a selection, it will be replaced.
  2016. drop_at_line = te->get_selection_from_line(selection_index);
  2017. drop_at_column = te->get_selection_from_column(selection_index);
  2018. is_empty_line = drop_at_column <= te->get_first_non_whitespace_column(drop_at_line) && te->get_selection_to_column(selection_index) == te->get_line(te->get_selection_to_line(selection_index)).length();
  2019. }
  2020. Node *scene_root = get_tree()->get_edited_scene_root();
  2021. const bool member_drop_modifier_pressed = Input::get_singleton()->is_key_pressed(Key::CMD_OR_CTRL);
  2022. const bool export_drop_modifier_pressed = Input::get_singleton()->is_key_pressed(Key::ALT);
  2023. const bool allow_uid = Input::get_singleton()->is_key_pressed(Key::SHIFT) != bool(EDITOR_GET("text_editor/behavior/files/drop_preload_resources_as_uid"));
  2024. const String &line = te->get_line(drop_at_line);
  2025. if (selection_index < 0) {
  2026. is_empty_line = line.is_empty() || te->get_first_non_whitespace_column(drop_at_line) == line.length();
  2027. }
  2028. String text_to_drop;
  2029. bool add_new_line = false;
  2030. const String type = d.get("type", "");
  2031. if (type == "resource") {
  2032. Ref<Resource> resource = d["resource"];
  2033. if (resource.is_null()) {
  2034. return;
  2035. }
  2036. const String &path = resource->get_path();
  2037. if (path.is_empty() || path.ends_with("::")) {
  2038. String warning = TTR("The resource does not have a valid path because it has not been saved.\nPlease save the scene or resource that contains this resource and try again.");
  2039. EditorToaster::get_singleton()->popup_str(warning, EditorToaster::SEVERITY_ERROR);
  2040. return;
  2041. }
  2042. if (member_drop_modifier_pressed) {
  2043. if (resource->is_built_in()) {
  2044. String warning = TTR("Preloading internal resources is not supported.");
  2045. EditorToaster::get_singleton()->popup_str(warning, EditorToaster::SEVERITY_ERROR);
  2046. } else {
  2047. text_to_drop = _get_dropped_resource_as_member(resource, is_empty_line, allow_uid);
  2048. }
  2049. } else if (export_drop_modifier_pressed) {
  2050. Vector<ObjectID> obj_ids = _get_objects_for_export_assignment();
  2051. text_to_drop = _get_dropped_resource_as_exported_member(resource, obj_ids);
  2052. } else {
  2053. text_to_drop = _quote_drop_data(path);
  2054. }
  2055. if (is_empty_line) {
  2056. text_to_drop += "\n";
  2057. }
  2058. }
  2059. if (type == "files" || type == "files_and_dirs") {
  2060. const PackedStringArray files = d["files"];
  2061. PackedStringArray parts;
  2062. for (const String &path : files) {
  2063. if ((member_drop_modifier_pressed || export_drop_modifier_pressed) && ResourceLoader::exists(path)) {
  2064. Ref<Resource> resource = ResourceLoader::load(path);
  2065. if (resource.is_null()) {
  2066. // Resource exists, but failed to load. We need only path and name, so we can use a dummy Resource instead.
  2067. resource.instantiate();
  2068. resource->set_path_cache(path);
  2069. }
  2070. if (member_drop_modifier_pressed) {
  2071. parts.append(_get_dropped_resource_as_member(resource, is_empty_line, allow_uid));
  2072. } else if (export_drop_modifier_pressed) {
  2073. Vector<ObjectID> obj_ids = _get_objects_for_export_assignment();
  2074. parts.append(_get_dropped_resource_as_exported_member(resource, obj_ids));
  2075. }
  2076. } else {
  2077. parts.append(_quote_drop_data(path));
  2078. }
  2079. }
  2080. String join_string;
  2081. if (is_empty_line) {
  2082. int indent_level = te->get_indent_level(drop_at_line);
  2083. if (te->is_indent_using_spaces()) {
  2084. join_string = "\n" + String(" ").repeat(indent_level);
  2085. } else {
  2086. join_string = "\n" + String("\t").repeat(indent_level / te->get_tab_size());
  2087. }
  2088. } else {
  2089. join_string = ", ";
  2090. }
  2091. text_to_drop = join_string.join(parts);
  2092. if (is_empty_line) {
  2093. text_to_drop += join_string;
  2094. }
  2095. }
  2096. if (type == "nodes") {
  2097. if (!scene_root) {
  2098. EditorNode::get_singleton()->show_warning(TTR("Can't drop nodes without an open scene."));
  2099. return;
  2100. }
  2101. if (!ClassDB::is_parent_class(script->get_instance_base_type(), "Node")) {
  2102. EditorToaster::get_singleton()->popup_str(vformat(TTR("Can't drop nodes because script '%s' does not inherit Node."), get_name()), EditorToaster::SEVERITY_WARNING);
  2103. return;
  2104. }
  2105. Node *sn = _find_script_node(scene_root, script);
  2106. if (!sn) {
  2107. sn = scene_root;
  2108. }
  2109. Array nodes = d["nodes"];
  2110. if (member_drop_modifier_pressed) {
  2111. const bool use_type = EDITOR_GET("text_editor/completion/add_type_hints");
  2112. add_new_line = !is_empty_line && drop_at_column != 0;
  2113. for (int i = 0; i < nodes.size(); i++) {
  2114. NodePath np = nodes[i];
  2115. Node *node = get_node(np);
  2116. if (!node) {
  2117. continue;
  2118. }
  2119. bool is_unique = node->is_unique_name_in_owner() && (node->get_owner() == sn || node->get_owner() == sn->get_owner());
  2120. String path = is_unique ? String(node->get_name()) : String(sn->get_path_to(node));
  2121. for (const String &segment : path.split("/")) {
  2122. if (!segment.is_valid_unicode_identifier()) {
  2123. path = _quote_drop_data(path);
  2124. break;
  2125. }
  2126. }
  2127. String variable_name = String(node->get_name()).to_snake_case().validate_unicode_identifier();
  2128. if (use_type) {
  2129. StringName class_name = node->get_class_name();
  2130. Ref<Script> node_script = node->get_script();
  2131. if (node_script.is_valid()) {
  2132. StringName global_node_script_name = node_script->get_global_name();
  2133. if (!global_node_script_name.is_empty()) {
  2134. class_name = global_node_script_name;
  2135. }
  2136. }
  2137. text_to_drop += vformat("@onready var %s: %s = %c%s", variable_name, class_name, is_unique ? '%' : '$', path);
  2138. } else {
  2139. text_to_drop += vformat("@onready var %s = %c%s", variable_name, is_unique ? '%' : '$', path);
  2140. }
  2141. if (i < nodes.size() - 1) {
  2142. text_to_drop += "\n";
  2143. }
  2144. }
  2145. if (is_empty_line || drop_at_column == 0) {
  2146. text_to_drop += "\n";
  2147. }
  2148. } else if (export_drop_modifier_pressed) {
  2149. Vector<ObjectID> obj_ids = _get_objects_for_export_assignment();
  2150. for (int i = 0; i < nodes.size(); i++) {
  2151. NodePath np = nodes[i];
  2152. Node *node = get_node(np);
  2153. if (!node) {
  2154. continue;
  2155. }
  2156. String variable_name = String(node->get_name()).to_snake_case().validate_unicode_identifier();
  2157. StringName class_name = node->get_class_name();
  2158. Ref<Script> node_script = node->get_script();
  2159. if (node_script.is_valid()) {
  2160. StringName global_node_script_name = node_script->get_global_name();
  2161. if (!global_node_script_name.is_empty()) {
  2162. class_name = global_node_script_name;
  2163. }
  2164. }
  2165. text_to_drop += vformat("@export var %s: %s\n", variable_name, class_name);
  2166. for (ObjectID obj_id : obj_ids) {
  2167. pending_dragged_exports.push_back(DraggedExport{ obj_id, variable_name, node, class_name });
  2168. }
  2169. }
  2170. } else {
  2171. for (int i = 0; i < nodes.size(); i++) {
  2172. if (i > 0) {
  2173. text_to_drop += ", ";
  2174. }
  2175. NodePath np = nodes[i];
  2176. Node *node = get_node(np);
  2177. if (!node) {
  2178. continue;
  2179. }
  2180. bool is_unique = node->is_unique_name_in_owner() && (node->get_owner() == sn || node->get_owner() == sn->get_owner());
  2181. String path = is_unique ? String(node->get_name()) : String(sn->get_path_to(node));
  2182. for (const String &segment : path.split("/")) {
  2183. if (!segment.is_valid_ascii_identifier()) {
  2184. path = _quote_drop_data(path);
  2185. break;
  2186. }
  2187. }
  2188. text_to_drop += (is_unique ? "%" : "$") + path;
  2189. }
  2190. }
  2191. }
  2192. if (type == "obj_property") {
  2193. bool add_literal = EDITOR_GET("text_editor/completion/add_node_path_literals");
  2194. text_to_drop = add_literal ? "^" : "";
  2195. // It is unclear whether properties may contain single or double quotes.
  2196. // Assume here that double-quotes may not exist. We are escaping single-quotes if necessary.
  2197. text_to_drop += _quote_drop_data(String(d["property"]));
  2198. }
  2199. if (text_to_drop.is_empty()) {
  2200. return;
  2201. }
  2202. // Remove drag caret before any actions so it is not included in undo.
  2203. te->remove_drag_caret();
  2204. te->begin_complex_operation();
  2205. if (selection_index >= 0) {
  2206. te->delete_selection(selection_index);
  2207. }
  2208. te->remove_secondary_carets();
  2209. te->deselect();
  2210. te->set_caret_line(drop_at_line);
  2211. if (add_new_line) {
  2212. te->set_caret_column(te->get_line(drop_at_line).length());
  2213. text_to_drop = "\n" + text_to_drop;
  2214. } else {
  2215. te->set_caret_column(drop_at_column);
  2216. }
  2217. te->insert_text_at_caret(text_to_drop);
  2218. te->end_complex_operation();
  2219. te->grab_focus();
  2220. }
  2221. Vector<ObjectID> ScriptTextEditor::_get_objects_for_export_assignment() const {
  2222. Vector<ObjectID> objects;
  2223. Node *scene_root = get_tree()->get_edited_scene_root();
  2224. bool assign_export_variables = scene_root && ClassDB::is_parent_class(script->get_instance_base_type(), "Node");
  2225. if (!assign_export_variables) {
  2226. return objects;
  2227. }
  2228. EditorInspector *inspector = EditorInterface::get_singleton()->get_inspector();
  2229. if (inspector) {
  2230. Object *edited_object = inspector->get_edited_object();
  2231. Node *node_edit = Object::cast_to<Node>(edited_object);
  2232. MultiNodeEdit *multi_node_edit = Object::cast_to<MultiNodeEdit>(edited_object);
  2233. if (node_edit != nullptr) {
  2234. if (node_edit->get_script() == script) {
  2235. objects.push_back(node_edit->get_instance_id());
  2236. }
  2237. } else if (multi_node_edit != nullptr) {
  2238. Node *es = EditorNode::get_singleton()->get_edited_scene();
  2239. for (int i = 0; i < multi_node_edit->get_node_count(); i++) {
  2240. NodePath np = multi_node_edit->get_node(i);
  2241. Node *node = es->get_node(np);
  2242. if (node->get_script() == script) {
  2243. objects.push_back(node->get_instance_id());
  2244. }
  2245. }
  2246. }
  2247. }
  2248. // In case there is no current editor selection/editor selection does not contain this script,
  2249. // it often still makes sense to try to assign the export variable,
  2250. // so we default to the first node with the script we find in the scene.
  2251. if (objects.is_empty()) {
  2252. Node *sn = _find_script_node(scene_root, script);
  2253. if (sn) {
  2254. objects.push_back(sn->get_instance_id());
  2255. }
  2256. }
  2257. return objects;
  2258. }
  2259. void ScriptTextEditor::_assign_dragged_export_variables() {
  2260. ERR_FAIL_COND(pending_dragged_exports.is_empty());
  2261. bool export_variable_set = false;
  2262. for (int i = pending_dragged_exports.size() - 1; i >= 0; i--) {
  2263. const DraggedExport &dragged_export = pending_dragged_exports[i];
  2264. Object *obj = ObjectDB::get_instance(dragged_export.obj_id);
  2265. if (!obj) {
  2266. WARN_PRINT("Object not found, can't assign export variable.");
  2267. pending_dragged_exports.remove_at(i);
  2268. continue;
  2269. }
  2270. ScriptInstance *si = obj->get_script_instance();
  2271. if (!si) {
  2272. WARN_PRINT("Script on " + obj->to_string() + " does not exist anymore, can't assign export variable.");
  2273. pending_dragged_exports.remove_at(i);
  2274. continue;
  2275. }
  2276. bool script_has_errors = false;
  2277. String scr_path = si->get_script()->get_path();
  2278. for (const ScriptLanguage::ScriptError &error : errors) {
  2279. if (error.path == scr_path) {
  2280. script_has_errors = true;
  2281. break;
  2282. }
  2283. }
  2284. if (!script_has_errors) {
  2285. bool success = false;
  2286. List<PropertyInfo> properties;
  2287. si->get_property_list(&properties);
  2288. for (const PropertyInfo &pi : properties) {
  2289. if (pi.name == dragged_export.variable_name && pi.hint_string == dragged_export.class_name) {
  2290. success = si->set(dragged_export.variable_name, dragged_export.value);
  2291. break;
  2292. }
  2293. }
  2294. if (success) {
  2295. export_variable_set = true;
  2296. }
  2297. pending_dragged_exports.remove_at(i);
  2298. }
  2299. }
  2300. if (export_variable_set) {
  2301. EditorInterface::get_singleton()->mark_scene_as_unsaved();
  2302. }
  2303. }
  2304. void ScriptTextEditor::_text_edit_gui_input(const Ref<InputEvent> &ev) {
  2305. Ref<InputEventMouseButton> mb = ev;
  2306. Ref<InputEventKey> k = ev;
  2307. Point2 local_pos;
  2308. bool create_menu = false;
  2309. CodeEdit *tx = code_editor->get_text_editor();
  2310. if (mb.is_valid() && mb->get_button_index() == MouseButton::RIGHT && mb->is_pressed()) {
  2311. local_pos = mb->get_global_position() - tx->get_global_position();
  2312. create_menu = true;
  2313. } else if (k.is_valid() && k->is_action("ui_menu", true)) {
  2314. tx->adjust_viewport_to_caret(0);
  2315. local_pos = tx->get_caret_draw_pos(0);
  2316. create_menu = true;
  2317. }
  2318. if (create_menu) {
  2319. tx->apply_ime();
  2320. Point2i pos = tx->get_line_column_at_pos(local_pos);
  2321. int mouse_line = pos.y;
  2322. int mouse_column = pos.x;
  2323. tx->set_move_caret_on_right_click_enabled(EDITOR_GET("text_editor/behavior/navigation/move_caret_on_right_click"));
  2324. int selection_clicked = -1;
  2325. if (tx->is_move_caret_on_right_click_enabled()) {
  2326. selection_clicked = tx->get_selection_at_line_column(mouse_line, mouse_column, true);
  2327. if (selection_clicked < 0) {
  2328. tx->deselect();
  2329. tx->remove_secondary_carets();
  2330. selection_clicked = 0;
  2331. tx->set_caret_line(mouse_line, false, false, -1);
  2332. tx->set_caret_column(mouse_column);
  2333. }
  2334. }
  2335. String word_at_pos = tx->get_lookup_word(mouse_line, mouse_column);
  2336. if (word_at_pos.is_empty()) {
  2337. word_at_pos = tx->get_word_under_caret(selection_clicked);
  2338. }
  2339. if (word_at_pos.is_empty()) {
  2340. word_at_pos = tx->get_selected_text(selection_clicked);
  2341. }
  2342. bool has_color = (word_at_pos == "Color");
  2343. bool foldable = tx->can_fold_line(mouse_line) || tx->is_line_folded(mouse_line);
  2344. bool open_docs = false;
  2345. bool goto_definition = false;
  2346. if (ScriptServer::is_global_class(word_at_pos) || word_at_pos.is_resource_file()) {
  2347. open_docs = true;
  2348. } else {
  2349. Node *base = get_tree()->get_edited_scene_root();
  2350. if (base) {
  2351. base = _find_node_for_script(base, base, script);
  2352. }
  2353. ScriptLanguage::LookupResult result;
  2354. if (script->get_language()->lookup_code(tx->get_text_for_symbol_lookup(), word_at_pos, script->get_path(), base, result) == OK) {
  2355. open_docs = true;
  2356. }
  2357. }
  2358. if (has_color) {
  2359. String line = tx->get_line(mouse_line);
  2360. color_position.x = mouse_line;
  2361. int begin = -1;
  2362. int end = -1;
  2363. enum EXPRESSION_PATTERNS {
  2364. NOT_PARSED,
  2365. RGBA_PARAMETER, // Color(float,float,float) or Color(float,float,float,float)
  2366. COLOR_NAME, // Color.COLOR_NAME
  2367. } expression_pattern = NOT_PARSED;
  2368. for (int i = mouse_column; i < line.length(); i++) {
  2369. if (line[i] == '(') {
  2370. if (expression_pattern == NOT_PARSED) {
  2371. begin = i;
  2372. expression_pattern = RGBA_PARAMETER;
  2373. } else {
  2374. // Method call or '(' appearing twice.
  2375. expression_pattern = NOT_PARSED;
  2376. break;
  2377. }
  2378. } else if (expression_pattern == RGBA_PARAMETER && line[i] == ')' && end < 0) {
  2379. end = i + 1;
  2380. break;
  2381. } else if (expression_pattern == NOT_PARSED && line[i] == '.') {
  2382. begin = i;
  2383. expression_pattern = COLOR_NAME;
  2384. } else if (expression_pattern == COLOR_NAME && end < 0 && (line[i] == ' ' || line[i] == '\t')) {
  2385. // Including '.' and spaces.
  2386. continue;
  2387. } else if (expression_pattern == COLOR_NAME && !(line[i] == '_' || ('A' <= line[i] && line[i] <= 'Z'))) {
  2388. end = i;
  2389. break;
  2390. }
  2391. }
  2392. switch (expression_pattern) {
  2393. case RGBA_PARAMETER: {
  2394. color_args = line.substr(begin, end - begin);
  2395. String stripped = color_args.remove_chars(" \t()");
  2396. PackedFloat64Array color = stripped.split_floats(",");
  2397. if (color.size() > 2) {
  2398. float alpha = color.size() > 3 ? color[3] : 1.0f;
  2399. color_picker->set_pick_color(Color(color[0], color[1], color[2], alpha));
  2400. }
  2401. } break;
  2402. case COLOR_NAME: {
  2403. if (end < 0) {
  2404. end = line.length();
  2405. }
  2406. color_args = line.substr(begin, end - begin);
  2407. const String color_name = color_args.remove_chars(" \t.");
  2408. const int color_index = Color::find_named_color(color_name);
  2409. if (0 <= color_index) {
  2410. const Color color_constant = Color::get_named_color(color_index);
  2411. color_picker->set_pick_color(color_constant);
  2412. } else {
  2413. has_color = false;
  2414. }
  2415. } break;
  2416. default:
  2417. has_color = false;
  2418. break;
  2419. }
  2420. if (has_color) {
  2421. color_panel->set_position(get_screen_position() + local_pos);
  2422. color_position.y = begin;
  2423. color_position.z = end;
  2424. }
  2425. }
  2426. _make_context_menu(tx->has_selection(), has_color, foldable, open_docs, goto_definition, local_pos);
  2427. }
  2428. }
  2429. void ScriptTextEditor::_color_changed(const Color &p_color) {
  2430. String new_args;
  2431. const int decimals = 3;
  2432. if (p_color.a == 1.0f) {
  2433. new_args = String("(" + String::num(p_color.r, decimals) + ", " + String::num(p_color.g, decimals) + ", " + String::num(p_color.b, decimals) + ")");
  2434. } else {
  2435. new_args = String("(" + String::num(p_color.r, decimals) + ", " + String::num(p_color.g, decimals) + ", " + String::num(p_color.b, decimals) + ", " + String::num(p_color.a, decimals) + ")");
  2436. }
  2437. String line = code_editor->get_text_editor()->get_line(color_position.x);
  2438. String line_with_replaced_args = line.substr(0, color_position.y) + line.substr(color_position.y, color_position.z - color_position.y).replace(color_args, new_args) + line.substr(color_position.z);
  2439. color_args = new_args;
  2440. code_editor->get_text_editor()->begin_complex_operation();
  2441. code_editor->get_text_editor()->set_line(color_position.x, line_with_replaced_args);
  2442. code_editor->get_text_editor()->end_complex_operation();
  2443. }
  2444. void ScriptTextEditor::_prepare_edit_menu() {
  2445. const CodeEdit *tx = code_editor->get_text_editor();
  2446. PopupMenu *popup = edit_menu->get_popup();
  2447. popup->set_item_disabled(popup->get_item_index(EDIT_UNDO), !tx->has_undo());
  2448. popup->set_item_disabled(popup->get_item_index(EDIT_REDO), !tx->has_redo());
  2449. }
  2450. void ScriptTextEditor::_make_context_menu(bool p_selection, bool p_color, bool p_foldable, bool p_open_docs, bool p_goto_definition, Vector2 p_pos) {
  2451. context_menu->clear();
  2452. if (DisplayServer::get_singleton()->has_feature(DisplayServer::FEATURE_EMOJI_AND_SYMBOL_PICKER)) {
  2453. context_menu->add_item(TTRC("Emoji & Symbols"), EDIT_EMOJI_AND_SYMBOL);
  2454. context_menu->add_separator();
  2455. }
  2456. context_menu->add_shortcut(ED_GET_SHORTCUT("ui_undo"), EDIT_UNDO);
  2457. context_menu->add_shortcut(ED_GET_SHORTCUT("ui_redo"), EDIT_REDO);
  2458. context_menu->add_separator();
  2459. context_menu->add_shortcut(ED_GET_SHORTCUT("ui_cut"), EDIT_CUT);
  2460. context_menu->add_shortcut(ED_GET_SHORTCUT("ui_copy"), EDIT_COPY);
  2461. context_menu->add_shortcut(ED_GET_SHORTCUT("ui_paste"), EDIT_PASTE);
  2462. context_menu->add_separator();
  2463. context_menu->add_shortcut(ED_GET_SHORTCUT("ui_text_select_all"), EDIT_SELECT_ALL);
  2464. context_menu->add_separator();
  2465. context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/indent"), EDIT_INDENT);
  2466. context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/unindent"), EDIT_UNINDENT);
  2467. context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/toggle_comment"), EDIT_TOGGLE_COMMENT);
  2468. context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/toggle_bookmark"), BOOKMARK_TOGGLE);
  2469. if (p_selection) {
  2470. context_menu->add_separator();
  2471. context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/convert_to_uppercase"), EDIT_TO_UPPERCASE);
  2472. context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/convert_to_lowercase"), EDIT_TO_LOWERCASE);
  2473. context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/evaluate_selection"), EDIT_EVALUATE);
  2474. context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/create_code_region"), EDIT_CREATE_CODE_REGION);
  2475. }
  2476. if (p_foldable) {
  2477. context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/toggle_fold_line"), EDIT_TOGGLE_FOLD_LINE);
  2478. }
  2479. if (p_color || p_open_docs || p_goto_definition) {
  2480. context_menu->add_separator();
  2481. if (p_open_docs) {
  2482. context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/goto_symbol"), LOOKUP_SYMBOL);
  2483. }
  2484. if (p_color) {
  2485. context_menu->add_item(TTRC("Pick Color"), EDIT_PICK_COLOR);
  2486. }
  2487. }
  2488. const PackedStringArray paths = { String(code_editor->get_text_editor()->get_path()) };
  2489. EditorContextMenuPluginManager::get_singleton()->add_options_from_plugins(context_menu, EditorContextMenuPlugin::CONTEXT_SLOT_SCRIPT_EDITOR_CODE, paths);
  2490. const CodeEdit *tx = code_editor->get_text_editor();
  2491. context_menu->set_item_disabled(context_menu->get_item_index(EDIT_UNDO), !tx->has_undo());
  2492. context_menu->set_item_disabled(context_menu->get_item_index(EDIT_REDO), !tx->has_redo());
  2493. context_menu->set_position(get_screen_position() + p_pos);
  2494. context_menu->reset_size();
  2495. context_menu->popup();
  2496. }
  2497. void ScriptTextEditor::_enable_code_editor() {
  2498. ERR_FAIL_COND(code_editor->get_parent());
  2499. VSplitContainer *editor_box = memnew(VSplitContainer);
  2500. add_child(editor_box);
  2501. editor_box->set_anchors_and_offsets_preset(Control::PRESET_FULL_RECT);
  2502. editor_box->set_v_size_flags(SIZE_EXPAND_FILL);
  2503. editor_box->add_child(code_editor);
  2504. code_editor->connect("show_errors_panel", callable_mp(this, &ScriptTextEditor::_show_errors_panel));
  2505. code_editor->connect("show_warnings_panel", callable_mp(this, &ScriptTextEditor::_show_warnings_panel));
  2506. code_editor->connect("validate_script", callable_mp(this, &ScriptTextEditor::_validate_script));
  2507. code_editor->connect("load_theme_settings", callable_mp(this, &ScriptTextEditor::_load_theme_settings));
  2508. code_editor->get_text_editor()->connect("symbol_lookup", callable_mp(this, &ScriptTextEditor::_lookup_symbol));
  2509. code_editor->get_text_editor()->connect("symbol_hovered", callable_mp(this, &ScriptTextEditor::_show_symbol_tooltip));
  2510. code_editor->get_text_editor()->connect("symbol_validate", callable_mp(this, &ScriptTextEditor::_validate_symbol));
  2511. code_editor->get_text_editor()->connect("gutter_added", callable_mp(this, &ScriptTextEditor::_update_gutter_indexes));
  2512. code_editor->get_text_editor()->connect("gutter_removed", callable_mp(this, &ScriptTextEditor::_update_gutter_indexes));
  2513. code_editor->get_text_editor()->connect("gutter_clicked", callable_mp(this, &ScriptTextEditor::_gutter_clicked));
  2514. code_editor->get_text_editor()->connect("_fold_line_updated", callable_mp(this, &ScriptTextEditor::_update_background_color));
  2515. code_editor->get_text_editor()->connect(SceneStringName(gui_input), callable_mp(this, &ScriptTextEditor::_text_edit_gui_input));
  2516. code_editor->show_toggle_files_button();
  2517. _update_gutter_indexes();
  2518. editor_box->add_child(warnings_panel);
  2519. warnings_panel->connect("meta_clicked", callable_mp(this, &ScriptTextEditor::_warning_clicked));
  2520. editor_box->add_child(errors_panel);
  2521. errors_panel->connect("meta_clicked", callable_mp(this, &ScriptTextEditor::_error_clicked));
  2522. add_child(context_menu);
  2523. context_menu->connect(SceneStringName(id_pressed), callable_mp(this, &ScriptTextEditor::_edit_option));
  2524. add_child(color_panel);
  2525. color_picker = memnew(ColorPicker);
  2526. color_picker->set_deferred_mode(true);
  2527. color_picker->connect("color_changed", callable_mp(this, &ScriptTextEditor::_color_changed));
  2528. color_panel->connect("about_to_popup", callable_mp(EditorNode::get_singleton(), &EditorNode::setup_color_picker).bind(color_picker));
  2529. color_panel->add_child(color_picker);
  2530. quick_open = memnew(ScriptEditorQuickOpen);
  2531. quick_open->set_title(TTRC("Go to Function"));
  2532. quick_open->connect("goto_line", callable_mp(this, &ScriptTextEditor::_goto_line));
  2533. add_child(quick_open);
  2534. goto_line_popup = memnew(GotoLinePopup);
  2535. add_child(goto_line_popup);
  2536. add_child(connection_info_dialog);
  2537. edit_hb->add_child(edit_menu);
  2538. edit_menu->connect("about_to_popup", callable_mp(this, &ScriptTextEditor::_prepare_edit_menu));
  2539. edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("ui_undo"), EDIT_UNDO);
  2540. edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("ui_redo"), EDIT_REDO);
  2541. edit_menu->get_popup()->add_separator();
  2542. edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("ui_cut"), EDIT_CUT);
  2543. edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("ui_copy"), EDIT_COPY);
  2544. edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("ui_paste"), EDIT_PASTE);
  2545. edit_menu->get_popup()->add_separator();
  2546. edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("ui_text_select_all"), EDIT_SELECT_ALL);
  2547. edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/duplicate_selection"), EDIT_DUPLICATE_SELECTION);
  2548. edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/duplicate_lines"), EDIT_DUPLICATE_LINES);
  2549. edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/evaluate_selection"), EDIT_EVALUATE);
  2550. edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/toggle_word_wrap"), EDIT_TOGGLE_WORD_WRAP);
  2551. edit_menu->get_popup()->add_separator();
  2552. {
  2553. PopupMenu *sub_menu = memnew(PopupMenu);
  2554. sub_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/move_up"), EDIT_MOVE_LINE_UP);
  2555. sub_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/move_down"), EDIT_MOVE_LINE_DOWN);
  2556. sub_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/indent"), EDIT_INDENT);
  2557. sub_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/unindent"), EDIT_UNINDENT);
  2558. sub_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/delete_line"), EDIT_DELETE_LINE);
  2559. sub_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/toggle_comment"), EDIT_TOGGLE_COMMENT);
  2560. sub_menu->connect(SceneStringName(id_pressed), callable_mp(this, &ScriptTextEditor::_edit_option));
  2561. edit_menu->get_popup()->add_submenu_node_item(TTRC("Line"), sub_menu);
  2562. }
  2563. {
  2564. PopupMenu *sub_menu = memnew(PopupMenu);
  2565. sub_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/toggle_fold_line"), EDIT_TOGGLE_FOLD_LINE);
  2566. sub_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/fold_all_lines"), EDIT_FOLD_ALL_LINES);
  2567. sub_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/unfold_all_lines"), EDIT_UNFOLD_ALL_LINES);
  2568. sub_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/create_code_region"), EDIT_CREATE_CODE_REGION);
  2569. sub_menu->connect(SceneStringName(id_pressed), callable_mp(this, &ScriptTextEditor::_edit_option));
  2570. edit_menu->get_popup()->add_submenu_node_item(TTRC("Folding"), sub_menu);
  2571. }
  2572. edit_menu->get_popup()->add_separator();
  2573. edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("ui_text_completion_query"), EDIT_COMPLETE);
  2574. edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/trim_trailing_whitespace"), EDIT_TRIM_TRAILING_WHITESAPCE);
  2575. edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/trim_final_newlines"), EDIT_TRIM_FINAL_NEWLINES);
  2576. {
  2577. PopupMenu *sub_menu = memnew(PopupMenu);
  2578. sub_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/convert_indent_to_spaces"), EDIT_CONVERT_INDENT_TO_SPACES);
  2579. sub_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/convert_indent_to_tabs"), EDIT_CONVERT_INDENT_TO_TABS);
  2580. sub_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/auto_indent"), EDIT_AUTO_INDENT);
  2581. sub_menu->connect(SceneStringName(id_pressed), callable_mp(this, &ScriptTextEditor::_edit_option));
  2582. edit_menu->get_popup()->add_submenu_node_item(TTRC("Indentation"), sub_menu);
  2583. }
  2584. edit_menu->get_popup()->connect(SceneStringName(id_pressed), callable_mp(this, &ScriptTextEditor::_edit_option));
  2585. edit_menu->get_popup()->add_separator();
  2586. {
  2587. PopupMenu *sub_menu = memnew(PopupMenu);
  2588. sub_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/convert_to_uppercase"), EDIT_TO_UPPERCASE);
  2589. sub_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/convert_to_lowercase"), EDIT_TO_LOWERCASE);
  2590. sub_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/capitalize"), EDIT_CAPITALIZE);
  2591. sub_menu->connect(SceneStringName(id_pressed), callable_mp(this, &ScriptTextEditor::_edit_option));
  2592. edit_menu->get_popup()->add_submenu_node_item(TTRC("Convert Case"), sub_menu);
  2593. }
  2594. edit_menu->get_popup()->add_submenu_node_item(TTRC("Syntax Highlighter"), highlighter_menu);
  2595. highlighter_menu->connect(SceneStringName(id_pressed), callable_mp(this, &ScriptTextEditor::_change_syntax_highlighter));
  2596. edit_hb->add_child(search_menu);
  2597. search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/find"), SEARCH_FIND);
  2598. search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/find_next"), SEARCH_FIND_NEXT);
  2599. search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/find_previous"), SEARCH_FIND_PREV);
  2600. search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/replace"), SEARCH_REPLACE);
  2601. search_menu->get_popup()->add_separator();
  2602. search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("editor/find_in_files"), SEARCH_IN_FILES);
  2603. search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/replace_in_files"), REPLACE_IN_FILES);
  2604. search_menu->get_popup()->add_separator();
  2605. search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/contextual_help"), HELP_CONTEXTUAL);
  2606. search_menu->get_popup()->connect(SceneStringName(id_pressed), callable_mp(this, &ScriptTextEditor::_edit_option));
  2607. _load_theme_settings();
  2608. edit_hb->add_child(goto_menu);
  2609. goto_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/goto_function"), SEARCH_LOCATE_FUNCTION);
  2610. goto_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/goto_line"), SEARCH_GOTO_LINE);
  2611. goto_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/goto_symbol"), LOOKUP_SYMBOL);
  2612. goto_menu->get_popup()->add_separator();
  2613. goto_menu->get_popup()->add_submenu_node_item(TTRC("Bookmarks"), bookmarks_menu);
  2614. _update_bookmark_list();
  2615. bookmarks_menu->connect("about_to_popup", callable_mp(this, &ScriptTextEditor::_update_bookmark_list));
  2616. bookmarks_menu->connect("index_pressed", callable_mp(this, &ScriptTextEditor::_bookmark_item_pressed));
  2617. goto_menu->get_popup()->add_submenu_node_item(TTRC("Breakpoints"), breakpoints_menu);
  2618. _update_breakpoint_list();
  2619. breakpoints_menu->connect("about_to_popup", callable_mp(this, &ScriptTextEditor::_update_breakpoint_list));
  2620. breakpoints_menu->connect("index_pressed", callable_mp(this, &ScriptTextEditor::_breakpoint_item_pressed));
  2621. goto_menu->get_popup()->connect(SceneStringName(id_pressed), callable_mp(this, &ScriptTextEditor::_edit_option));
  2622. }
  2623. ScriptTextEditor::ScriptTextEditor() {
  2624. code_editor = memnew(CodeTextEditor);
  2625. code_editor->set_toggle_list_control(ScriptEditor::get_singleton()->get_left_list_split());
  2626. code_editor->add_theme_constant_override("separation", 2);
  2627. code_editor->set_anchors_and_offsets_preset(Control::PRESET_FULL_RECT);
  2628. code_editor->set_code_complete_func(_code_complete_scripts, this);
  2629. code_editor->set_v_size_flags(SIZE_EXPAND_FILL);
  2630. code_editor->get_text_editor()->set_draw_breakpoints_gutter(true);
  2631. code_editor->get_text_editor()->set_draw_executing_lines_gutter(true);
  2632. code_editor->get_text_editor()->connect("breakpoint_toggled", callable_mp(this, &ScriptTextEditor::_breakpoint_toggled));
  2633. code_editor->get_text_editor()->connect("caret_changed", callable_mp(this, &ScriptTextEditor::_on_caret_moved));
  2634. code_editor->connect("navigation_preview_ended", callable_mp(this, &ScriptTextEditor::_on_caret_moved));
  2635. connection_gutter = 1;
  2636. code_editor->get_text_editor()->add_gutter(connection_gutter);
  2637. code_editor->get_text_editor()->set_gutter_name(connection_gutter, "connection_gutter");
  2638. code_editor->get_text_editor()->set_gutter_draw(connection_gutter, false);
  2639. code_editor->get_text_editor()->set_gutter_overwritable(connection_gutter, true);
  2640. code_editor->get_text_editor()->set_gutter_type(connection_gutter, TextEdit::GUTTER_TYPE_ICON);
  2641. warnings_panel = memnew(RichTextLabel);
  2642. warnings_panel->set_custom_minimum_size(Size2(0, 100 * EDSCALE));
  2643. warnings_panel->set_h_size_flags(SIZE_EXPAND_FILL);
  2644. warnings_panel->set_meta_underline(true);
  2645. warnings_panel->set_selection_enabled(true);
  2646. warnings_panel->set_context_menu_enabled(true);
  2647. warnings_panel->set_focus_mode(FOCUS_CLICK);
  2648. warnings_panel->hide();
  2649. errors_panel = memnew(RichTextLabel);
  2650. errors_panel->set_custom_minimum_size(Size2(0, 100 * EDSCALE));
  2651. errors_panel->set_h_size_flags(SIZE_EXPAND_FILL);
  2652. errors_panel->set_meta_underline(true);
  2653. errors_panel->set_selection_enabled(true);
  2654. errors_panel->set_context_menu_enabled(true);
  2655. errors_panel->set_focus_mode(FOCUS_CLICK);
  2656. errors_panel->hide();
  2657. update_settings();
  2658. code_editor->get_text_editor()->set_symbol_lookup_on_click_enabled(true);
  2659. code_editor->get_text_editor()->set_symbol_tooltip_on_hover_enabled(true);
  2660. code_editor->get_text_editor()->set_context_menu_enabled(false);
  2661. context_menu = memnew(PopupMenu);
  2662. color_panel = memnew(PopupPanel);
  2663. edit_hb = memnew(HBoxContainer);
  2664. edit_menu = memnew(MenuButton);
  2665. edit_menu->set_flat(false);
  2666. edit_menu->set_theme_type_variation("FlatMenuButton");
  2667. edit_menu->set_text(TTRC("Edit"));
  2668. edit_menu->set_switch_on_hover(true);
  2669. edit_menu->set_shortcut_context(this);
  2670. highlighter_menu = memnew(PopupMenu);
  2671. Ref<EditorPlainTextSyntaxHighlighter> plain_highlighter;
  2672. plain_highlighter.instantiate();
  2673. add_syntax_highlighter(plain_highlighter);
  2674. Ref<EditorStandardSyntaxHighlighter> highlighter;
  2675. highlighter.instantiate();
  2676. add_syntax_highlighter(highlighter);
  2677. set_syntax_highlighter(highlighter);
  2678. search_menu = memnew(MenuButton);
  2679. search_menu->set_flat(false);
  2680. search_menu->set_theme_type_variation("FlatMenuButton");
  2681. search_menu->set_text(TTRC("Search"));
  2682. search_menu->set_switch_on_hover(true);
  2683. search_menu->set_shortcut_context(this);
  2684. goto_menu = memnew(MenuButton);
  2685. goto_menu->set_flat(false);
  2686. goto_menu->set_theme_type_variation("FlatMenuButton");
  2687. goto_menu->set_text(TTRC("Go To"));
  2688. goto_menu->set_switch_on_hover(true);
  2689. goto_menu->set_shortcut_context(this);
  2690. bookmarks_menu = memnew(PopupMenu);
  2691. breakpoints_menu = memnew(PopupMenu);
  2692. inline_color_popup = memnew(PopupPanel);
  2693. add_child(inline_color_popup);
  2694. inline_color_picker = memnew(ColorPicker);
  2695. inline_color_picker->set_mouse_filter(MOUSE_FILTER_STOP);
  2696. inline_color_picker->set_deferred_mode(true);
  2697. inline_color_picker->set_hex_visible(false);
  2698. inline_color_picker->connect("color_changed", callable_mp(this, &ScriptTextEditor::_picker_color_changed));
  2699. inline_color_popup->add_child(inline_color_picker);
  2700. inline_color_options = memnew(OptionButton);
  2701. inline_color_options->set_h_size_flags(SIZE_FILL);
  2702. inline_color_options->set_text_overrun_behavior(TextServer::OVERRUN_TRIM_ELLIPSIS);
  2703. inline_color_options->set_fit_to_longest_item(false);
  2704. inline_color_options->connect("item_selected", callable_mp(this, &ScriptTextEditor::_update_color_text).unbind(1));
  2705. inline_color_picker->get_slider_container()->add_sibling(inline_color_options);
  2706. connection_info_dialog = memnew(ConnectionInfoDialog);
  2707. SET_DRAG_FORWARDING_GCD(code_editor->get_text_editor(), ScriptTextEditor);
  2708. }
  2709. ScriptTextEditor::~ScriptTextEditor() {
  2710. highlighters.clear();
  2711. if (!editor_enabled) {
  2712. memdelete(code_editor);
  2713. memdelete(warnings_panel);
  2714. memdelete(errors_panel);
  2715. memdelete(context_menu);
  2716. memdelete(color_panel);
  2717. memdelete(edit_hb);
  2718. memdelete(edit_menu);
  2719. memdelete(highlighter_menu);
  2720. memdelete(search_menu);
  2721. memdelete(goto_menu);
  2722. memdelete(bookmarks_menu);
  2723. memdelete(breakpoints_menu);
  2724. memdelete(connection_info_dialog);
  2725. }
  2726. }
  2727. static ScriptEditorBase *create_editor(const Ref<Resource> &p_resource) {
  2728. if (Object::cast_to<Script>(*p_resource)) {
  2729. return memnew(ScriptTextEditor);
  2730. }
  2731. return nullptr;
  2732. }
  2733. void ScriptTextEditor::register_editor() {
  2734. ED_SHORTCUT("script_text_editor/move_up", TTRC("Move Up"), KeyModifierMask::ALT | Key::UP);
  2735. ED_SHORTCUT("script_text_editor/move_down", TTRC("Move Down"), KeyModifierMask::ALT | Key::DOWN);
  2736. ED_SHORTCUT("script_text_editor/delete_line", TTRC("Delete Line"), KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT | Key::K);
  2737. // Leave these at zero, same can be accomplished with tab/shift-tab, including selection.
  2738. // The next/previous in history shortcut in this case makes a lot more sense.
  2739. ED_SHORTCUT("script_text_editor/indent", TTRC("Indent"), Key::NONE);
  2740. ED_SHORTCUT("script_text_editor/unindent", TTRC("Unindent"), KeyModifierMask::SHIFT | Key::TAB);
  2741. ED_SHORTCUT_ARRAY("script_text_editor/toggle_comment", TTRC("Toggle Comment"), { int32_t(KeyModifierMask::CMD_OR_CTRL | Key::K), int32_t(KeyModifierMask::CMD_OR_CTRL | Key::SLASH), int32_t(KeyModifierMask::CMD_OR_CTRL | Key::KP_DIVIDE), int32_t(KeyModifierMask::CMD_OR_CTRL | Key::NUMBERSIGN) });
  2742. ED_SHORTCUT("script_text_editor/toggle_fold_line", TTRC("Fold/Unfold Line"), KeyModifierMask::ALT | Key::F);
  2743. ED_SHORTCUT_OVERRIDE("script_text_editor/toggle_fold_line", "macos", KeyModifierMask::CTRL | KeyModifierMask::META | Key::F);
  2744. ED_SHORTCUT("script_text_editor/fold_all_lines", TTRC("Fold All Lines"), Key::NONE);
  2745. ED_SHORTCUT("script_text_editor/create_code_region", TTRC("Create Code Region"), KeyModifierMask::ALT | Key::R);
  2746. ED_SHORTCUT("script_text_editor/unfold_all_lines", TTRC("Unfold All Lines"), Key::NONE);
  2747. ED_SHORTCUT("script_text_editor/duplicate_selection", TTRC("Duplicate Selection"), KeyModifierMask::SHIFT | KeyModifierMask::CTRL | Key::D);
  2748. ED_SHORTCUT_OVERRIDE("script_text_editor/duplicate_selection", "macos", KeyModifierMask::SHIFT | KeyModifierMask::META | Key::C);
  2749. ED_SHORTCUT("script_text_editor/duplicate_lines", TTRC("Duplicate Lines"), KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::ALT | Key::DOWN);
  2750. ED_SHORTCUT_OVERRIDE("script_text_editor/duplicate_lines", "macos", KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT | Key::DOWN);
  2751. ED_SHORTCUT("script_text_editor/evaluate_selection", TTRC("Evaluate Selection"), KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT | Key::E);
  2752. ED_SHORTCUT("script_text_editor/toggle_word_wrap", TTRC("Toggle Word Wrap"), KeyModifierMask::ALT | Key::Z);
  2753. ED_SHORTCUT("script_text_editor/trim_trailing_whitespace", TTRC("Trim Trailing Whitespace"), KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::ALT | Key::T);
  2754. ED_SHORTCUT("script_text_editor/trim_final_newlines", TTRC("Trim Final Newlines"), Key::NONE);
  2755. ED_SHORTCUT("script_text_editor/convert_indent_to_spaces", TTRC("Convert Indent to Spaces"), KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT | Key::Y);
  2756. ED_SHORTCUT("script_text_editor/convert_indent_to_tabs", TTRC("Convert Indent to Tabs"), KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT | Key::I);
  2757. ED_SHORTCUT("script_text_editor/auto_indent", TTRC("Auto Indent"), KeyModifierMask::CMD_OR_CTRL | Key::I);
  2758. ED_SHORTCUT_AND_COMMAND("script_text_editor/find", TTRC("Find..."), KeyModifierMask::CMD_OR_CTRL | Key::F);
  2759. ED_SHORTCUT("script_text_editor/find_next", TTRC("Find Next"), Key::F3);
  2760. ED_SHORTCUT_OVERRIDE("script_text_editor/find_next", "macos", KeyModifierMask::META | Key::G);
  2761. ED_SHORTCUT("script_text_editor/find_previous", TTRC("Find Previous"), KeyModifierMask::SHIFT | Key::F3);
  2762. ED_SHORTCUT_OVERRIDE("script_text_editor/find_previous", "macos", KeyModifierMask::META | KeyModifierMask::SHIFT | Key::G);
  2763. ED_SHORTCUT_AND_COMMAND("script_text_editor/replace", TTRC("Replace..."), KeyModifierMask::CTRL | Key::R);
  2764. ED_SHORTCUT_OVERRIDE("script_text_editor/replace", "macos", KeyModifierMask::ALT | KeyModifierMask::META | Key::F);
  2765. ED_SHORTCUT("script_text_editor/replace_in_files", TTRC("Replace in Files..."), KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT | Key::R);
  2766. ED_SHORTCUT("script_text_editor/contextual_help", TTRC("Contextual Help"), KeyModifierMask::ALT | Key::F1);
  2767. ED_SHORTCUT_OVERRIDE("script_text_editor/contextual_help", "macos", KeyModifierMask::ALT | KeyModifierMask::SHIFT | Key::SPACE);
  2768. ED_SHORTCUT("script_text_editor/toggle_bookmark", TTRC("Toggle Bookmark"), KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::ALT | Key::B);
  2769. ED_SHORTCUT("script_text_editor/goto_next_bookmark", TTRC("Go to Next Bookmark"), KeyModifierMask::CMD_OR_CTRL | Key::B);
  2770. ED_SHORTCUT_OVERRIDE("script_text_editor/goto_next_bookmark", "macos", KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT | KeyModifierMask::ALT | Key::B);
  2771. ED_SHORTCUT("script_text_editor/goto_previous_bookmark", TTRC("Go to Previous Bookmark"), KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT | Key::B);
  2772. ED_SHORTCUT("script_text_editor/remove_all_bookmarks", TTRC("Remove All Bookmarks"), Key::NONE);
  2773. ED_SHORTCUT("script_text_editor/goto_function", TTRC("Go to Function..."), KeyModifierMask::ALT | KeyModifierMask::CTRL | Key::F);
  2774. ED_SHORTCUT_OVERRIDE("script_text_editor/goto_function", "macos", KeyModifierMask::CTRL | KeyModifierMask::META | Key::J);
  2775. ED_SHORTCUT("script_text_editor/goto_line", TTRC("Go to Line..."), KeyModifierMask::CMD_OR_CTRL | Key::G);
  2776. ED_SHORTCUT_OVERRIDE("script_text_editor/goto_line", "macos", KeyModifierMask::CMD_OR_CTRL | Key::L);
  2777. ED_SHORTCUT("script_text_editor/goto_symbol", TTRC("Lookup Symbol"));
  2778. ED_SHORTCUT("script_text_editor/toggle_breakpoint", TTRC("Toggle Breakpoint"), Key::F9);
  2779. ED_SHORTCUT_OVERRIDE("script_text_editor/toggle_breakpoint", "macos", KeyModifierMask::META | KeyModifierMask::SHIFT | Key::B);
  2780. ED_SHORTCUT("script_text_editor/remove_all_breakpoints", TTRC("Remove All Breakpoints"), KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT | Key::F9);
  2781. // Using Control for these shortcuts even on macOS because Command+Comma is taken for opening Editor Settings.
  2782. ED_SHORTCUT("script_text_editor/goto_next_breakpoint", TTRC("Go to Next Breakpoint"), KeyModifierMask::CTRL | Key::PERIOD);
  2783. ED_SHORTCUT("script_text_editor/goto_previous_breakpoint", TTRC("Go to Previous Breakpoint"), KeyModifierMask::CTRL | Key::COMMA);
  2784. ScriptEditor::register_create_script_editor_function(create_editor);
  2785. }
  2786. void ScriptTextEditor::validate() {
  2787. code_editor->validate_script();
  2788. }