TextEditor.cpp 71 KB

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