TextEditor.cpp 70 KB

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