TextEditor.cpp 59 KB

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