script_text_editor.cpp 117 KB

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