TextEditor.cpp 58 KB

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