TextEditor.cpp 54 KB

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