TextEditor.cpp 53 KB

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