TextEditor.cpp 60 KB

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