TextEditor.cpp 80 KB

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