TextEditor.cpp 75 KB

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