TextEditor.cpp 58 KB

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