TextEditor.cpp 83 KB

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