TextEditor.cpp 54 KB

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