script_text_editor.cpp 118 KB

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