TextEditor.cpp 80 KB

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