TextEditor.cpp 93 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637
  1. /*
  2. * Copyright (c) 2018-2023, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, networkException <networkexception@serenityos.org>
  4. * Copyright (c) 2022, the SerenityOS developers.
  5. * Copyright (c) 2023, Sam Atkins <atkinssj@serenityos.org>
  6. *
  7. * SPDX-License-Identifier: BSD-2-Clause
  8. */
  9. #include <AK/CharacterTypes.h>
  10. #include <AK/Debug.h>
  11. #include <AK/ScopeGuard.h>
  12. #include <AK/StringBuilder.h>
  13. #include <AK/TemporaryChange.h>
  14. #include <LibCore/Timer.h>
  15. #include <LibGUI/Action.h>
  16. #include <LibGUI/AutocompleteProvider.h>
  17. #include <LibGUI/Clipboard.h>
  18. #include <LibGUI/EditingEngine.h>
  19. #include <LibGUI/EmojiInputDialog.h>
  20. #include <LibGUI/IncrementalSearchBanner.h>
  21. #include <LibGUI/InputBox.h>
  22. #include <LibGUI/Menu.h>
  23. #include <LibGUI/Painter.h>
  24. #include <LibGUI/RegularEditingEngine.h>
  25. #include <LibGUI/Scrollbar.h>
  26. #include <LibGUI/TextEditor.h>
  27. #include <LibGUI/Window.h>
  28. #include <LibGfx/Bitmap.h>
  29. #include <LibGfx/Font/Font.h>
  30. #include <LibGfx/Font/FontDatabase.h>
  31. #include <LibGfx/Palette.h>
  32. #include <LibGfx/StandardCursor.h>
  33. #include <LibSyntax/Highlighter.h>
  34. #include <LibUnicode/Segmentation.h>
  35. #include <fcntl.h>
  36. #include <stdio.h>
  37. #include <unistd.h>
  38. REGISTER_WIDGET(GUI, TextEditor)
  39. namespace GUI {
  40. static constexpr StringView folded_region_summary_text = " ..."sv;
  41. TextEditor::TextEditor(Type type)
  42. : m_type(type)
  43. {
  44. REGISTER_DEPRECATED_STRING_PROPERTY("text", text, set_text);
  45. REGISTER_DEPRECATED_STRING_PROPERTY("placeholder", placeholder, set_placeholder);
  46. REGISTER_BOOL_PROPERTY("gutter", is_gutter_visible, set_gutter_visible);
  47. REGISTER_BOOL_PROPERTY("ruler", is_ruler_visible, set_ruler_visible);
  48. REGISTER_ENUM_PROPERTY("mode", mode, set_mode, Mode,
  49. { Editable, "Editable" },
  50. { ReadOnly, "ReadOnly" },
  51. { DisplayOnly, "DisplayOnly" });
  52. set_focus_policy(GUI::FocusPolicy::StrongFocus);
  53. set_or_clear_emoji_input_callback();
  54. set_override_cursor(Gfx::StandardCursor::IBeam);
  55. set_background_role(ColorRole::Base);
  56. set_foreground_role(ColorRole::BaseText);
  57. set_document(TextDocument::create());
  58. if (is_single_line())
  59. set_visualize_trailing_whitespace(false);
  60. set_scrollbars_enabled(is_multi_line());
  61. if (is_multi_line()) {
  62. set_font(Gfx::FontDatabase::default_fixed_width_font());
  63. set_wrapping_mode(WrappingMode::WrapAtWords);
  64. m_search_banner = GUI::IncrementalSearchBanner::construct(*this);
  65. set_banner_widget(m_search_banner);
  66. }
  67. vertical_scrollbar().set_step(line_height());
  68. m_cursor = { 0, 0 };
  69. create_actions();
  70. set_editing_engine(make<RegularEditingEngine>());
  71. }
  72. TextEditor::~TextEditor()
  73. {
  74. if (m_document)
  75. m_document->unregister_client(*this);
  76. }
  77. void TextEditor::create_actions()
  78. {
  79. m_undo_action = CommonActions::make_undo_action([&](auto&) { undo(); }, this);
  80. m_redo_action = CommonActions::make_redo_action([&](auto&) { redo(); }, this);
  81. m_undo_action->set_enabled(false);
  82. m_redo_action->set_enabled(false);
  83. m_cut_action = CommonActions::make_cut_action([&](auto&) { cut(); }, this);
  84. m_copy_action = CommonActions::make_copy_action([&](auto&) { copy(); }, this);
  85. m_cut_action->set_enabled(false);
  86. m_copy_action->set_enabled(false);
  87. m_paste_action = CommonActions::make_paste_action([&](auto&) { paste(); }, this);
  88. m_paste_action->set_enabled(is_editable() && Clipboard::the().fetch_mime_type().starts_with("text/"sv));
  89. if (is_multi_line()) {
  90. m_go_to_line_or_column_action = Action::create(
  91. "Go to Line/Column...", { Mod_Ctrl, Key_L }, Gfx::Bitmap::load_from_file("/res/icons/16x16/go-to.png"sv).release_value_but_fixme_should_propagate_errors(), [this](auto&) {
  92. String value;
  93. if (InputBox::show(window(), value, "Enter the line, or line:column:"sv, "Go to Line/Column"sv) == InputBox::ExecResult::OK) {
  94. // If there is a `:` in the string, the format is expected to be `line:column`. E.g: `123:45`
  95. if (value.contains(':')) {
  96. auto line_and_column_or_error = value.split(':');
  97. if (line_and_column_or_error.is_error()) {
  98. return;
  99. }
  100. auto line_and_column = line_and_column_or_error.value();
  101. if (line_and_column.size() != 2) {
  102. return;
  103. }
  104. auto line_target = AK::StringUtils::convert_to_uint(line_and_column.at(0));
  105. auto column_target = AK::StringUtils::convert_to_uint(line_and_column.at(1));
  106. if (line_target.has_value() && column_target.has_value()) {
  107. set_cursor_and_focus_line(line_target.value() - 1, column_target.value());
  108. }
  109. return;
  110. }
  111. // If there is no `:` in the string, we just treat the integer as the line
  112. auto line_target = AK::StringUtils::convert_to_uint(value.bytes_as_string_view());
  113. if (line_target.has_value()) {
  114. set_cursor_and_focus_line(line_target.value() - 1, 0);
  115. }
  116. }
  117. },
  118. this);
  119. }
  120. m_select_all_action = CommonActions::make_select_all_action([this](auto&) { select_all(); }, this);
  121. m_insert_emoji_action = CommonActions::make_insert_emoji_action([&](auto&) { insert_emoji(); }, this);
  122. }
  123. void TextEditor::set_text(StringView text, AllowCallback allow_callback)
  124. {
  125. m_selection.clear();
  126. document().set_text(text, allow_callback);
  127. update_content_size();
  128. recompute_all_visual_lines();
  129. if (is_single_line())
  130. set_cursor(0, line(0).length());
  131. else
  132. set_cursor(0, 0);
  133. did_update_selection();
  134. update();
  135. }
  136. void TextEditor::update_content_size()
  137. {
  138. int content_width = 0;
  139. int content_height = 0;
  140. for (auto& line : m_line_data) {
  141. content_width = max(line->visual_rect.width(), content_width);
  142. content_height += line->visual_rect.height();
  143. }
  144. content_width += m_horizontal_content_padding * 2;
  145. if (is_right_text_alignment(m_text_alignment))
  146. content_width = max(frame_inner_rect().width(), content_width);
  147. set_content_size({ content_width, content_height });
  148. set_size_occupied_by_fixed_elements({ fixed_elements_width(), 0 });
  149. }
  150. TextPosition TextEditor::text_position_at_content_position(Gfx::IntPoint content_position) const
  151. {
  152. auto position = content_position;
  153. if (is_single_line() && icon())
  154. position.translate_by(-(icon_size() + icon_padding()), 0);
  155. size_t line_index = 0;
  156. if (position.y() >= 0) {
  157. size_t last_visible_line_index = 0;
  158. // FIXME: Oh boy is this a slow way of calculating this!
  159. // NOTE: Offset by 1 in calculations is because we can't do `i >= 0` with an unsigned type.
  160. for (size_t i = line_count(); i > 0; --i) {
  161. if (document().line_is_visible(i - 1)) {
  162. last_visible_line_index = i - 1;
  163. break;
  164. }
  165. }
  166. for (size_t i = 0; i < line_count(); ++i) {
  167. if (!document().line_is_visible(i))
  168. continue;
  169. auto& rect = m_line_data[i]->visual_rect;
  170. if (rect.contains_vertically(position.y())) {
  171. line_index = i;
  172. break;
  173. }
  174. if (position.y() >= rect.bottom())
  175. line_index = last_visible_line_index;
  176. }
  177. line_index = max((size_t)0, min(line_index, last_visible_line_index));
  178. }
  179. size_t column_index = 0;
  180. switch (m_text_alignment) {
  181. case Gfx::TextAlignment::CenterLeft:
  182. for_each_visual_line(line_index, [&](Gfx::IntRect const& rect, auto& view, size_t start_of_line, [[maybe_unused]] bool is_last_visual_line) {
  183. if (is_multi_line() && !rect.contains_vertically(position.y()) && !is_last_visual_line && position.y() >= 0)
  184. return IterationDecision::Continue;
  185. column_index = start_of_line;
  186. int glyph_x = 0;
  187. if (position.x() <= 0) {
  188. // We're outside the text on the left side, put cursor at column 0 on this visual line.
  189. return IterationDecision::Break;
  190. }
  191. for (auto it = view.begin(); it != view.end(); ++it, ++column_index) {
  192. int advance = font().glyph_or_emoji_width(it) + font().glyph_spacing();
  193. if ((glyph_x + (advance / 2)) >= position.x())
  194. break;
  195. glyph_x += advance;
  196. }
  197. return IterationDecision::Break;
  198. });
  199. break;
  200. case Gfx::TextAlignment::CenterRight:
  201. // FIXME: Support right-aligned line wrapping, I guess.
  202. VERIFY(!is_wrapping_enabled());
  203. column_index = (position.x() - content_x_for_position({ line_index, 0 }) + fixed_glyph_width() / 2) / fixed_glyph_width();
  204. break;
  205. default:
  206. VERIFY_NOT_REACHED();
  207. }
  208. column_index = max((size_t)0, min(column_index, line(line_index).length()));
  209. return { line_index, column_index };
  210. }
  211. TextPosition TextEditor::text_position_at(Gfx::IntPoint widget_position) const
  212. {
  213. auto content_position = widget_position;
  214. content_position.translate_by(horizontal_scrollbar().value(), vertical_scrollbar().value());
  215. content_position.translate_by(-(m_horizontal_content_padding + fixed_elements_width()), 0);
  216. content_position.translate_by(-frame_thickness(), -frame_thickness());
  217. content_position.translate_by(0, -height_occupied_by_banner_widget());
  218. return text_position_at_content_position(content_position);
  219. }
  220. void TextEditor::doubleclick_event(MouseEvent& event)
  221. {
  222. if (event.button() != MouseButton::Primary)
  223. return;
  224. if (is_displayonly())
  225. return;
  226. if (!current_line().can_select())
  227. return;
  228. rehighlight_if_needed();
  229. m_triple_click_timer.start();
  230. m_in_drag_select = false;
  231. auto position = text_position_at(event.position());
  232. if (m_substitution_code_point.has_value()) {
  233. // NOTE: If we substitute the code points, we don't want double clicking to only select a single word, since
  234. // whitespace isn't visible anymore.
  235. m_selection = document().range_for_entire_line(position.line());
  236. } else if (document().has_spans()) {
  237. for (auto& span : document().spans()) {
  238. if (span.range.contains(position)) {
  239. m_selection = span.range;
  240. break;
  241. }
  242. }
  243. } else {
  244. m_selection.set_start(document().first_word_break_before(position, false));
  245. m_selection.set_end(document().first_word_break_after(position));
  246. }
  247. set_cursor(m_selection.end());
  248. update();
  249. did_update_selection();
  250. }
  251. void TextEditor::mousedown_event(MouseEvent& event)
  252. {
  253. using namespace AK::TimeLiterals;
  254. if (event.button() != MouseButton::Primary) {
  255. return;
  256. }
  257. auto text_position = text_position_at(event.position());
  258. if (event.modifiers() == 0 && folding_indicator_rect(text_position.line()).contains(event.position())) {
  259. if (auto folding_region = document().folding_region_starting_on_line(text_position.line()); folding_region.has_value()) {
  260. folding_region->is_folded = !folding_region->is_folded;
  261. dbgln_if(TEXTEDITOR_DEBUG, "TextEditor: {} region {}.", folding_region->is_folded ? "Folding"sv : "Unfolding"sv, folding_region->range);
  262. if (folding_region->is_folded && folding_region->range.contains(cursor())) {
  263. // Cursor is now within a hidden range, so move it outside.
  264. set_cursor(folding_region->range.start());
  265. }
  266. recompute_all_visual_lines();
  267. update();
  268. return;
  269. }
  270. }
  271. if (gutter_content_rect(text_position.line()).contains(event.position())) {
  272. auto& gutter_indicators = m_line_data[text_position.line()]->gutter_indicators;
  273. auto indicator_position = 0;
  274. for (auto i = 0u; i < m_gutter_indicators.size(); ++i) {
  275. if ((gutter_indicators & (1 << i)) == 0)
  276. continue;
  277. if (gutter_indicator_rect(text_position.line(), indicator_position).contains(event.position())) {
  278. auto& indicator_data = m_gutter_indicators[i];
  279. if (indicator_data.on_click)
  280. indicator_data.on_click(text_position.line(), event.modifiers());
  281. return;
  282. }
  283. indicator_position++;
  284. }
  285. // We didn't click on an indicator
  286. if (on_gutter_click)
  287. on_gutter_click(text_position.line(), event.modifiers());
  288. return;
  289. }
  290. if (on_mousedown)
  291. on_mousedown();
  292. if (is_displayonly())
  293. return;
  294. if (m_triple_click_timer.is_valid() && m_triple_click_timer.elapsed_time() < 250_ms) {
  295. m_triple_click_timer = Core::ElapsedTimer();
  296. select_current_line();
  297. return;
  298. }
  299. if (event.modifiers() & Mod_Shift) {
  300. if (!has_selection())
  301. m_selection.set(m_cursor, {});
  302. } else {
  303. m_selection.clear();
  304. }
  305. m_in_drag_select = true;
  306. set_cursor_to_text_position(event.position());
  307. if (!(event.modifiers() & Mod_Shift)) {
  308. if (!has_selection())
  309. m_selection.set(m_cursor, {});
  310. }
  311. if (m_selection.start().is_valid() && m_selection.start() != m_cursor)
  312. m_selection.set_end(m_cursor);
  313. // FIXME: Only update the relevant rects.
  314. update();
  315. did_update_selection();
  316. }
  317. void TextEditor::mouseup_event(MouseEvent& event)
  318. {
  319. if (event.button() == MouseButton::Primary) {
  320. if (m_in_drag_select) {
  321. m_in_drag_select = false;
  322. }
  323. return;
  324. }
  325. }
  326. void TextEditor::mousemove_event(MouseEvent& event)
  327. {
  328. m_last_mousemove_position = event.position();
  329. if (m_in_drag_select) {
  330. auto constrained = event.position().constrained(widget_inner_rect());
  331. set_cursor_to_text_position(constrained);
  332. m_selection.set_end(m_cursor);
  333. did_update_selection();
  334. update();
  335. return;
  336. }
  337. if (m_ruler_visible && ruler_rect_in_inner_coordinates().contains(event.position())) {
  338. set_override_cursor(Gfx::StandardCursor::None);
  339. } else if (m_ruler_visible && folding_indicator_rect_in_inner_coordinates().contains(event.position())) {
  340. auto text_position = text_position_at(event.position());
  341. if (document().folding_region_starting_on_line(text_position.line()).has_value()
  342. && folding_indicator_rect(text_position.line()).contains(event.position())) {
  343. set_override_cursor(Gfx::StandardCursor::Hand);
  344. } else {
  345. set_override_cursor(Gfx::StandardCursor::None);
  346. }
  347. } else if (m_gutter_visible && gutter_rect_in_inner_coordinates().contains(event.position())) {
  348. set_override_cursor(Gfx::StandardCursor::None);
  349. } else {
  350. set_editing_cursor();
  351. }
  352. }
  353. void TextEditor::select_current_line()
  354. {
  355. m_selection = document().range_for_entire_line(m_cursor.line());
  356. set_cursor(m_selection.end());
  357. update();
  358. did_update_selection();
  359. }
  360. void TextEditor::automatic_scrolling_timer_did_fire()
  361. {
  362. if (!m_in_drag_select) {
  363. set_automatic_scrolling_timer_active(false);
  364. return;
  365. }
  366. set_cursor_to_text_position(m_last_mousemove_position);
  367. m_selection.set_end(m_cursor);
  368. did_update_selection();
  369. update();
  370. }
  371. int TextEditor::folding_indicator_width() const
  372. {
  373. return document().has_folding_regions() ? line_height() : 0;
  374. }
  375. int TextEditor::ruler_width() const
  376. {
  377. if (!m_ruler_visible)
  378. return 0;
  379. int line_count_digits = static_cast<int>(log10(line_count())) + 1;
  380. auto padding = 5 + (font().is_fixed_width() ? 1 : (line_count_digits - (line_count() < 10 ? -1 : 0)));
  381. auto widest_numeral = font().bold_variant().glyph_width('4');
  382. return line_count() < 10 ? (line_count_digits + 1) * widest_numeral + padding : line_count_digits * widest_numeral + padding;
  383. }
  384. int TextEditor::gutter_width() const
  385. {
  386. if (!m_gutter_visible)
  387. return 0;
  388. return line_height() * (m_most_gutter_indicators_displayed_on_one_line + 1);
  389. }
  390. Gfx::IntRect TextEditor::gutter_content_rect(size_t line_index) const
  391. {
  392. if (!m_gutter_visible)
  393. return {};
  394. return {
  395. 0,
  396. line_content_rect(line_index).y() - vertical_scrollbar().value(),
  397. gutter_width(),
  398. line_content_rect(line_index).height()
  399. };
  400. }
  401. Gfx::IntRect TextEditor::ruler_content_rect(size_t line_index) const
  402. {
  403. if (!m_ruler_visible)
  404. return {};
  405. return {
  406. gutter_width(),
  407. line_content_rect(line_index).y() - vertical_scrollbar().value(),
  408. ruler_width(),
  409. line_content_rect(line_index).height()
  410. };
  411. }
  412. Gfx::IntRect TextEditor::folding_indicator_rect(size_t line_index) const
  413. {
  414. if (!m_ruler_visible || !document().has_folding_regions())
  415. return {};
  416. return {
  417. gutter_width() + ruler_width(),
  418. line_content_rect(line_index).y() - vertical_scrollbar().value(),
  419. folding_indicator_width(),
  420. line_content_rect(line_index).height()
  421. };
  422. }
  423. Gfx::IntRect TextEditor::gutter_indicator_rect(size_t line_number, int indicator_position) const
  424. {
  425. auto gutter_rect = gutter_content_rect(line_number);
  426. auto indicator_size = gutter_rect.height();
  427. return Gfx::IntRect {
  428. gutter_rect.right() - 1 - static_cast<int>(lroundf(indicator_size * (indicator_position + 1.5f))),
  429. gutter_rect.top(),
  430. indicator_size,
  431. indicator_size
  432. };
  433. }
  434. Gfx::IntRect TextEditor::gutter_rect_in_inner_coordinates() const
  435. {
  436. return { 0, 0, gutter_width(), widget_inner_rect().height() };
  437. }
  438. Gfx::IntRect TextEditor::ruler_rect_in_inner_coordinates() const
  439. {
  440. return { gutter_width(), 0, ruler_width(), widget_inner_rect().height() };
  441. }
  442. Gfx::IntRect TextEditor::folding_indicator_rect_in_inner_coordinates() const
  443. {
  444. return { gutter_width() + ruler_width(), 0, folding_indicator_width(), widget_inner_rect().height() };
  445. }
  446. Gfx::IntRect TextEditor::visible_text_rect_in_inner_coordinates() const
  447. {
  448. return {
  449. m_horizontal_content_padding + fixed_elements_width(),
  450. 0,
  451. frame_inner_rect().width() - (m_horizontal_content_padding * 2) - width_occupied_by_vertical_scrollbar() - fixed_elements_width(),
  452. frame_inner_rect().height() - height_occupied_by_horizontal_scrollbar()
  453. };
  454. }
  455. void TextEditor::paint_event(PaintEvent& event)
  456. {
  457. Color widget_background_color = palette().color(is_enabled() ? background_role() : Gfx::ColorRole::Window);
  458. rehighlight_if_needed();
  459. Frame::paint_event(event);
  460. Painter painter(*this);
  461. painter.add_clip_rect(widget_inner_rect());
  462. painter.add_clip_rect(event.rect());
  463. painter.fill_rect(event.rect(), widget_background_color);
  464. Gfx::TextAttributes unspanned_text_attributes;
  465. if (is_displayonly() && is_focused()) {
  466. unspanned_text_attributes.color = palette().color(is_enabled() ? Gfx::ColorRole::SelectionText : Gfx::ColorRole::DisabledText);
  467. } else {
  468. unspanned_text_attributes.color = palette().color(is_enabled() ? foreground_role() : Gfx::ColorRole::DisabledText);
  469. }
  470. auto& folded_region_summary_font = font().bold_variant();
  471. Gfx::TextAttributes folded_region_summary_attributes { palette().color(Gfx::ColorRole::SyntaxComment) };
  472. // NOTE: This lambda and TextEditor::text_width_for_font() are used to substitute all glyphs with m_substitution_code_point if necessary.
  473. // Painter::draw_text() and Gfx::Font::width() should not be called directly, but using this lambda and TextEditor::text_width_for_font().
  474. auto draw_text = [&](auto const& rect, auto const& raw_text, Gfx::Font const& font, Gfx::TextAlignment alignment, Gfx::TextAttributes attributes, bool substitute = true) {
  475. if (m_substitution_code_point.has_value() && substitute) {
  476. painter.draw_text(rect, substitution_code_point_view(raw_text.length()), font, alignment, attributes.color);
  477. } else {
  478. painter.draw_text(rect, raw_text, font, alignment, attributes.color);
  479. }
  480. if (attributes.underline_style.has_value()) {
  481. auto bottom_left = [&]() {
  482. auto point = rect.bottom_left();
  483. if constexpr (IsSame<RemoveCVReference<decltype(rect)>, Gfx::IntRect>)
  484. return point;
  485. else
  486. return point.template to_type<int>();
  487. };
  488. auto bottom_right = [&]() {
  489. auto point = rect.bottom_right().translated(-1, 0);
  490. if constexpr (IsSame<RemoveCVReference<decltype(rect)>, Gfx::IntRect>)
  491. return point;
  492. else
  493. return point.template to_type<int>();
  494. };
  495. if (attributes.underline_style == Gfx::TextAttributes::UnderlineStyle::Solid)
  496. painter.draw_line(bottom_left(), bottom_right(), attributes.underline_color.value_or(attributes.color));
  497. if (attributes.underline_style == Gfx::TextAttributes::UnderlineStyle::Wavy)
  498. painter.draw_triangle_wave(bottom_left(), bottom_right(), attributes.underline_color.value_or(attributes.color), 2);
  499. }
  500. };
  501. if (is_displayonly() && is_focused()) {
  502. Gfx::IntRect display_rect {
  503. widget_inner_rect().x() + 1,
  504. widget_inner_rect().y() + 1,
  505. widget_inner_rect().width() - 2,
  506. widget_inner_rect().height() - 2
  507. };
  508. painter.fill_rect(display_rect, palette().selection());
  509. }
  510. painter.translate(frame_thickness(), frame_thickness());
  511. painter.translate(0, height_occupied_by_banner_widget());
  512. if (!is_multi_line() && m_icon) {
  513. Gfx::IntRect icon_rect { icon_padding(), 1, icon_size(), icon_size() };
  514. painter.draw_scaled_bitmap(icon_rect, *m_icon, m_icon->rect());
  515. }
  516. if (m_gutter_visible) {
  517. auto gutter_rect = gutter_rect_in_inner_coordinates();
  518. painter.fill_rect(gutter_rect, palette().gutter());
  519. if (!m_ruler_visible)
  520. painter.draw_line(gutter_rect.top_right().translated(-1, 0), gutter_rect.bottom_right().translated(-1), palette().gutter_border());
  521. }
  522. if (m_ruler_visible) {
  523. auto ruler_rect = ruler_rect_in_inner_coordinates().inflated(0, folding_indicator_width(), 0, 0);
  524. painter.fill_rect(ruler_rect, palette().ruler());
  525. painter.draw_line(ruler_rect.top_right().translated(-1, 0), ruler_rect.bottom_right().translated(-1), palette().ruler_border());
  526. // Paint +/- buttons for folding regions
  527. for (auto const& folding_region : document().folding_regions()) {
  528. auto start_line = folding_region.range.start().line();
  529. if (!document().line_is_visible(start_line))
  530. continue;
  531. auto fold_indicator_rect = folding_indicator_rect(start_line).shrunken(4, 4);
  532. fold_indicator_rect.set_height(fold_indicator_rect.width());
  533. painter.draw_rect(fold_indicator_rect, palette().ruler_inactive_text());
  534. auto fold_symbol = folding_region.is_folded ? "+"sv : "-"sv;
  535. painter.draw_text(fold_indicator_rect, fold_symbol, font(), Gfx::TextAlignment::Center, palette().ruler_inactive_text());
  536. }
  537. }
  538. size_t first_visible_line = text_position_at(event.rect().top_left()).line();
  539. size_t last_visible_line = text_position_at(event.rect().bottom_right().translated(-1)).line();
  540. auto selection = normalized_selection();
  541. bool has_selection = selection.is_valid();
  542. if (m_ruler_visible) {
  543. for (size_t i = first_visible_line; i <= last_visible_line; ++i) {
  544. if (!document().line_is_visible(i))
  545. continue;
  546. bool is_current_line = i == m_cursor.line();
  547. auto ruler_line_rect = ruler_content_rect(i);
  548. // NOTE: Shrink the rectangle to be only on the first visual line.
  549. auto const line_height = font().preferred_line_height();
  550. if (ruler_line_rect.height() > line_height)
  551. ruler_line_rect.set_height(line_height);
  552. // NOTE: Use Painter::draw_text() directly here, as we want to always draw the line numbers in clear text.
  553. size_t const line_number = is_relative_line_number() && !is_current_line ? max(i, m_cursor.line()) - min(i, m_cursor.line()) : i + 1;
  554. painter.draw_text(
  555. ruler_line_rect.shrunken(2, 0),
  556. DeprecatedString::number(line_number),
  557. is_current_line ? font().bold_variant() : font(),
  558. Gfx::TextAlignment::CenterRight,
  559. is_current_line ? palette().ruler_active_text() : palette().ruler_inactive_text());
  560. }
  561. }
  562. // Draw gutter indicators
  563. if (m_gutter_visible) {
  564. for (size_t line_index = first_visible_line; line_index <= last_visible_line; ++line_index) {
  565. if (!document().line_is_visible(line_index))
  566. continue;
  567. auto& gutter_indicators = m_line_data[line_index]->gutter_indicators;
  568. if (gutter_indicators == 0)
  569. continue;
  570. auto indicator_position = 0;
  571. for (auto i = 0u; i < m_gutter_indicators.size(); ++i) {
  572. if ((gutter_indicators & (1 << i)) == 0)
  573. continue;
  574. auto rect = gutter_indicator_rect(line_index, indicator_position);
  575. m_gutter_indicators[i].draw_indicator(painter, rect, line_index);
  576. indicator_position++;
  577. }
  578. }
  579. }
  580. auto horizontal_scrollbar_value = horizontal_scrollbar().value();
  581. painter.translate(-horizontal_scrollbar_value, -vertical_scrollbar().value());
  582. if (m_icon && horizontal_scrollbar_value > 0)
  583. painter.translate(min(icon_size() + icon_padding(), horizontal_scrollbar_value), 0);
  584. auto gutter_ruler_width = fixed_elements_width();
  585. painter.translate(gutter_ruler_width, 0);
  586. Gfx::IntRect text_clip_rect { 0, 0, widget_inner_rect().width() - gutter_ruler_width, widget_inner_rect().height() };
  587. text_clip_rect.translate_by(horizontal_scrollbar().value(), vertical_scrollbar().value());
  588. painter.add_clip_rect(text_clip_rect);
  589. size_t span_index = 0;
  590. if (document().has_spans()) {
  591. for (;;) {
  592. if (span_index >= document().spans().size() || document().spans()[span_index].range.end().line() >= first_visible_line) {
  593. break;
  594. }
  595. ++span_index;
  596. }
  597. }
  598. for (size_t line_index = first_visible_line; line_index <= last_visible_line; ++line_index) {
  599. auto& line = this->line(line_index);
  600. bool physical_line_has_selection = has_selection && line_index >= selection.start().line() && line_index <= selection.end().line();
  601. size_t first_visual_line_with_selection = 0;
  602. size_t last_visual_line_with_selection = 0;
  603. if (physical_line_has_selection) {
  604. if (selection.start().line() < line_index)
  605. first_visual_line_with_selection = 0;
  606. else
  607. first_visual_line_with_selection = visual_line_containing(line_index, selection.start().column());
  608. if (selection.end().line() > line_index)
  609. last_visual_line_with_selection = m_line_data[line_index]->visual_lines.size();
  610. else
  611. last_visual_line_with_selection = visual_line_containing(line_index, selection.end().column());
  612. }
  613. size_t selection_start_column_within_line = selection.start().line() == line_index ? selection.start().column() : 0;
  614. size_t selection_end_column_within_line = selection.end().line() == line_index ? selection.end().column() : line.length();
  615. size_t visual_line_index = 0;
  616. size_t last_start_of_visual_line = 0;
  617. Optional<size_t> multiline_trailing_space_offset {};
  618. for_each_visual_line(line_index, [&](Gfx::IntRect const& visual_line_rect, auto& visual_line_text, size_t start_of_visual_line, [[maybe_unused]] bool is_last_visual_line) {
  619. ScopeGuard update_last_start_of_visual_line { [&]() { last_start_of_visual_line = start_of_visual_line; } };
  620. if (is_focused() && is_multi_line() && line_index == m_cursor.line() && is_cursor_line_highlighted()) {
  621. Gfx::IntRect visible_content_line_rect {
  622. visible_content_rect().x(),
  623. visual_line_rect.y(),
  624. widget_inner_rect().width() - gutter_ruler_width,
  625. line_height()
  626. };
  627. painter.fill_rect(visible_content_line_rect, widget_background_color.darkened(0.9f));
  628. }
  629. if constexpr (TEXTEDITOR_DEBUG)
  630. painter.draw_rect(visual_line_rect, Color::Cyan);
  631. if (!placeholder().is_empty() && document().is_empty() && line_index == 0) {
  632. auto line_rect = visual_line_rect;
  633. line_rect.set_width(text_width_for_font(placeholder(), font()));
  634. draw_text(line_rect, placeholder(), font(), m_text_alignment, { palette().color(Gfx::ColorRole::PlaceholderText) }, false);
  635. } else if (!document().has_spans()) {
  636. // Fast-path for plain text
  637. draw_text(visual_line_rect, visual_line_text, font(), m_text_alignment, unspanned_text_attributes);
  638. } else {
  639. size_t next_column = 0;
  640. Gfx::FloatRect span_rect = { visual_line_rect.location(), { 0, line_height() } };
  641. auto draw_text_helper = [&](size_t start, size_t end, Gfx::Font const& font, Gfx::TextAttributes text_attributes) {
  642. size_t length = end - start;
  643. if (length == 0)
  644. return;
  645. auto text = visual_line_text.substring_view(start, length);
  646. span_rect.set_width(font.width(text) + font.glyph_spacing());
  647. if (text_attributes.background_color.has_value()) {
  648. painter.fill_rect(span_rect.to_type<int>(), text_attributes.background_color.value());
  649. }
  650. draw_text(span_rect, text, font, m_text_alignment, text_attributes);
  651. span_rect.translate_by(span_rect.width(), 0);
  652. };
  653. bool started_new_folded_region = false;
  654. while (span_index < document().spans().size()) {
  655. auto& span = document().spans()[span_index];
  656. // Skip spans that have ended before this point.
  657. // That is, for spans that are for lines inside a folded region.
  658. if ((span.range.end().line() < line_index)
  659. || (span.range.end().line() == line_index && span.range.end().column() <= start_of_visual_line)) {
  660. ++span_index;
  661. continue;
  662. }
  663. if (span.range.start().line() > line_index
  664. || (span.range.start().line() == line_index && span.range.start().column() >= start_of_visual_line + visual_line_text.length())) {
  665. // no more spans in this line, moving on
  666. break;
  667. }
  668. size_t span_start;
  669. if (span.range.start().line() < line_index || span.range.start().column() < start_of_visual_line) {
  670. span_start = 0;
  671. } else {
  672. span_start = span.range.start().column() - start_of_visual_line;
  673. }
  674. size_t span_end;
  675. bool span_consumed;
  676. if (span.range.end().line() > line_index || span.range.end().column() > start_of_visual_line + visual_line_text.length()) {
  677. span_end = visual_line_text.length();
  678. span_consumed = false;
  679. } else {
  680. span_end = span.range.end().column() - start_of_visual_line;
  681. span_consumed = true;
  682. }
  683. if (span_start != next_column) {
  684. // draw unspanned text between spans
  685. draw_text_helper(next_column, span_start, font(), unspanned_text_attributes);
  686. }
  687. auto& span_font = span.attributes.bold ? font().bold_variant() : font();
  688. draw_text_helper(span_start, span_end, span_font, span.attributes);
  689. next_column = span_end;
  690. if (!span_consumed) {
  691. // continue with same span on next line
  692. break;
  693. } else {
  694. ++span_index;
  695. }
  696. }
  697. // draw unspanned text after last span
  698. if (!started_new_folded_region && next_column < visual_line_text.length()) {
  699. draw_text_helper(next_column, visual_line_text.length(), font(), unspanned_text_attributes);
  700. }
  701. // Paint "..." at the end of the line if it starts a folded region.
  702. // FIXME: This doesn't wrap.
  703. if (is_last_visual_line) {
  704. if (auto folded_region = document().folding_region_starting_on_line(line_index); folded_region.has_value() && folded_region->is_folded) {
  705. span_rect.set_width(folded_region_summary_font.width(folded_region_summary_text));
  706. draw_text(span_rect, folded_region_summary_text, folded_region_summary_font, m_text_alignment, folded_region_summary_attributes);
  707. }
  708. }
  709. }
  710. if (m_visualize_trailing_whitespace && line.ends_in_whitespace()) {
  711. size_t physical_column;
  712. auto last_non_whitespace_column = line.last_non_whitespace_column();
  713. if (last_non_whitespace_column.has_value())
  714. physical_column = last_non_whitespace_column.value() + 1;
  715. else
  716. physical_column = 0;
  717. size_t end_of_visual_line = (start_of_visual_line + visual_line_text.length());
  718. if (physical_column < end_of_visual_line) {
  719. physical_column -= multiline_trailing_space_offset.value_or(0);
  720. size_t visual_column = physical_column > start_of_visual_line ? (physical_column - start_of_visual_line) : 0;
  721. Gfx::IntRect whitespace_rect {
  722. content_x_for_position({ line_index, physical_column }),
  723. visual_line_rect.y(),
  724. text_width_for_font(visual_line_text.substring_view(visual_column, visual_line_text.length() - visual_column), font()),
  725. visual_line_rect.height()
  726. };
  727. painter.fill_rect_with_dither_pattern(whitespace_rect, Color(), Color(255, 192, 192));
  728. if (!multiline_trailing_space_offset.has_value())
  729. multiline_trailing_space_offset = physical_column - last_start_of_visual_line;
  730. }
  731. }
  732. if (m_visualize_leading_whitespace && line.leading_spaces() > 0) {
  733. size_t physical_column = line.leading_spaces();
  734. if (start_of_visual_line < physical_column) {
  735. size_t end_of_leading_whitespace = min(physical_column - start_of_visual_line, visual_line_text.length());
  736. Gfx::IntRect whitespace_rect {
  737. content_x_for_position({ line_index, start_of_visual_line }),
  738. visual_line_rect.y(),
  739. text_width_for_font(visual_line_text.substring_view(0, end_of_leading_whitespace), font()),
  740. visual_line_rect.height()
  741. };
  742. painter.fill_rect_with_dither_pattern(whitespace_rect, Color(), Color(192, 255, 192));
  743. }
  744. }
  745. if (physical_line_has_selection && window()->focused_widget() == this) {
  746. size_t const start_of_selection_within_visual_line = (size_t)max(0, (int)selection_start_column_within_line - (int)start_of_visual_line);
  747. size_t const end_of_selection_within_visual_line = min(selection_end_column_within_line - start_of_visual_line, visual_line_text.length());
  748. bool current_visual_line_has_selection = start_of_selection_within_visual_line != end_of_selection_within_visual_line
  749. && ((line_index != selection.start().line() && line_index != selection.end().line())
  750. || (visual_line_index >= first_visual_line_with_selection && visual_line_index <= last_visual_line_with_selection));
  751. if (current_visual_line_has_selection) {
  752. bool selection_begins_on_current_visual_line = visual_line_index == first_visual_line_with_selection;
  753. bool selection_ends_on_current_visual_line = visual_line_index == last_visual_line_with_selection;
  754. int selection_left = selection_begins_on_current_visual_line
  755. ? content_x_for_position({ line_index, (size_t)selection_start_column_within_line })
  756. : m_horizontal_content_padding;
  757. int selection_right = selection_ends_on_current_visual_line
  758. ? content_x_for_position({ line_index, (size_t)selection_end_column_within_line })
  759. : visual_line_rect.right();
  760. Gfx::IntRect selection_rect {
  761. selection_left,
  762. visual_line_rect.y(),
  763. selection_right - selection_left,
  764. visual_line_rect.height()
  765. };
  766. Color background_color = is_focused() ? palette().selection() : palette().inactive_selection();
  767. Color text_color = is_focused() ? palette().selection_text() : palette().inactive_selection_text();
  768. painter.fill_rect(selection_rect, background_color);
  769. if (visual_line_text.code_points()) {
  770. Utf32View visual_selected_text {
  771. visual_line_text.code_points() + start_of_selection_within_visual_line,
  772. end_of_selection_within_visual_line - start_of_selection_within_visual_line
  773. };
  774. draw_text(selection_rect, visual_selected_text, font(), Gfx::TextAlignment::CenterLeft, { text_color });
  775. }
  776. }
  777. }
  778. ++visual_line_index;
  779. return IterationDecision::Continue;
  780. });
  781. }
  782. if (is_enabled() && is_focused() && !focus_preempted() && m_cursor_state && !is_displayonly())
  783. painter.fill_rect(cursor_content_rect(), palette().text_cursor());
  784. }
  785. Optional<UISize> TextEditor::calculated_min_size() const
  786. {
  787. if (is_multi_line())
  788. return AbstractScrollableWidget::calculated_min_size();
  789. auto constexpr cursor_padding = 4;
  790. auto m = content_margins();
  791. auto width = max(40, m.horizontal_total());
  792. auto height = max(22, line_height() + m.vertical_total() + cursor_padding);
  793. return UISize { width, height };
  794. }
  795. void TextEditor::select_all()
  796. {
  797. TextPosition start_of_document { 0, 0 };
  798. TextPosition end_of_document { line_count() - 1, line(line_count() - 1).length() };
  799. m_selection.set(end_of_document, start_of_document);
  800. did_update_selection();
  801. set_cursor(start_of_document);
  802. update();
  803. }
  804. void TextEditor::insert_emoji()
  805. {
  806. if (!on_emoji_input || window()->blocks_emoji_input())
  807. return;
  808. auto emoji_input_dialog = EmojiInputDialog::construct(window());
  809. if (emoji_input_dialog->exec() != EmojiInputDialog::ExecResult::OK)
  810. return;
  811. auto emoji_code_point = emoji_input_dialog->selected_emoji_text();
  812. insert_at_cursor_or_replace_selection(emoji_code_point);
  813. }
  814. void TextEditor::set_or_clear_emoji_input_callback()
  815. {
  816. switch (m_mode) {
  817. case Editable:
  818. on_emoji_input = [this](auto emoji) {
  819. insert_at_cursor_or_replace_selection(emoji);
  820. };
  821. break;
  822. case DisplayOnly:
  823. case ReadOnly:
  824. on_emoji_input = {};
  825. break;
  826. default:
  827. VERIFY_NOT_REACHED();
  828. }
  829. }
  830. void TextEditor::keydown_event(KeyEvent& event)
  831. {
  832. if (!is_editable() && event.key() == KeyCode::Key_Tab)
  833. return AbstractScrollableWidget::keydown_event(event);
  834. if (m_autocomplete_box && m_autocomplete_box->is_visible() && (event.key() == KeyCode::Key_Return || event.key() == KeyCode::Key_Tab)) {
  835. TemporaryChange change { m_should_keep_autocomplete_box, true };
  836. if (m_autocomplete_box->apply_suggestion() == CodeComprehension::AutocompleteResultEntry::HideAutocompleteAfterApplying::Yes)
  837. hide_autocomplete();
  838. else
  839. try_update_autocomplete();
  840. return;
  841. }
  842. if (m_autocomplete_box && m_autocomplete_box->is_visible() && event.key() == KeyCode::Key_Escape) {
  843. hide_autocomplete();
  844. return;
  845. }
  846. if (m_autocomplete_box && m_autocomplete_box->is_visible() && event.key() == KeyCode::Key_Up) {
  847. m_autocomplete_box->previous_suggestion();
  848. return;
  849. }
  850. if (m_autocomplete_box && m_autocomplete_box->is_visible() && event.key() == KeyCode::Key_Down) {
  851. m_autocomplete_box->next_suggestion();
  852. return;
  853. }
  854. if (is_single_line()) {
  855. if (event.key() == KeyCode::Key_Tab)
  856. return AbstractScrollableWidget::keydown_event(event);
  857. if (event.modifiers() == KeyModifier::Mod_Shift && event.key() == KeyCode::Key_Return) {
  858. if (on_shift_return_pressed)
  859. on_shift_return_pressed();
  860. return;
  861. }
  862. if (event.modifiers() == KeyModifier::Mod_Ctrl && event.key() == KeyCode::Key_Return) {
  863. if (on_ctrl_return_pressed)
  864. on_ctrl_return_pressed();
  865. return;
  866. }
  867. if (event.key() == KeyCode::Key_Return) {
  868. if (on_return_pressed)
  869. on_return_pressed();
  870. return;
  871. }
  872. if (event.key() == KeyCode::Key_Up) {
  873. if (on_up_pressed)
  874. on_up_pressed();
  875. return;
  876. }
  877. if (event.key() == KeyCode::Key_Down) {
  878. if (on_down_pressed)
  879. on_down_pressed();
  880. return;
  881. }
  882. if (event.key() == KeyCode::Key_PageUp) {
  883. if (on_pageup_pressed)
  884. on_pageup_pressed();
  885. return;
  886. }
  887. if (event.key() == KeyCode::Key_PageDown) {
  888. if (on_pagedown_pressed)
  889. on_pagedown_pressed();
  890. return;
  891. }
  892. } else if (!is_multi_line()) {
  893. VERIFY_NOT_REACHED();
  894. }
  895. ArmedScopeGuard update_autocomplete { [&] {
  896. try_update_autocomplete();
  897. } };
  898. if (is_multi_line() && !event.alt() && event.ctrl() && event.key() == KeyCode::Key_Return) {
  899. if (!is_editable())
  900. return;
  901. size_t indent_length = current_line().leading_spaces();
  902. DeprecatedString indent = current_line().to_utf8().substring(0, indent_length);
  903. auto insert_pos = event.shift() ? InsertLineCommand::InsertPosition::Above : InsertLineCommand::InsertPosition::Below;
  904. execute<InsertLineCommand>(m_cursor, move(indent), insert_pos);
  905. return;
  906. }
  907. if (is_multi_line() && !event.shift() && !event.alt() && event.ctrl() && event.key() == KeyCode::Key_Space) {
  908. if (m_autocomplete_provider) {
  909. try_show_autocomplete(UserRequestedAutocomplete::Yes);
  910. update_autocomplete.disarm();
  911. return;
  912. }
  913. }
  914. if (is_multi_line() && !event.shift() && !event.alt() && event.ctrl() && event.key() == KeyCode::Key_F) {
  915. m_search_banner->show();
  916. return;
  917. }
  918. if (m_editing_engine->on_key(event))
  919. return;
  920. if (event.key() == KeyCode::Key_Escape) {
  921. if (on_escape_pressed)
  922. on_escape_pressed();
  923. return;
  924. }
  925. if (event.modifiers() == Mod_Shift && event.key() == KeyCode::Key_Delete) {
  926. if (m_autocomplete_box)
  927. hide_autocomplete();
  928. return;
  929. }
  930. if (event.key() == KeyCode::Key_Tab) {
  931. if (has_selection()) {
  932. if (event.modifiers() == Mod_Shift) {
  933. unindent_selection();
  934. return;
  935. }
  936. if (is_indenting_selection()) {
  937. indent_selection();
  938. return;
  939. }
  940. } else {
  941. if (event.modifiers() == Mod_Shift) {
  942. unindent_line();
  943. return;
  944. }
  945. }
  946. }
  947. if (event.key() == KeyCode::Key_Delete) {
  948. if (!is_editable())
  949. return;
  950. if (m_autocomplete_box)
  951. hide_autocomplete();
  952. if (has_selection()) {
  953. delete_selection();
  954. did_update_selection();
  955. return;
  956. }
  957. if (m_cursor.column() < current_line().length()) {
  958. // Delete within line
  959. int erase_count = 1;
  960. if (event.modifiers() == Mod_Ctrl) {
  961. auto word_break_pos = document().first_word_break_after(m_cursor);
  962. erase_count = word_break_pos.column() - m_cursor.column();
  963. } else {
  964. auto grapheme_break_position = document().get_next_grapheme_cluster_boundary(m_cursor);
  965. erase_count = grapheme_break_position - m_cursor.column();
  966. }
  967. TextRange erased_range(m_cursor, { m_cursor.line(), m_cursor.column() + erase_count });
  968. execute<RemoveTextCommand>(document().text_in_range(erased_range), erased_range, erased_range.start());
  969. return;
  970. }
  971. if (m_cursor.column() == current_line().length() && m_cursor.line() != line_count() - 1) {
  972. // Delete at end of line; merge with next line
  973. size_t erase_count = 0;
  974. if (event.modifiers() == Mod_Ctrl) {
  975. erase_count = document().first_word_break_after({ m_cursor.line() + 1, 0 }).column();
  976. }
  977. TextRange erased_range(m_cursor, { m_cursor.line() + 1, erase_count });
  978. execute<RemoveTextCommand>(document().text_in_range(erased_range), erased_range, erased_range.end());
  979. return;
  980. }
  981. return;
  982. }
  983. if (event.key() == KeyCode::Key_Backspace) {
  984. if (!is_editable())
  985. return;
  986. if (m_autocomplete_box)
  987. hide_autocomplete();
  988. if (has_selection()) {
  989. delete_selection();
  990. did_update_selection();
  991. return;
  992. }
  993. if (m_cursor.column() > 0) {
  994. int erase_count = 1;
  995. if (event.modifiers() == Mod_Ctrl) {
  996. auto word_break_pos = document().first_word_break_before(m_cursor, true);
  997. erase_count = m_cursor.column() - word_break_pos.column();
  998. } else if (current_line().first_non_whitespace_column() >= m_cursor.column()) {
  999. int new_column;
  1000. if (m_cursor.column() % m_soft_tab_width == 0)
  1001. new_column = m_cursor.column() - m_soft_tab_width;
  1002. else
  1003. new_column = (m_cursor.column() / m_soft_tab_width) * m_soft_tab_width;
  1004. erase_count = m_cursor.column() - new_column;
  1005. } else {
  1006. auto grapheme_break_position = document().get_previous_grapheme_cluster_boundary(m_cursor);
  1007. erase_count = m_cursor.column() - grapheme_break_position;
  1008. }
  1009. // Backspace within line
  1010. TextRange erased_range({ m_cursor.line(), m_cursor.column() - erase_count }, m_cursor);
  1011. auto erased_text = document().text_in_range(erased_range);
  1012. execute<RemoveTextCommand>(erased_text, erased_range, erased_range.end());
  1013. return;
  1014. }
  1015. if (m_cursor.column() == 0 && m_cursor.line() != 0) {
  1016. // Backspace at column 0; merge with previous line
  1017. size_t previous_length = line(m_cursor.line() - 1).length();
  1018. TextRange erased_range({ m_cursor.line() - 1, previous_length }, m_cursor);
  1019. execute<RemoveTextCommand>("\n", erased_range, erased_range.end());
  1020. return;
  1021. }
  1022. return;
  1023. }
  1024. // AltGr is emulated as Ctrl+Alt; if Ctrl is set check if it's not for AltGr
  1025. if ((!event.ctrl() || event.altgr()) && !event.alt() && event.code_point() != 0) {
  1026. TemporaryChange change { m_should_keep_autocomplete_box, true };
  1027. add_code_point(event.code_point());
  1028. return;
  1029. }
  1030. if (event.ctrl() && event.key() == KeyCode::Key_Slash) {
  1031. if (m_highlighter != nullptr) {
  1032. auto prefix = m_highlighter->comment_prefix().value_or(""sv);
  1033. auto suffix = m_highlighter->comment_suffix().value_or(""sv);
  1034. auto range = has_selection() ? selection().normalized() : TextRange { { m_cursor.line(), m_cursor.column() }, { m_cursor.line(), m_cursor.column() } };
  1035. auto is_already_commented = true;
  1036. for (size_t i = range.start().line(); i <= range.end().line(); i++) {
  1037. auto text = m_document->line(i).to_utf8().trim_whitespace();
  1038. if (!(text.starts_with(prefix) && text.ends_with(suffix))) {
  1039. is_already_commented = false;
  1040. break;
  1041. }
  1042. }
  1043. if (is_already_commented)
  1044. execute<UncommentSelection>(prefix, suffix, range);
  1045. else
  1046. execute<CommentSelection>(prefix, suffix, range);
  1047. return;
  1048. }
  1049. }
  1050. event.ignore();
  1051. }
  1052. bool TextEditor::is_indenting_selection()
  1053. {
  1054. auto const selection_start = m_selection.start() > m_selection.end() ? m_selection.end() : m_selection.start();
  1055. auto const selection_end = m_selection.end() > m_selection.start() ? m_selection.end() : m_selection.start();
  1056. auto const whole_line_selected = selection_end.column() - selection_start.column() >= current_line().length() - current_line().first_non_whitespace_column();
  1057. auto const on_same_line = selection_start.line() == selection_end.line();
  1058. if (has_selection() && (whole_line_selected || !on_same_line)) {
  1059. return true;
  1060. }
  1061. return false;
  1062. }
  1063. void TextEditor::indent_selection()
  1064. {
  1065. auto const selection_start = m_selection.start() > m_selection.end() ? m_selection.end() : m_selection.start();
  1066. auto const selection_end = m_selection.end() > m_selection.start() ? m_selection.end() : m_selection.start();
  1067. if (is_indenting_selection()) {
  1068. execute<IndentSelection>(m_soft_tab_width, TextRange(selection_start, selection_end));
  1069. m_selection.set_start({ selection_start.line(), selection_start.column() + m_soft_tab_width });
  1070. m_selection.set_end({ selection_end.line(), selection_end.column() + m_soft_tab_width });
  1071. set_cursor({ m_cursor.line(), m_cursor.column() + m_soft_tab_width });
  1072. }
  1073. }
  1074. void TextEditor::unindent_selection()
  1075. {
  1076. auto const selection_start = m_selection.start() > m_selection.end() ? m_selection.end() : m_selection.start();
  1077. auto const selection_end = m_selection.end() > m_selection.start() ? m_selection.end() : m_selection.start();
  1078. if (current_line().first_non_whitespace_column() != 0) {
  1079. if (current_line().first_non_whitespace_column() > m_soft_tab_width && selection_start.column() != 0) {
  1080. m_selection.set_start({ selection_start.line(), selection_start.column() - m_soft_tab_width });
  1081. m_selection.set_end({ selection_end.line(), selection_end.column() - m_soft_tab_width });
  1082. } else if (selection_start.column() != 0) {
  1083. m_selection.set_start({ selection_start.line(), selection_start.column() - current_line().leading_spaces() });
  1084. m_selection.set_end({ selection_end.line(), selection_end.column() - current_line().leading_spaces() });
  1085. }
  1086. execute<UnindentSelection>(m_soft_tab_width, TextRange(selection_start, selection_end));
  1087. }
  1088. }
  1089. void TextEditor::unindent_line()
  1090. {
  1091. if (current_line().first_non_whitespace_column() != 0) {
  1092. auto const unindent_size = current_line().leading_spaces() < m_soft_tab_width ? current_line().leading_spaces() : m_soft_tab_width;
  1093. auto const temp_column = m_cursor.column();
  1094. execute<UnindentSelection>(unindent_size, TextRange({ m_cursor.line(), 0 }, { m_cursor.line(), line(m_cursor.line()).length() }));
  1095. set_cursor({ m_cursor.line(), temp_column <= unindent_size ? 0 : temp_column - unindent_size });
  1096. }
  1097. }
  1098. void TextEditor::delete_previous_word()
  1099. {
  1100. TextRange to_erase(document().first_word_before(m_cursor, true), m_cursor);
  1101. execute<RemoveTextCommand>(document().text_in_range(to_erase), to_erase, to_erase.end());
  1102. }
  1103. void TextEditor::delete_current_line()
  1104. {
  1105. if (has_selection())
  1106. return delete_selection();
  1107. TextPosition start;
  1108. TextPosition end;
  1109. if (m_cursor.line() == 0 && line_count() == 1) {
  1110. start = { 0, 0 };
  1111. end = { 0, line(0).length() };
  1112. } else if (m_cursor.line() == line_count() - 1) {
  1113. start = { m_cursor.line() - 1, line(m_cursor.line() - 1).length() };
  1114. end = { m_cursor.line(), line(m_cursor.line()).length() };
  1115. } else {
  1116. start = { m_cursor.line(), 0 };
  1117. end = { m_cursor.line() + 1, 0 };
  1118. }
  1119. TextRange erased_range(start, end);
  1120. execute<RemoveTextCommand>(document().text_in_range(erased_range), erased_range, m_cursor);
  1121. }
  1122. void TextEditor::delete_previous_char()
  1123. {
  1124. if (!is_editable())
  1125. return;
  1126. if (has_selection())
  1127. return delete_selection();
  1128. TextRange to_erase({ m_cursor.line(), m_cursor.column() - 1 }, m_cursor);
  1129. if (m_cursor.column() == 0 && m_cursor.line() != 0) {
  1130. size_t prev_line_len = line(m_cursor.line() - 1).length();
  1131. to_erase.set_start({ m_cursor.line() - 1, prev_line_len });
  1132. }
  1133. execute<RemoveTextCommand>(document().text_in_range(to_erase), to_erase, to_erase.end());
  1134. }
  1135. void TextEditor::delete_from_line_start_to_cursor()
  1136. {
  1137. TextPosition start(m_cursor.line(), current_line().first_non_whitespace_column());
  1138. TextRange to_erase(start, m_cursor);
  1139. execute<RemoveTextCommand>(document().text_in_range(to_erase), to_erase, m_cursor);
  1140. }
  1141. void TextEditor::do_delete()
  1142. {
  1143. if (!is_editable())
  1144. return;
  1145. if (has_selection())
  1146. return delete_selection();
  1147. if (m_cursor.column() < current_line().length()) {
  1148. // Delete within line
  1149. TextRange erased_range(m_cursor, { m_cursor.line(), m_cursor.column() + 1 });
  1150. execute<RemoveTextCommand>(document().text_in_range(erased_range), erased_range, erased_range.start());
  1151. return;
  1152. }
  1153. if (m_cursor.column() == current_line().length() && m_cursor.line() != line_count() - 1) {
  1154. // Delete at end of line; merge with next line
  1155. TextRange erased_range(m_cursor, { m_cursor.line() + 1, 0 });
  1156. execute<RemoveTextCommand>(document().text_in_range(erased_range), erased_range, erased_range.start());
  1157. return;
  1158. }
  1159. }
  1160. void TextEditor::add_code_point(u32 code_point)
  1161. {
  1162. if (!is_editable())
  1163. return;
  1164. StringBuilder sb;
  1165. sb.append_code_point(code_point);
  1166. if (should_autocomplete_automatically()) {
  1167. if (sb.string_view().is_whitespace())
  1168. m_autocomplete_timer->stop();
  1169. else
  1170. m_autocomplete_timer->start();
  1171. }
  1172. insert_at_cursor_or_replace_selection(sb.to_deprecated_string());
  1173. };
  1174. void TextEditor::reset_cursor_blink()
  1175. {
  1176. m_cursor_state = true;
  1177. update_cursor();
  1178. stop_timer();
  1179. start_timer(500);
  1180. }
  1181. void TextEditor::update_selection(bool is_selecting)
  1182. {
  1183. if (is_selecting && !selection().is_valid()) {
  1184. selection().set(cursor(), {});
  1185. did_update_selection();
  1186. update();
  1187. return;
  1188. }
  1189. if (!is_selecting && selection().is_valid()) {
  1190. selection().clear();
  1191. did_update_selection();
  1192. update();
  1193. return;
  1194. }
  1195. if (is_selecting && selection().start().is_valid()) {
  1196. selection().set_end(cursor());
  1197. did_update_selection();
  1198. update();
  1199. return;
  1200. }
  1201. }
  1202. int TextEditor::content_x_for_position(TextPosition const& position) const
  1203. {
  1204. auto& line = this->line(position.line());
  1205. int x_offset = 0;
  1206. switch (m_text_alignment) {
  1207. case Gfx::TextAlignment::CenterLeft:
  1208. for_each_visual_line(position.line(), [&](Gfx::IntRect const&, auto& visual_line_view, size_t start_of_visual_line, bool is_last_visual_line) {
  1209. size_t offset_in_visual_line = position.column() - start_of_visual_line;
  1210. auto before_line_end = is_last_visual_line ? (offset_in_visual_line <= visual_line_view.length()) : (offset_in_visual_line < visual_line_view.length());
  1211. if (position.column() >= start_of_visual_line && before_line_end) {
  1212. if (offset_in_visual_line == 0) {
  1213. x_offset = 0;
  1214. } else {
  1215. x_offset = text_width_for_font(visual_line_view.substring_view(0, offset_in_visual_line), font());
  1216. x_offset += font().glyph_spacing();
  1217. }
  1218. return IterationDecision::Break;
  1219. }
  1220. return IterationDecision::Continue;
  1221. });
  1222. return m_horizontal_content_padding + ((is_single_line() && icon()) ? (icon_size() + icon_padding()) : 0) + x_offset;
  1223. case Gfx::TextAlignment::CenterRight:
  1224. // FIXME
  1225. VERIFY(!is_wrapping_enabled());
  1226. return content_width() - m_horizontal_content_padding - (line.length() * fixed_glyph_width()) + (position.column() * fixed_glyph_width());
  1227. default:
  1228. VERIFY_NOT_REACHED();
  1229. }
  1230. }
  1231. int TextEditor::text_width_for_font(auto const& text, Gfx::Font const& font) const
  1232. {
  1233. if (m_substitution_code_point.has_value())
  1234. return font.width(substitution_code_point_view(text.length()));
  1235. else
  1236. return font.width(text);
  1237. }
  1238. Utf32View TextEditor::substitution_code_point_view(size_t length) const
  1239. {
  1240. VERIFY(m_substitution_code_point.has_value());
  1241. if (!m_substitution_string_data)
  1242. m_substitution_string_data = make<Vector<u32>>();
  1243. if (!m_substitution_string_data->is_empty())
  1244. VERIFY(m_substitution_string_data->first() == m_substitution_code_point);
  1245. while (m_substitution_string_data->size() < length)
  1246. m_substitution_string_data->append(m_substitution_code_point.value());
  1247. return Utf32View { m_substitution_string_data->data(), length };
  1248. }
  1249. Gfx::IntRect TextEditor::content_rect_for_position(TextPosition const& position) const
  1250. {
  1251. if (!position.is_valid())
  1252. return {};
  1253. VERIFY(!lines().is_empty());
  1254. VERIFY(position.column() <= (current_line().length() + 1));
  1255. int x = content_x_for_position(position);
  1256. if (is_single_line()) {
  1257. Gfx::IntRect rect { x, 0, 1, line_height() };
  1258. rect.center_vertically_within({ {}, frame_inner_rect().size() });
  1259. return rect;
  1260. }
  1261. Gfx::IntRect rect;
  1262. for_each_visual_line(position.line(), [&](Gfx::IntRect const& visual_line_rect, auto& view, size_t start_of_visual_line, bool is_last_visual_line) {
  1263. auto before_line_end = is_last_visual_line ? ((position.column() - start_of_visual_line) <= view.length()) : ((position.column() - start_of_visual_line) < view.length());
  1264. if (position.column() >= start_of_visual_line && before_line_end) {
  1265. // NOTE: We have to subtract the horizontal padding here since it's part of the visual line rect
  1266. // *and* included in what we get from content_x_for_position().
  1267. rect = {
  1268. visual_line_rect.x() + x - (m_horizontal_content_padding),
  1269. visual_line_rect.y(),
  1270. m_editing_engine->cursor_width() == CursorWidth::WIDE ? 7 : 1,
  1271. line_height()
  1272. };
  1273. return IterationDecision::Break;
  1274. }
  1275. return IterationDecision::Continue;
  1276. });
  1277. return rect;
  1278. }
  1279. Gfx::IntRect TextEditor::cursor_content_rect() const
  1280. {
  1281. return content_rect_for_position(m_cursor);
  1282. }
  1283. Gfx::IntRect TextEditor::line_widget_rect(size_t line_index) const
  1284. {
  1285. auto rect = line_content_rect(line_index);
  1286. rect.set_x(frame_thickness());
  1287. rect.set_width(frame_inner_rect().width());
  1288. rect.translate_by(0, -(vertical_scrollbar().value()));
  1289. rect.translate_by(0, frame_thickness());
  1290. rect.translate_by(0, height_occupied_by_banner_widget());
  1291. rect.intersect(frame_inner_rect());
  1292. return rect;
  1293. }
  1294. void TextEditor::scroll_position_into_view(TextPosition const& position)
  1295. {
  1296. auto rect = content_rect_for_position(position);
  1297. if (position.column() == 0)
  1298. rect.set_x(content_x_for_position({ position.line(), 0 }) - 2);
  1299. else if (position.column() == line(position.line()).length())
  1300. rect.set_x(content_x_for_position({ position.line(), line(position.line()).length() }) + 2);
  1301. scroll_into_view(rect, true, true);
  1302. }
  1303. void TextEditor::scroll_cursor_into_view()
  1304. {
  1305. if (!m_reflow_deferred)
  1306. scroll_position_into_view(m_cursor);
  1307. }
  1308. Gfx::IntRect TextEditor::line_content_rect(size_t line_index) const
  1309. {
  1310. auto& line = this->line(line_index);
  1311. if (is_single_line()) {
  1312. Gfx::IntRect line_rect = { content_x_for_position({ line_index, 0 }), 0, text_width_for_font(line.view(), font()), font().pixel_size_rounded_up() + 4 };
  1313. line_rect.center_vertically_within({ {}, frame_inner_rect().size() });
  1314. return line_rect;
  1315. }
  1316. return m_line_data[line_index]->visual_rect;
  1317. }
  1318. void TextEditor::set_cursor_and_focus_line(size_t line, size_t column)
  1319. {
  1320. u_int index_max = line_count() - 1;
  1321. set_cursor(line, column);
  1322. if (line > 1 && line < index_max) {
  1323. int headroom = frame_inner_rect().height() / 3;
  1324. do {
  1325. auto const& line_data = m_line_data[line];
  1326. headroom -= line_data->visual_rect.height();
  1327. line--;
  1328. } while (line > 0 && headroom > 0);
  1329. Gfx::IntRect rect = { 0, line_content_rect(line).y(),
  1330. 1, frame_inner_rect().height() };
  1331. scroll_into_view(rect, false, true);
  1332. }
  1333. }
  1334. void TextEditor::update_cursor()
  1335. {
  1336. update(line_widget_rect(m_cursor.line()));
  1337. }
  1338. void TextEditor::set_cursor(size_t line, size_t column)
  1339. {
  1340. set_cursor({ line, column });
  1341. }
  1342. void TextEditor::set_cursor(TextPosition const& a_position)
  1343. {
  1344. VERIFY(!lines().is_empty());
  1345. TextPosition position = a_position;
  1346. if (position.line() >= line_count())
  1347. position.set_line(line_count() - 1);
  1348. if (position.column() > lines()[position.line()]->length())
  1349. position.set_column(lines()[position.line()]->length());
  1350. if (m_cursor != position && is_visual_data_up_to_date()) {
  1351. // NOTE: If the old cursor is no longer valid, repaint everything just in case.
  1352. auto old_cursor_line_rect = m_cursor.line() < line_count()
  1353. ? line_widget_rect(m_cursor.line())
  1354. : rect();
  1355. m_cursor = position;
  1356. m_cursor_state = true;
  1357. scroll_cursor_into_view();
  1358. update(old_cursor_line_rect);
  1359. update_cursor();
  1360. } else if (m_cursor != position) {
  1361. m_cursor = position;
  1362. m_cursor_state = true;
  1363. }
  1364. cursor_did_change();
  1365. if (on_cursor_change)
  1366. on_cursor_change();
  1367. if (m_highlighter)
  1368. m_highlighter->cursor_did_change();
  1369. if (m_relative_line_number)
  1370. update();
  1371. }
  1372. void TextEditor::set_cursor_to_text_position(Gfx::IntPoint position)
  1373. {
  1374. auto visual_position = text_position_at(position);
  1375. size_t physical_column = 0;
  1376. auto const& line = document().line(visual_position.line());
  1377. size_t boundary_index = 0;
  1378. Unicode::for_each_grapheme_segmentation_boundary(line.view(), [&](auto boundary) {
  1379. physical_column = boundary;
  1380. if (boundary_index++ >= visual_position.column())
  1381. return IterationDecision::Break;
  1382. return IterationDecision::Continue;
  1383. });
  1384. set_cursor({ visual_position.line(), physical_column });
  1385. }
  1386. void TextEditor::set_cursor_to_end_of_visual_line()
  1387. {
  1388. for_each_visual_line(m_cursor.line(), [&](auto const&, auto& view, size_t start_of_visual_line, auto) {
  1389. if (m_cursor.column() < start_of_visual_line)
  1390. return IterationDecision::Continue;
  1391. if ((m_cursor.column() - start_of_visual_line) >= view.length())
  1392. return IterationDecision::Continue;
  1393. set_cursor(m_cursor.line(), start_of_visual_line + view.length());
  1394. return IterationDecision::Break;
  1395. });
  1396. }
  1397. void TextEditor::focusin_event(FocusEvent& event)
  1398. {
  1399. if (event.source() == FocusSource::Keyboard)
  1400. select_all();
  1401. m_cursor_state = true;
  1402. update_cursor();
  1403. stop_timer();
  1404. start_timer(500);
  1405. if (on_focusin)
  1406. on_focusin();
  1407. }
  1408. void TextEditor::focusout_event(FocusEvent&)
  1409. {
  1410. if (is_displayonly() && has_selection())
  1411. m_selection.clear();
  1412. stop_timer();
  1413. if (on_focusout)
  1414. on_focusout();
  1415. }
  1416. void TextEditor::timer_event(Core::TimerEvent&)
  1417. {
  1418. m_cursor_state = !m_cursor_state;
  1419. if (is_focused())
  1420. update_cursor();
  1421. }
  1422. ErrorOr<void> TextEditor::write_to_file(StringView path)
  1423. {
  1424. auto file = TRY(Core::File::open(path, Core::File::OpenMode::Write | Core::File::OpenMode::Truncate));
  1425. TRY(write_to_file(*file));
  1426. return {};
  1427. }
  1428. ErrorOr<void> TextEditor::write_to_file(Core::File& file)
  1429. {
  1430. off_t file_size = 0;
  1431. if (line_count() == 1 && line(0).is_empty()) {
  1432. // Truncate to zero.
  1433. } else {
  1434. // Compute the final file size and ftruncate() to make writing fast.
  1435. // FIXME: Remove this once the kernel is smart enough to do this instead.
  1436. for (size_t i = 0; i < line_count(); ++i)
  1437. file_size += line(i).length();
  1438. file_size += line_count();
  1439. }
  1440. TRY(file.truncate(file_size));
  1441. if (file_size == 0) {
  1442. // A size 0 file doesn't need a data copy.
  1443. } else {
  1444. for (size_t i = 0; i < line_count(); ++i) {
  1445. TRY(file.write_until_depleted(line(i).to_utf8().bytes()));
  1446. TRY(file.write_until_depleted("\n"sv.bytes()));
  1447. }
  1448. }
  1449. document().set_unmodified();
  1450. return {};
  1451. }
  1452. DeprecatedString TextEditor::text() const
  1453. {
  1454. return document().text();
  1455. }
  1456. void TextEditor::clear()
  1457. {
  1458. document().remove_all_lines();
  1459. document().append_line(make<TextDocumentLine>(document()));
  1460. m_selection.clear();
  1461. did_update_selection();
  1462. set_cursor(0, 0);
  1463. update();
  1464. }
  1465. DeprecatedString TextEditor::selected_text() const
  1466. {
  1467. if (!has_selection())
  1468. return {};
  1469. return document().text_in_range(m_selection);
  1470. }
  1471. size_t TextEditor::number_of_selected_words() const
  1472. {
  1473. if (!has_selection())
  1474. return 0;
  1475. size_t word_count = 0;
  1476. bool in_word = false;
  1477. auto selected_text = this->selected_text();
  1478. for (char c : selected_text) {
  1479. if (in_word && is_ascii_space(c)) {
  1480. in_word = false;
  1481. word_count++;
  1482. continue;
  1483. }
  1484. if (!in_word && !is_ascii_space(c))
  1485. in_word = true;
  1486. }
  1487. if (in_word)
  1488. word_count++;
  1489. return word_count;
  1490. }
  1491. size_t TextEditor::number_of_words() const
  1492. {
  1493. if (document().is_empty())
  1494. return 0;
  1495. size_t word_count = 0;
  1496. bool in_word = false;
  1497. auto text = this->text();
  1498. for (char c : text) {
  1499. if (in_word && is_ascii_space(c)) {
  1500. in_word = false;
  1501. word_count++;
  1502. continue;
  1503. }
  1504. if (!in_word && !is_ascii_space(c))
  1505. in_word = true;
  1506. }
  1507. if (in_word)
  1508. word_count++;
  1509. return word_count;
  1510. }
  1511. void TextEditor::delete_selection()
  1512. {
  1513. auto selection = normalized_selection();
  1514. auto selected = selected_text();
  1515. m_selection.clear();
  1516. execute<RemoveTextCommand>(selected, selection, selection.end());
  1517. did_update_selection();
  1518. did_change();
  1519. set_cursor(selection.start());
  1520. update();
  1521. }
  1522. void TextEditor::delete_text_range(TextRange range)
  1523. {
  1524. auto normalized_range = range.normalized();
  1525. execute<RemoveTextCommand>(document().text_in_range(normalized_range), normalized_range, normalized_range.end());
  1526. did_change();
  1527. set_cursor(normalized_range.start());
  1528. update();
  1529. }
  1530. void TextEditor::insert_at_cursor_or_replace_selection(StringView text)
  1531. {
  1532. ReflowDeferrer defer(*this);
  1533. VERIFY(is_editable());
  1534. if (has_selection())
  1535. delete_selection();
  1536. // Check if adding a newline leaves the previous line as just whitespace.
  1537. auto const clear_length = m_cursor.column();
  1538. auto const should_clear_last_line = text == "\n"
  1539. && clear_length > 0
  1540. && current_line().leading_spaces() == clear_length;
  1541. execute<InsertTextCommand>(text, m_cursor);
  1542. if (should_clear_last_line) { // If it does leave just whitespace, clear it.
  1543. auto const original_cursor_position = cursor();
  1544. TextPosition start(original_cursor_position.line() - 1, 0);
  1545. TextPosition end(original_cursor_position.line() - 1, clear_length);
  1546. TextRange erased_range(start, end);
  1547. execute<RemoveTextCommand>(document().text_in_range(erased_range), erased_range, erased_range.end());
  1548. set_cursor(original_cursor_position);
  1549. }
  1550. }
  1551. void TextEditor::replace_all_text_without_resetting_undo_stack(StringView text)
  1552. {
  1553. auto start = GUI::TextPosition(0, 0);
  1554. auto last_line_index = line_count() - 1;
  1555. auto end = GUI::TextPosition(last_line_index, line(last_line_index).length());
  1556. auto range = GUI::TextRange(start, end);
  1557. auto normalized_range = range.normalized();
  1558. execute<ReplaceAllTextCommand>(text, range, "GML Playground Format Text");
  1559. did_change();
  1560. set_cursor(normalized_range.start());
  1561. update();
  1562. }
  1563. void TextEditor::cut()
  1564. {
  1565. if (!is_editable())
  1566. return;
  1567. auto selected_text = this->selected_text();
  1568. dbgln_if(TEXTEDITOR_DEBUG, "Cut: \"{}\"", selected_text);
  1569. Clipboard::the().set_plain_text(selected_text);
  1570. delete_selection();
  1571. }
  1572. void TextEditor::copy()
  1573. {
  1574. auto selected_text = this->selected_text();
  1575. dbgln_if(TEXTEDITOR_DEBUG, "Copy: \"{}\"\n", selected_text);
  1576. Clipboard::the().set_plain_text(selected_text);
  1577. }
  1578. void TextEditor::paste()
  1579. {
  1580. if (!is_editable())
  1581. return;
  1582. auto [data, mime_type, _] = GUI::Clipboard::the().fetch_data_and_type();
  1583. if (!mime_type.starts_with("text/"sv))
  1584. return;
  1585. if (data.is_empty())
  1586. return;
  1587. dbgln_if(TEXTEDITOR_DEBUG, "Paste: \"{}\"", DeprecatedString::copy(data));
  1588. TemporaryChange change(m_automatic_indentation_enabled, false);
  1589. insert_at_cursor_or_replace_selection(data);
  1590. }
  1591. void TextEditor::defer_reflow()
  1592. {
  1593. ++m_reflow_deferred;
  1594. }
  1595. void TextEditor::undefer_reflow()
  1596. {
  1597. VERIFY(m_reflow_deferred);
  1598. if (!--m_reflow_deferred) {
  1599. if (m_reflow_requested) {
  1600. recompute_all_visual_lines();
  1601. scroll_cursor_into_view();
  1602. }
  1603. }
  1604. }
  1605. void TextEditor::try_show_autocomplete(UserRequestedAutocomplete user_requested_autocomplete)
  1606. {
  1607. force_update_autocomplete([&, user_requested_autocomplete = move(user_requested_autocomplete)] {
  1608. if (user_requested_autocomplete == Yes || m_autocomplete_box->has_suggestions()) {
  1609. auto position = content_rect_for_position(cursor()).translated(0, -visible_content_rect().y()).bottom_right().translated(screen_relative_rect().top_left().translated(ruler_width(), 0).translated(9, 4));
  1610. m_autocomplete_box->show(position);
  1611. }
  1612. });
  1613. }
  1614. void TextEditor::try_update_autocomplete(Function<void()> callback)
  1615. {
  1616. if (m_autocomplete_box && m_autocomplete_box->is_visible())
  1617. force_update_autocomplete(move(callback));
  1618. }
  1619. void TextEditor::force_update_autocomplete(Function<void()> callback)
  1620. {
  1621. if (m_autocomplete_provider) {
  1622. m_autocomplete_provider->provide_completions([&, callback = move(callback)](auto completions) {
  1623. m_autocomplete_box->update_suggestions(move(completions));
  1624. if (callback)
  1625. callback();
  1626. });
  1627. }
  1628. }
  1629. void TextEditor::hide_autocomplete_if_needed()
  1630. {
  1631. if (!m_should_keep_autocomplete_box)
  1632. hide_autocomplete();
  1633. }
  1634. void TextEditor::hide_autocomplete()
  1635. {
  1636. if (m_autocomplete_box) {
  1637. m_autocomplete_box->close();
  1638. if (m_autocomplete_timer)
  1639. m_autocomplete_timer->stop();
  1640. }
  1641. }
  1642. void TextEditor::enter_event(Core::Event&)
  1643. {
  1644. set_automatic_scrolling_timer_active(false);
  1645. }
  1646. void TextEditor::leave_event(Core::Event&)
  1647. {
  1648. if (m_in_drag_select)
  1649. set_automatic_scrolling_timer_active(true);
  1650. }
  1651. void TextEditor::did_change(AllowCallback allow_callback)
  1652. {
  1653. update_content_size();
  1654. recompute_all_visual_lines();
  1655. hide_autocomplete_if_needed();
  1656. m_needs_rehighlight = true;
  1657. if (on_change && allow_callback == AllowCallback::Yes)
  1658. on_change();
  1659. }
  1660. void TextEditor::set_mode(const Mode mode)
  1661. {
  1662. if (m_mode == mode)
  1663. return;
  1664. m_mode = mode;
  1665. switch (mode) {
  1666. case Editable:
  1667. m_cut_action->set_enabled(has_selection() && !text_is_secret());
  1668. m_paste_action->set_enabled(true);
  1669. m_insert_emoji_action->set_enabled(true);
  1670. break;
  1671. case DisplayOnly:
  1672. case ReadOnly:
  1673. m_cut_action->set_enabled(false);
  1674. m_paste_action->set_enabled(false);
  1675. m_insert_emoji_action->set_enabled(false);
  1676. break;
  1677. default:
  1678. VERIFY_NOT_REACHED();
  1679. }
  1680. set_or_clear_emoji_input_callback();
  1681. set_editing_cursor();
  1682. }
  1683. void TextEditor::set_editing_cursor()
  1684. {
  1685. if (!is_displayonly())
  1686. set_override_cursor(Gfx::StandardCursor::IBeam);
  1687. else
  1688. set_override_cursor(Gfx::StandardCursor::None);
  1689. }
  1690. void TextEditor::did_update_selection()
  1691. {
  1692. m_cut_action->set_enabled(is_editable() && has_selection() && !text_is_secret());
  1693. m_copy_action->set_enabled(has_selection() && !text_is_secret());
  1694. if (on_selection_change)
  1695. on_selection_change();
  1696. if (is_wrapping_enabled()) {
  1697. // FIXME: Try to repaint less.
  1698. update();
  1699. }
  1700. }
  1701. void TextEditor::context_menu_event(ContextMenuEvent& event)
  1702. {
  1703. if (is_displayonly())
  1704. return;
  1705. m_insert_emoji_action->set_enabled(on_emoji_input && !window()->blocks_emoji_input());
  1706. if (!m_context_menu) {
  1707. m_context_menu = Menu::construct();
  1708. m_context_menu->add_action(undo_action());
  1709. m_context_menu->add_action(redo_action());
  1710. m_context_menu->add_separator();
  1711. m_context_menu->add_action(cut_action());
  1712. m_context_menu->add_action(copy_action());
  1713. m_context_menu->add_action(paste_action());
  1714. m_context_menu->add_separator();
  1715. m_context_menu->add_action(select_all_action());
  1716. m_context_menu->add_action(insert_emoji_action());
  1717. if (is_multi_line()) {
  1718. m_context_menu->add_separator();
  1719. m_context_menu->add_action(go_to_line_or_column_action());
  1720. }
  1721. if (!m_custom_context_menu_actions.is_empty()) {
  1722. m_context_menu->add_separator();
  1723. for (auto& action : m_custom_context_menu_actions) {
  1724. m_context_menu->add_action(action);
  1725. }
  1726. }
  1727. }
  1728. m_context_menu->popup(event.screen_position());
  1729. }
  1730. void TextEditor::set_text_alignment(Gfx::TextAlignment alignment)
  1731. {
  1732. if (m_text_alignment == alignment)
  1733. return;
  1734. m_text_alignment = alignment;
  1735. update();
  1736. }
  1737. void TextEditor::resize_event(ResizeEvent& event)
  1738. {
  1739. AbstractScrollableWidget::resize_event(event);
  1740. update_content_size();
  1741. recompute_all_visual_lines();
  1742. }
  1743. void TextEditor::theme_change_event(ThemeChangeEvent& event)
  1744. {
  1745. AbstractScrollableWidget::theme_change_event(event);
  1746. m_needs_rehighlight = true;
  1747. }
  1748. void TextEditor::set_selection(TextRange const& selection)
  1749. {
  1750. if (m_selection == selection)
  1751. return;
  1752. m_selection = selection;
  1753. set_cursor(m_selection.end());
  1754. scroll_position_into_view(normalized_selection().start());
  1755. update();
  1756. }
  1757. void TextEditor::clear_selection()
  1758. {
  1759. if (!has_selection())
  1760. return;
  1761. m_selection.clear();
  1762. update();
  1763. }
  1764. void TextEditor::recompute_all_visual_lines()
  1765. {
  1766. if (m_reflow_deferred) {
  1767. m_reflow_requested = true;
  1768. return;
  1769. }
  1770. m_reflow_requested = false;
  1771. int y_offset = 0;
  1772. auto folded_regions = document().currently_folded_regions();
  1773. auto folded_region_iterator = folded_regions.begin();
  1774. for (size_t line_index = 0; line_index < line_count(); ++line_index) {
  1775. recompute_visual_lines(line_index, folded_region_iterator);
  1776. m_line_data[line_index]->visual_rect.set_y(y_offset);
  1777. y_offset += m_line_data[line_index]->visual_rect.height();
  1778. }
  1779. update_content_size();
  1780. }
  1781. void TextEditor::ensure_cursor_is_valid()
  1782. {
  1783. auto new_cursor = m_cursor;
  1784. if (new_cursor.line() >= line_count())
  1785. new_cursor.set_line(line_count() - 1);
  1786. if (new_cursor.column() > line(new_cursor.line()).length())
  1787. new_cursor.set_column(line(new_cursor.line()).length());
  1788. if (m_cursor != new_cursor)
  1789. set_cursor(new_cursor);
  1790. }
  1791. size_t TextEditor::visual_line_containing(size_t line_index, size_t column) const
  1792. {
  1793. size_t visual_line_index = 0;
  1794. for_each_visual_line(line_index, [&](Gfx::IntRect const&, auto& view, size_t start_of_visual_line, [[maybe_unused]] bool is_last_visual_line) {
  1795. if (column >= start_of_visual_line && ((column - start_of_visual_line) < view.length()))
  1796. return IterationDecision::Break;
  1797. ++visual_line_index;
  1798. return IterationDecision::Continue;
  1799. });
  1800. return visual_line_index;
  1801. }
  1802. void TextEditor::recompute_visual_lines(size_t line_index, Vector<TextDocumentFoldingRegion const&>::Iterator& folded_region_iterator)
  1803. {
  1804. auto const& line = document().line(line_index);
  1805. size_t line_width_so_far = 0;
  1806. auto& visual_data = m_line_data[line_index];
  1807. visual_data->visual_lines.clear_with_capacity();
  1808. auto available_width = visible_text_rect_in_inner_coordinates().width();
  1809. auto glyph_spacing = font().glyph_spacing();
  1810. while (!folded_region_iterator.is_end() && folded_region_iterator->range.end() < TextPosition { line_index, 0 })
  1811. ++folded_region_iterator;
  1812. bool line_is_visible = true;
  1813. if (!folded_region_iterator.is_end()) {
  1814. if (folded_region_iterator->range.start().line() < line_index) {
  1815. if (folded_region_iterator->range.end().line() > line_index) {
  1816. line_is_visible = false;
  1817. } else if (folded_region_iterator->range.end().line() == line_index) {
  1818. ++folded_region_iterator;
  1819. }
  1820. }
  1821. }
  1822. auto wrap_visual_lines_anywhere = [&]() {
  1823. size_t start_of_visual_line = 0;
  1824. for (auto it = line.view().begin(); it != line.view().end(); ++it) {
  1825. auto it_before_computing_glyph_width = it;
  1826. auto glyph_width = font().glyph_or_emoji_width(it);
  1827. if (line_width_so_far + glyph_width + glyph_spacing > available_width) {
  1828. auto start_of_next_visual_line = line.view().iterator_offset(it_before_computing_glyph_width);
  1829. visual_data->visual_lines.append(line.view().substring_view(start_of_visual_line, start_of_next_visual_line - start_of_visual_line));
  1830. line_width_so_far = 0;
  1831. start_of_visual_line = start_of_next_visual_line;
  1832. }
  1833. line_width_so_far += glyph_width + glyph_spacing;
  1834. }
  1835. visual_data->visual_lines.append(line.view().substring_view(start_of_visual_line, line.view().length() - start_of_visual_line));
  1836. };
  1837. auto wrap_visual_lines_at_words = [&]() {
  1838. size_t last_boundary = 0;
  1839. size_t start_of_visual_line = 0;
  1840. Unicode::for_each_word_segmentation_boundary(line.view(), [&](auto boundary) {
  1841. if (boundary == 0)
  1842. return IterationDecision::Continue;
  1843. auto word = line.view().substring_view(last_boundary, boundary - last_boundary);
  1844. auto word_width = font().width(word);
  1845. if (line_width_so_far + word_width + glyph_spacing > available_width) {
  1846. visual_data->visual_lines.append(line.view().substring_view(start_of_visual_line, last_boundary - start_of_visual_line));
  1847. line_width_so_far = 0;
  1848. start_of_visual_line = last_boundary;
  1849. }
  1850. line_width_so_far += word_width + glyph_spacing;
  1851. last_boundary = boundary;
  1852. return IterationDecision::Continue;
  1853. });
  1854. visual_data->visual_lines.append(line.view().substring_view(start_of_visual_line, line.view().length() - start_of_visual_line));
  1855. };
  1856. if (line_is_visible) {
  1857. switch (wrapping_mode()) {
  1858. case WrappingMode::NoWrap:
  1859. visual_data->visual_lines.append(line.view());
  1860. break;
  1861. case WrappingMode::WrapAnywhere:
  1862. wrap_visual_lines_anywhere();
  1863. break;
  1864. case WrappingMode::WrapAtWords:
  1865. wrap_visual_lines_at_words();
  1866. break;
  1867. }
  1868. }
  1869. if (is_wrapping_enabled())
  1870. visual_data->visual_rect = { m_horizontal_content_padding, 0, available_width, static_cast<int>(visual_data->visual_lines.size()) * line_height() };
  1871. else
  1872. visual_data->visual_rect = { m_horizontal_content_padding, 0, text_width_for_font(line.view(), font()), line_height() };
  1873. }
  1874. template<typename Callback>
  1875. void TextEditor::for_each_visual_line(size_t line_index, Callback callback) const
  1876. {
  1877. auto editor_visible_text_rect = visible_text_rect_in_inner_coordinates();
  1878. size_t visual_line_index = 0;
  1879. auto& line = document().line(line_index);
  1880. auto& visual_data = m_line_data[line_index];
  1881. for (auto visual_line_view : visual_data->visual_lines) {
  1882. Gfx::IntRect visual_line_rect {
  1883. visual_data->visual_rect.x(),
  1884. visual_data->visual_rect.y() + ((int)visual_line_index * line_height()),
  1885. text_width_for_font(visual_line_view, font()) + font().glyph_spacing(),
  1886. line_height()
  1887. };
  1888. if (is_right_text_alignment(text_alignment()))
  1889. visual_line_rect.set_right_without_resize(editor_visible_text_rect.right());
  1890. if (is_single_line()) {
  1891. visual_line_rect.center_vertically_within(editor_visible_text_rect);
  1892. if (m_icon)
  1893. visual_line_rect.translate_by(icon_size() + icon_padding(), 0);
  1894. }
  1895. size_t start_of_line = visual_line_view.code_points() - line.code_points();
  1896. if (callback(visual_line_rect, visual_line_view, start_of_line, visual_line_index == visual_data->visual_lines.size() - 1) == IterationDecision::Break)
  1897. break;
  1898. ++visual_line_index;
  1899. }
  1900. }
  1901. void TextEditor::set_wrapping_mode(WrappingMode mode)
  1902. {
  1903. if (m_wrapping_mode == mode)
  1904. return;
  1905. m_wrapping_mode = mode;
  1906. horizontal_scrollbar().set_visible(m_wrapping_mode == WrappingMode::NoWrap);
  1907. update_content_size();
  1908. recompute_all_visual_lines();
  1909. update();
  1910. }
  1911. void TextEditor::add_custom_context_menu_action(Action& action)
  1912. {
  1913. m_custom_context_menu_actions.append(action);
  1914. }
  1915. void TextEditor::did_change_font()
  1916. {
  1917. vertical_scrollbar().set_step(line_height());
  1918. recompute_all_visual_lines();
  1919. update();
  1920. AbstractScrollableWidget::did_change_font();
  1921. }
  1922. void TextEditor::document_did_append_line()
  1923. {
  1924. m_line_data.append(make<LineData>());
  1925. recompute_all_visual_lines();
  1926. update();
  1927. }
  1928. void TextEditor::document_did_remove_line(size_t line_index)
  1929. {
  1930. m_line_data.remove(line_index);
  1931. recompute_all_visual_lines();
  1932. update();
  1933. }
  1934. void TextEditor::document_did_remove_all_lines()
  1935. {
  1936. m_line_data.clear();
  1937. recompute_all_visual_lines();
  1938. update();
  1939. }
  1940. void TextEditor::document_did_insert_line(size_t line_index)
  1941. {
  1942. m_line_data.insert(line_index, make<LineData>());
  1943. recompute_all_visual_lines();
  1944. update();
  1945. }
  1946. void TextEditor::document_did_change(AllowCallback allow_callback)
  1947. {
  1948. did_change(allow_callback);
  1949. update();
  1950. }
  1951. void TextEditor::document_did_update_undo_stack()
  1952. {
  1953. auto make_action_text = [](auto prefix, auto suffix) {
  1954. StringBuilder builder;
  1955. builder.append(prefix);
  1956. if (suffix.has_value()) {
  1957. builder.append(' ');
  1958. builder.append(suffix.value());
  1959. }
  1960. return builder.to_deprecated_string();
  1961. };
  1962. m_undo_action->set_enabled(can_undo() && !text_is_secret());
  1963. m_redo_action->set_enabled(can_redo() && !text_is_secret());
  1964. m_undo_action->set_text(make_action_text("&Undo"sv, document().undo_stack().undo_action_text()));
  1965. m_redo_action->set_text(make_action_text("&Redo"sv, document().undo_stack().redo_action_text()));
  1966. // FIXME: This is currently firing more often than it should.
  1967. // Ideally we'd only send this out when the undo stack modified state actually changes.
  1968. if (on_modified_change)
  1969. on_modified_change(document().is_modified());
  1970. }
  1971. void TextEditor::populate_line_data()
  1972. {
  1973. m_line_data.clear();
  1974. m_line_data.ensure_capacity(m_document->line_count());
  1975. for (size_t i = 0; i < m_document->line_count(); ++i) {
  1976. m_line_data.unchecked_append(make<LineData>());
  1977. }
  1978. }
  1979. void TextEditor::document_did_set_text(AllowCallback allow_callback)
  1980. {
  1981. populate_line_data();
  1982. document_did_change(allow_callback);
  1983. }
  1984. void TextEditor::document_did_set_cursor(TextPosition const& position)
  1985. {
  1986. set_cursor(position);
  1987. }
  1988. void TextEditor::cursor_did_change()
  1989. {
  1990. hide_autocomplete_if_needed();
  1991. }
  1992. void TextEditor::clipboard_content_did_change(DeprecatedString const& mime_type)
  1993. {
  1994. m_paste_action->set_enabled(is_editable() && mime_type.starts_with("text/"sv));
  1995. }
  1996. void TextEditor::set_document(TextDocument& document)
  1997. {
  1998. if (m_document.ptr() == &document)
  1999. return;
  2000. if (m_document)
  2001. m_document->unregister_client(*this);
  2002. m_document = document;
  2003. populate_line_data();
  2004. set_cursor(0, 0);
  2005. if (has_selection())
  2006. m_selection.clear();
  2007. recompute_all_visual_lines();
  2008. update();
  2009. m_document->register_client(*this);
  2010. }
  2011. void TextEditor::rehighlight_if_needed()
  2012. {
  2013. if (!m_needs_rehighlight)
  2014. return;
  2015. force_rehighlight();
  2016. }
  2017. void TextEditor::force_rehighlight()
  2018. {
  2019. if (m_highlighter)
  2020. m_highlighter->rehighlight(palette());
  2021. m_needs_rehighlight = false;
  2022. }
  2023. Syntax::Highlighter const* TextEditor::syntax_highlighter() const
  2024. {
  2025. return m_highlighter.ptr();
  2026. }
  2027. Syntax::Highlighter* TextEditor::syntax_highlighter()
  2028. {
  2029. return m_highlighter.ptr();
  2030. }
  2031. void TextEditor::set_syntax_highlighter(OwnPtr<Syntax::Highlighter> highlighter)
  2032. {
  2033. if (m_highlighter)
  2034. m_highlighter->detach();
  2035. m_highlighter = move(highlighter);
  2036. if (m_highlighter) {
  2037. m_highlighter->attach(*this);
  2038. m_needs_rehighlight = true;
  2039. } else
  2040. document().set_spans(Syntax::HighlighterClient::span_collection_index, {});
  2041. if (on_highlighter_change)
  2042. on_highlighter_change();
  2043. }
  2044. AutocompleteProvider const* TextEditor::autocomplete_provider() const
  2045. {
  2046. return m_autocomplete_provider.ptr();
  2047. }
  2048. void TextEditor::set_autocomplete_provider(OwnPtr<AutocompleteProvider>&& provider)
  2049. {
  2050. if (m_autocomplete_provider)
  2051. m_autocomplete_provider->detach();
  2052. m_autocomplete_provider = move(provider);
  2053. if (m_autocomplete_provider) {
  2054. m_autocomplete_provider->attach(*this);
  2055. if (!m_autocomplete_box)
  2056. m_autocomplete_box = make<AutocompleteBox>(*this);
  2057. }
  2058. if (m_autocomplete_box)
  2059. hide_autocomplete();
  2060. }
  2061. EditingEngine const* TextEditor::editing_engine() const
  2062. {
  2063. return m_editing_engine.ptr();
  2064. }
  2065. void TextEditor::set_editing_engine(OwnPtr<EditingEngine> editing_engine)
  2066. {
  2067. if (m_editing_engine)
  2068. m_editing_engine->detach();
  2069. m_editing_engine = move(editing_engine);
  2070. VERIFY(m_editing_engine);
  2071. m_editing_engine->attach(*this);
  2072. m_cursor_state = true;
  2073. update_cursor();
  2074. stop_timer();
  2075. start_timer(500);
  2076. }
  2077. int TextEditor::line_height() const
  2078. {
  2079. return static_cast<int>(ceilf(font().preferred_line_height()));
  2080. }
  2081. int TextEditor::fixed_glyph_width() const
  2082. {
  2083. VERIFY(font().is_fixed_width());
  2084. return font().glyph_width(' ');
  2085. }
  2086. void TextEditor::set_icon(Gfx::Bitmap const* icon)
  2087. {
  2088. if (m_icon == icon)
  2089. return;
  2090. m_icon = icon;
  2091. update();
  2092. }
  2093. void TextEditor::set_visualize_trailing_whitespace(bool enabled)
  2094. {
  2095. if (m_visualize_trailing_whitespace == enabled)
  2096. return;
  2097. m_visualize_trailing_whitespace = enabled;
  2098. update();
  2099. }
  2100. void TextEditor::set_visualize_leading_whitespace(bool enabled)
  2101. {
  2102. if (m_visualize_leading_whitespace == enabled)
  2103. return;
  2104. m_visualize_leading_whitespace = enabled;
  2105. update();
  2106. }
  2107. void TextEditor::set_should_autocomplete_automatically(bool value)
  2108. {
  2109. if (value == should_autocomplete_automatically())
  2110. return;
  2111. if (value) {
  2112. VERIFY(m_autocomplete_provider);
  2113. m_autocomplete_timer = Core::Timer::create_single_shot(m_automatic_autocomplete_delay_ms, [this] {
  2114. if (m_autocomplete_box && !m_autocomplete_box->is_visible())
  2115. try_show_autocomplete(UserRequestedAutocomplete::No);
  2116. }).release_value_but_fixme_should_propagate_errors();
  2117. return;
  2118. }
  2119. remove_child(*m_autocomplete_timer);
  2120. m_autocomplete_timer = nullptr;
  2121. }
  2122. void TextEditor::set_substitution_code_point(Optional<u32> code_point)
  2123. {
  2124. if (code_point.has_value())
  2125. VERIFY(is_unicode(code_point.value()));
  2126. m_substitution_string_data.clear();
  2127. m_substitution_code_point = move(code_point);
  2128. }
  2129. int TextEditor::number_of_visible_lines() const
  2130. {
  2131. return visible_content_rect().height() / line_height();
  2132. }
  2133. void TextEditor::set_relative_line_number(bool relative)
  2134. {
  2135. if (m_relative_line_number == relative)
  2136. return;
  2137. m_relative_line_number = relative;
  2138. recompute_all_visual_lines();
  2139. update();
  2140. }
  2141. void TextEditor::set_ruler_visible(bool visible)
  2142. {
  2143. if (m_ruler_visible == visible)
  2144. return;
  2145. m_ruler_visible = visible;
  2146. recompute_all_visual_lines();
  2147. update();
  2148. }
  2149. void TextEditor::set_gutter_visible(bool visible)
  2150. {
  2151. if (m_gutter_visible == visible)
  2152. return;
  2153. m_gutter_visible = visible;
  2154. recompute_all_visual_lines();
  2155. update();
  2156. }
  2157. void TextEditor::set_cursor_line_highlighting(bool highlighted)
  2158. {
  2159. if (m_cursor_line_highlighting == highlighted)
  2160. return;
  2161. m_cursor_line_highlighting = highlighted;
  2162. update();
  2163. }
  2164. void TextEditor::undo()
  2165. {
  2166. clear_selection();
  2167. document().undo();
  2168. }
  2169. void TextEditor::redo()
  2170. {
  2171. clear_selection();
  2172. document().redo();
  2173. }
  2174. void TextEditor::set_text_is_secret(bool text_is_secret)
  2175. {
  2176. m_text_is_secret = text_is_secret;
  2177. document_did_update_undo_stack();
  2178. did_update_selection();
  2179. }
  2180. TextRange TextEditor::find_text(StringView needle, SearchDirection direction, GUI::TextDocument::SearchShouldWrap should_wrap, bool use_regex, bool match_case)
  2181. {
  2182. GUI::TextRange range {};
  2183. if (direction == SearchDirection::Forward) {
  2184. range = document().find_next(needle,
  2185. m_search_result_index.has_value() ? m_search_results[*m_search_result_index].end() : GUI::TextPosition {},
  2186. should_wrap, use_regex, match_case);
  2187. } else {
  2188. range = document().find_previous(needle,
  2189. m_search_result_index.has_value() ? m_search_results[*m_search_result_index].start() : GUI::TextPosition {},
  2190. should_wrap, use_regex, match_case);
  2191. }
  2192. if (!range.is_valid()) {
  2193. reset_search_results();
  2194. return {};
  2195. }
  2196. auto all_results = document().find_all(needle, use_regex, match_case);
  2197. on_search_results(range, all_results);
  2198. return range;
  2199. }
  2200. void TextEditor::reset_search_results()
  2201. {
  2202. m_search_result_index.clear();
  2203. m_search_results.clear();
  2204. document().set_spans(search_results_span_collection_index, {});
  2205. update();
  2206. }
  2207. void TextEditor::on_search_results(GUI::TextRange current, Vector<GUI::TextRange> all_results)
  2208. {
  2209. m_search_result_index.clear();
  2210. m_search_results.clear();
  2211. set_cursor(current.start());
  2212. if (auto it = all_results.find(current); it->is_valid())
  2213. m_search_result_index = it.index();
  2214. m_search_results = move(all_results);
  2215. Vector<GUI::TextDocumentSpan> spans;
  2216. for (size_t i = 0; i < m_search_results.size(); ++i) {
  2217. auto& result = m_search_results[i];
  2218. GUI::TextDocumentSpan span;
  2219. span.range = result;
  2220. span.attributes.background_color = palette().hover_highlight();
  2221. span.attributes.color = Color::from_argb(0xff000000); // So text without spans from a highlighter will have color
  2222. if (i == m_search_result_index) {
  2223. span.attributes.bold = true;
  2224. span.attributes.underline_style = Gfx::TextAttributes::UnderlineStyle::Solid;
  2225. }
  2226. spans.append(move(span));
  2227. }
  2228. document().set_spans(search_results_span_collection_index, move(spans));
  2229. update();
  2230. }
  2231. void TextEditor::highlighter_did_set_folding_regions(Vector<GUI::TextDocumentFoldingRegion> folding_regions)
  2232. {
  2233. document().set_folding_regions(move(folding_regions));
  2234. recompute_all_visual_lines();
  2235. }
  2236. ErrorOr<TextEditor::GutterIndicatorID> TextEditor::register_gutter_indicator(PaintGutterIndicator draw_indicator, OnGutterIndicatorClick on_click)
  2237. {
  2238. // We use a u32 to store a line's active gutter indicators, so that's the limit of how many we can have.
  2239. VERIFY(m_gutter_indicators.size() < 32);
  2240. GutterIndicatorID id = m_gutter_indicators.size();
  2241. TRY(m_gutter_indicators.try_empend(move(draw_indicator), move(on_click)));
  2242. return id;
  2243. }
  2244. void TextEditor::add_gutter_indicator(GutterIndicatorID id, size_t line)
  2245. {
  2246. auto& line_indicators = m_line_data[line]->gutter_indicators;
  2247. if (line_indicators & (1 << id.value()))
  2248. return;
  2249. line_indicators |= (1 << id.value());
  2250. // Ensure the gutter is at least wide enough to display all the indicators on this line.
  2251. if (m_most_gutter_indicators_displayed_on_one_line < m_gutter_indicators.size()) {
  2252. unsigned indicators_on_line = popcount(line_indicators);
  2253. if (indicators_on_line > m_most_gutter_indicators_displayed_on_one_line) {
  2254. m_most_gutter_indicators_displayed_on_one_line = indicators_on_line;
  2255. update();
  2256. }
  2257. }
  2258. update(gutter_content_rect(line));
  2259. }
  2260. void TextEditor::remove_gutter_indicator(GutterIndicatorID id, size_t line)
  2261. {
  2262. m_line_data[line]->gutter_indicators &= ~(1 << id.value());
  2263. update(gutter_content_rect(line));
  2264. }
  2265. void TextEditor::clear_gutter_indicators(GutterIndicatorID id)
  2266. {
  2267. for (auto line = 0u; line < line_count(); ++line)
  2268. remove_gutter_indicator(id, line);
  2269. update();
  2270. }
  2271. }