TextEditor.cpp 54 KB

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