TextEditor.cpp 59 KB

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