script_text_editor.cpp 117 KB

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