TextEditor.cpp 62 KB

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