TextEditor.cpp 88 KB

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