TextEditor.cpp 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, Jakob-Niklas See <git@nwex.de>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/CharacterTypes.h>
  8. #include <AK/Debug.h>
  9. #include <AK/ScopeGuard.h>
  10. #include <AK/StringBuilder.h>
  11. #include <AK/TemporaryChange.h>
  12. #include <LibCore/Timer.h>
  13. #include <LibGUI/Action.h>
  14. #include <LibGUI/AutocompleteProvider.h>
  15. #include <LibGUI/Clipboard.h>
  16. #include <LibGUI/EditingEngine.h>
  17. #include <LibGUI/InputBox.h>
  18. #include <LibGUI/Menu.h>
  19. #include <LibGUI/Painter.h>
  20. #include <LibGUI/RegularEditingEngine.h>
  21. #include <LibGUI/Scrollbar.h>
  22. #include <LibGUI/TextEditor.h>
  23. #include <LibGUI/Window.h>
  24. #include <LibGfx/Bitmap.h>
  25. #include <LibGfx/Font.h>
  26. #include <LibGfx/FontDatabase.h>
  27. #include <LibGfx/Palette.h>
  28. #include <LibSyntax/Highlighter.h>
  29. #include <fcntl.h>
  30. #include <stdio.h>
  31. #include <unistd.h>
  32. REGISTER_WIDGET(GUI, TextEditor)
  33. namespace GUI {
  34. TextEditor::TextEditor(Type type)
  35. : m_type(type)
  36. {
  37. REGISTER_STRING_PROPERTY("text", text, set_text);
  38. REGISTER_STRING_PROPERTY("placeholder", placeholder, set_placeholder);
  39. REGISTER_BOOL_PROPERTY("gutter", is_gutter_visible, set_gutter_visible);
  40. REGISTER_BOOL_PROPERTY("ruler", is_ruler_visible, set_ruler_visible);
  41. REGISTER_ENUM_PROPERTY("mode", mode, set_mode, Mode,
  42. { Editable, "Editable" },
  43. { ReadOnly, "ReadOnly" },
  44. { DisplayOnly, "DisplayOnly" });
  45. set_focus_policy(GUI::FocusPolicy::StrongFocus);
  46. set_accepts_emoji_input(true);
  47. set_override_cursor(Gfx::StandardCursor::IBeam);
  48. set_background_role(ColorRole::Base);
  49. set_foreground_role(ColorRole::BaseText);
  50. set_document(TextDocument::create());
  51. if (is_single_line())
  52. set_visualize_trailing_whitespace(false);
  53. set_scrollbars_enabled(is_multi_line());
  54. if (is_multi_line())
  55. set_font(Gfx::FontDatabase::default_fixed_width_font());
  56. vertical_scrollbar().set_step(line_height());
  57. m_cursor = { 0, 0 };
  58. m_automatic_selection_scroll_timer = add<Core::Timer>(100, [this] {
  59. automatic_selection_scroll_timer_fired();
  60. });
  61. m_automatic_selection_scroll_timer->stop();
  62. create_actions();
  63. set_editing_engine(make<RegularEditingEngine>());
  64. }
  65. TextEditor::~TextEditor()
  66. {
  67. if (m_document)
  68. m_document->unregister_client(*this);
  69. }
  70. void TextEditor::create_actions()
  71. {
  72. m_undo_action = CommonActions::make_undo_action([&](auto&) { undo(); }, this);
  73. m_redo_action = CommonActions::make_redo_action([&](auto&) { redo(); }, this);
  74. m_undo_action->set_enabled(false);
  75. m_redo_action->set_enabled(false);
  76. m_cut_action = CommonActions::make_cut_action([&](auto&) { cut(); }, this);
  77. m_copy_action = CommonActions::make_copy_action([&](auto&) { copy(); }, this);
  78. m_cut_action->set_enabled(false);
  79. m_copy_action->set_enabled(false);
  80. m_paste_action = CommonActions::make_paste_action([&](auto&) { paste(); }, this);
  81. m_paste_action->set_enabled(is_editable() && Clipboard::the().fetch_mime_type().starts_with("text/"));
  82. if (is_multi_line()) {
  83. m_go_to_line_action = Action::create(
  84. "Go to line...", { Mod_Ctrl, Key_L }, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/go-forward.png").release_value_but_fixme_should_propagate_errors(), [this](auto&) {
  85. String value;
  86. if (InputBox::show(window(), value, "Line:", "Go to line") == InputBox::ExecOK) {
  87. auto line_target = value.to_uint();
  88. if (line_target.has_value()) {
  89. set_cursor_and_focus_line(line_target.value() - 1, 0);
  90. }
  91. }
  92. },
  93. this);
  94. }
  95. m_select_all_action = CommonActions::make_select_all_action([this](auto&) { select_all(); }, this);
  96. }
  97. void TextEditor::set_text(StringView text, AllowCallback allow_callback)
  98. {
  99. m_selection.clear();
  100. document().set_text(text, allow_callback);
  101. update_content_size();
  102. recompute_all_visual_lines();
  103. if (is_single_line())
  104. set_cursor(0, line(0).length());
  105. else
  106. set_cursor(0, 0);
  107. did_update_selection();
  108. update();
  109. }
  110. void TextEditor::update_content_size()
  111. {
  112. int content_width = 0;
  113. int content_height = 0;
  114. for (auto& line : m_line_visual_data) {
  115. content_width = max(line.visual_rect.width(), content_width);
  116. content_height += line.visual_rect.height();
  117. }
  118. content_width += m_horizontal_content_padding * 2;
  119. if (is_right_text_alignment(m_text_alignment))
  120. content_width = max(frame_inner_rect().width(), content_width);
  121. set_content_size({ content_width, content_height });
  122. set_size_occupied_by_fixed_elements({ ruler_width() + gutter_width(), 0 });
  123. }
  124. TextPosition TextEditor::text_position_at_content_position(Gfx::IntPoint const& content_position) const
  125. {
  126. auto position = content_position;
  127. if (is_single_line() && icon())
  128. position.translate_by(-(icon_size() + icon_padding()), 0);
  129. size_t line_index = 0;
  130. if (position.y() >= 0) {
  131. if (is_wrapping_enabled()) {
  132. for (size_t i = 0; i < line_count(); ++i) {
  133. auto& rect = m_line_visual_data[i].visual_rect;
  134. if (position.y() >= rect.top() && position.y() <= rect.bottom()) {
  135. line_index = i;
  136. break;
  137. }
  138. if (position.y() > rect.bottom())
  139. line_index = line_count() - 1;
  140. }
  141. } else {
  142. line_index = (size_t)(position.y() / line_height());
  143. }
  144. line_index = max((size_t)0, min(line_index, line_count() - 1));
  145. }
  146. size_t column_index = 0;
  147. switch (m_text_alignment) {
  148. case Gfx::TextAlignment::CenterLeft:
  149. for_each_visual_line(line_index, [&](Gfx::IntRect const& rect, auto& view, size_t start_of_line, [[maybe_unused]] bool is_last_visual_line) {
  150. if (is_multi_line() && !rect.contains_vertically(position.y()) && !is_last_visual_line)
  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_or_emoji_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. VERIFY(!is_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. VERIFY_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. TextPosition TextEditor::text_position_at(Gfx::IntPoint const& widget_position) const
  181. {
  182. auto content_position = widget_position;
  183. content_position.translate_by(horizontal_scrollbar().value(), vertical_scrollbar().value());
  184. content_position.translate_by(-(m_horizontal_content_padding + ruler_width() + gutter_width()), 0);
  185. content_position.translate_by(-frame_thickness(), -frame_thickness());
  186. return text_position_at_content_position(content_position);
  187. }
  188. void TextEditor::doubleclick_event(MouseEvent& event)
  189. {
  190. if (event.button() != MouseButton::Primary)
  191. return;
  192. if (is_displayonly())
  193. return;
  194. if (!current_line().can_select())
  195. return;
  196. rehighlight_if_needed();
  197. m_triple_click_timer.start();
  198. m_in_drag_select = false;
  199. auto position = text_position_at(event.position());
  200. if (m_substitution_code_point) {
  201. // NOTE: If we substitute the code points, we don't want double clicking to only select a single word, since
  202. // whitespace isn't visible anymore.
  203. m_selection = document().range_for_entire_line(position.line());
  204. } else if (document().has_spans()) {
  205. for (auto& span : document().spans()) {
  206. if (span.range.contains(position)) {
  207. m_selection = span.range;
  208. break;
  209. }
  210. }
  211. } else {
  212. m_selection.set_start(document().first_word_break_before(position, false));
  213. m_selection.set_end(document().first_word_break_after(position));
  214. }
  215. set_cursor(m_selection.end());
  216. update();
  217. did_update_selection();
  218. }
  219. void TextEditor::mousedown_event(MouseEvent& event)
  220. {
  221. if (event.button() != MouseButton::Primary) {
  222. return;
  223. }
  224. if (on_mousedown)
  225. on_mousedown();
  226. if (is_displayonly())
  227. return;
  228. if (m_triple_click_timer.is_valid() && m_triple_click_timer.elapsed() < 250) {
  229. m_triple_click_timer = Core::ElapsedTimer();
  230. select_current_line();
  231. return;
  232. }
  233. if (event.modifiers() & Mod_Shift) {
  234. if (!has_selection())
  235. m_selection.set(m_cursor, {});
  236. } else {
  237. m_selection.clear();
  238. }
  239. m_in_drag_select = true;
  240. m_automatic_selection_scroll_timer->start();
  241. set_cursor(text_position_at(event.position()));
  242. if (!(event.modifiers() & Mod_Shift)) {
  243. if (!has_selection())
  244. m_selection.set(m_cursor, {});
  245. }
  246. if (m_selection.start().is_valid() && m_selection.start() != m_cursor)
  247. m_selection.set_end(m_cursor);
  248. // FIXME: Only update the relevant rects.
  249. update();
  250. did_update_selection();
  251. }
  252. void TextEditor::mouseup_event(MouseEvent& event)
  253. {
  254. if (event.button() == MouseButton::Primary) {
  255. if (m_in_drag_select) {
  256. m_in_drag_select = false;
  257. }
  258. return;
  259. }
  260. }
  261. void TextEditor::mousemove_event(MouseEvent& event)
  262. {
  263. m_last_mousemove_position = event.position();
  264. if (m_in_drag_select && (rect().contains(event.position()) || !m_automatic_selection_scroll_timer->is_active())) {
  265. set_cursor(text_position_at(event.position()));
  266. m_selection.set_end(m_cursor);
  267. did_update_selection();
  268. update();
  269. return;
  270. }
  271. }
  272. void TextEditor::select_current_line()
  273. {
  274. m_selection = document().range_for_entire_line(m_cursor.line());
  275. set_cursor(m_selection.end());
  276. update();
  277. did_update_selection();
  278. }
  279. void TextEditor::automatic_selection_scroll_timer_fired()
  280. {
  281. if (!m_in_drag_select) {
  282. m_automatic_selection_scroll_timer->stop();
  283. return;
  284. }
  285. set_cursor(text_position_at(m_last_mousemove_position));
  286. m_selection.set_end(m_cursor);
  287. did_update_selection();
  288. update();
  289. }
  290. int TextEditor::ruler_width() const
  291. {
  292. if (!m_ruler_visible)
  293. return 0;
  294. int line_count_digits = static_cast<int>(log10(line_count())) + 1;
  295. constexpr size_t padding = 5;
  296. return line_count() < 10 ? (line_count_digits + 1) * font().glyph_width('x') + padding : line_count_digits * font().glyph_width('x') + padding;
  297. }
  298. int TextEditor::gutter_width() const
  299. {
  300. if (!m_gutter_visible)
  301. return 0;
  302. return line_height(); // square gutter
  303. }
  304. Gfx::IntRect TextEditor::ruler_content_rect(size_t line_index) const
  305. {
  306. if (!m_ruler_visible)
  307. return {};
  308. return {
  309. 0 - ruler_width() + horizontal_scrollbar().value(),
  310. line_content_rect(line_index).y(),
  311. ruler_width(),
  312. line_content_rect(line_index).height()
  313. };
  314. }
  315. Gfx::IntRect TextEditor::gutter_content_rect(size_t line_index) const
  316. {
  317. if (!m_gutter_visible)
  318. return {};
  319. return {
  320. 0 - ruler_width() - gutter_width() + horizontal_scrollbar().value(),
  321. line_content_rect(line_index).y(),
  322. gutter_width(),
  323. line_content_rect(line_index).height()
  324. };
  325. }
  326. Gfx::IntRect TextEditor::ruler_rect_in_inner_coordinates() const
  327. {
  328. return { gutter_width(), 0, ruler_width(), widget_inner_rect().height() };
  329. }
  330. Gfx::IntRect TextEditor::gutter_rect_in_inner_coordinates() const
  331. {
  332. return { 0, 0, gutter_width(), widget_inner_rect().height() };
  333. }
  334. Gfx::IntRect TextEditor::visible_text_rect_in_inner_coordinates() const
  335. {
  336. return {
  337. m_horizontal_content_padding + (m_ruler_visible ? (ruler_rect_in_inner_coordinates().right() + 1) : 0),
  338. 0,
  339. frame_inner_rect().width() - (m_horizontal_content_padding * 2) - width_occupied_by_vertical_scrollbar() - ruler_width(),
  340. frame_inner_rect().height() - height_occupied_by_horizontal_scrollbar()
  341. };
  342. }
  343. void TextEditor::paint_event(PaintEvent& event)
  344. {
  345. Color widget_background_color = palette().color(is_enabled() ? background_role() : Gfx::ColorRole::Window);
  346. rehighlight_if_needed();
  347. Frame::paint_event(event);
  348. Painter painter(*this);
  349. painter.add_clip_rect(widget_inner_rect());
  350. painter.add_clip_rect(event.rect());
  351. painter.fill_rect(event.rect(), widget_background_color);
  352. // NOTE: This lambda and TextEditor::text_width_for_font() are used to substitute all glyphs with m_substitution_code_point if necessary.
  353. // Painter::draw_text() and Gfx::Font::width() should not be called directly, but using this lambda and TextEditor::text_width_for_font().
  354. auto draw_text = [&](Gfx::IntRect const& rect, auto const& raw_text, Gfx::Font const& font, Gfx::TextAlignment alignment, Gfx::TextAttributes attributes, bool substitute = true) {
  355. if (m_substitution_code_point && substitute) {
  356. painter.draw_text(rect, substitution_code_point_view(raw_text.length()), font, alignment, attributes.color);
  357. } else {
  358. painter.draw_text(rect, raw_text, font, alignment, attributes.color);
  359. }
  360. if (attributes.underline) {
  361. if (attributes.underline_style == Gfx::TextAttributes::UnderlineStyle::Solid)
  362. painter.draw_line(rect.bottom_left().translated(0, 1), rect.bottom_right().translated(0, 1), attributes.underline_color.value_or(attributes.color));
  363. if (attributes.underline_style == Gfx::TextAttributes::UnderlineStyle::Wavy)
  364. painter.draw_triangle_wave(rect.bottom_left().translated(0, 1), rect.bottom_right().translated(0, 1), attributes.underline_color.value_or(attributes.color), 2);
  365. }
  366. };
  367. if (is_displayonly() && is_focused()) {
  368. Gfx::IntRect display_rect {
  369. widget_inner_rect().x() + 1,
  370. widget_inner_rect().y() + 1,
  371. widget_inner_rect().width() - 2,
  372. widget_inner_rect().height() - 2
  373. };
  374. painter.fill_rect(display_rect, palette().selection());
  375. }
  376. painter.translate(frame_thickness(), frame_thickness());
  377. if (!is_multi_line() && m_icon) {
  378. Gfx::IntRect icon_rect { icon_padding(), 1, icon_size(), icon_size() };
  379. painter.draw_scaled_bitmap(icon_rect, *m_icon, m_icon->rect());
  380. }
  381. if (m_gutter_visible) {
  382. auto gutter_rect = gutter_rect_in_inner_coordinates();
  383. painter.fill_rect(gutter_rect, palette().gutter());
  384. if (!m_ruler_visible)
  385. painter.draw_line(gutter_rect.top_right(), gutter_rect.bottom_right(), palette().gutter_border());
  386. }
  387. if (m_ruler_visible) {
  388. auto ruler_rect = ruler_rect_in_inner_coordinates();
  389. painter.fill_rect(ruler_rect, palette().ruler());
  390. painter.draw_line(ruler_rect.top_right(), ruler_rect.bottom_right(), palette().ruler_border());
  391. }
  392. painter.translate(-horizontal_scrollbar().value(), -vertical_scrollbar().value());
  393. painter.translate(gutter_width(), 0);
  394. painter.translate(ruler_width(), 0);
  395. size_t first_visible_line = text_position_at(event.rect().top_left()).line();
  396. size_t last_visible_line = text_position_at(event.rect().bottom_right()).line();
  397. auto selection = normalized_selection();
  398. bool has_selection = selection.is_valid();
  399. if (m_ruler_visible) {
  400. for (size_t i = first_visible_line; i <= last_visible_line; ++i) {
  401. bool is_current_line = i == m_cursor.line();
  402. auto ruler_line_rect = ruler_content_rect(i);
  403. // NOTE: Use Painter::draw_text() directly here, as we want to always draw the line numbers in clear text.
  404. painter.draw_text(
  405. ruler_line_rect.shrunken(2, 0).translated(0, m_line_spacing / 2),
  406. String::number(i + 1),
  407. is_current_line ? font().bold_variant() : font(),
  408. Gfx::TextAlignment::TopRight,
  409. is_current_line ? palette().ruler_active_text() : palette().ruler_inactive_text());
  410. }
  411. }
  412. auto gutter_ruler_width = gutter_width() + ruler_width();
  413. Gfx::IntRect text_clip_rect { 0, 0, widget_inner_rect().width() - gutter_ruler_width, widget_inner_rect().height() };
  414. text_clip_rect.translate_by(horizontal_scrollbar().value(), vertical_scrollbar().value());
  415. painter.add_clip_rect(text_clip_rect);
  416. size_t span_index = 0;
  417. if (document().has_spans()) {
  418. for (;;) {
  419. if (span_index >= document().spans().size() || document().spans()[span_index].range.end().line() >= first_visible_line) {
  420. break;
  421. }
  422. ++span_index;
  423. }
  424. }
  425. for (size_t line_index = first_visible_line; line_index <= last_visible_line; ++line_index) {
  426. auto& line = this->line(line_index);
  427. bool physical_line_has_selection = has_selection && line_index >= selection.start().line() && line_index <= selection.end().line();
  428. size_t first_visual_line_with_selection = 0;
  429. size_t last_visual_line_with_selection = 0;
  430. if (physical_line_has_selection) {
  431. if (selection.start().line() < line_index)
  432. first_visual_line_with_selection = 0;
  433. else
  434. first_visual_line_with_selection = visual_line_containing(line_index, selection.start().column());
  435. if (selection.end().line() > line_index)
  436. last_visual_line_with_selection = m_line_visual_data[line_index].visual_line_breaks.size();
  437. else
  438. last_visual_line_with_selection = visual_line_containing(line_index, selection.end().column());
  439. }
  440. size_t selection_start_column_within_line = selection.start().line() == line_index ? selection.start().column() : 0;
  441. size_t selection_end_column_within_line = selection.end().line() == line_index ? selection.end().column() : line.length();
  442. size_t visual_line_index = 0;
  443. for_each_visual_line(line_index, [&](Gfx::IntRect const& visual_line_rect, auto& visual_line_text, size_t start_of_visual_line, [[maybe_unused]] bool is_last_visual_line) {
  444. if (is_focused() && is_multi_line() && line_index == m_cursor.line() && is_cursor_line_highlighted()) {
  445. Gfx::IntRect visible_content_line_rect {
  446. visible_content_rect().x(),
  447. visual_line_rect.y(),
  448. widget_inner_rect().width() - gutter_ruler_width,
  449. line_height()
  450. };
  451. painter.fill_rect(visible_content_line_rect, widget_background_color.darkened(0.9f));
  452. }
  453. if constexpr (TEXTEDITOR_DEBUG)
  454. painter.draw_rect(visual_line_rect, Color::Cyan);
  455. if (!placeholder().is_empty() && document().is_empty() && line_index == 0) {
  456. auto line_rect = visual_line_rect;
  457. line_rect.set_width(text_width_for_font(placeholder(), font()));
  458. draw_text(line_rect, placeholder(), font(), m_text_alignment, { palette().color(Gfx::ColorRole::PlaceholderText) }, false);
  459. } else if (!document().has_spans()) {
  460. // Fast-path for plain text
  461. auto color = palette().color(is_enabled() ? foreground_role() : Gfx::ColorRole::DisabledText);
  462. if (is_displayonly() && is_focused())
  463. color = palette().color(is_enabled() ? Gfx::ColorRole::SelectionText : Gfx::ColorRole::DisabledText);
  464. draw_text(visual_line_rect, visual_line_text, font(), m_text_alignment, { color });
  465. } else {
  466. auto unspanned_color = palette().color(is_enabled() ? foreground_role() : Gfx::ColorRole::DisabledText);
  467. if (is_displayonly() && is_focused())
  468. unspanned_color = palette().color(is_enabled() ? Gfx::ColorRole::SelectionText : Gfx::ColorRole::DisabledText);
  469. RefPtr<Gfx::Font> unspanned_font = this->font();
  470. size_t next_column = 0;
  471. Gfx::IntRect span_rect = { visual_line_rect.location(), { 0, line_height() } };
  472. auto draw_text_helper = [&](size_t start, size_t end, RefPtr<Gfx::Font>& font, Gfx::TextAttributes text_attributes) {
  473. size_t length = end - start;
  474. if (length == 0)
  475. return;
  476. auto text = visual_line_text.substring_view(start, length);
  477. span_rect.set_width(font->width(text));
  478. if (text_attributes.background_color.has_value()) {
  479. painter.fill_rect(span_rect, text_attributes.background_color.value());
  480. }
  481. draw_text(span_rect, text, *font, m_text_alignment, text_attributes);
  482. span_rect.translate_by(span_rect.width(), 0);
  483. };
  484. for (;;) {
  485. if (span_index >= document().spans().size()) {
  486. break;
  487. }
  488. auto& span = document().spans()[span_index];
  489. if (!span.range.is_valid()) {
  490. ++span_index;
  491. continue;
  492. }
  493. if (span.range.end().line() < line_index) {
  494. dbgln_if(TEXTEDITOR_DEBUG, "spans not sorted (span end {}:{} is before current line {}) => ignoring", span.range.end().line(), span.range.end().column(), line_index);
  495. ++span_index;
  496. continue;
  497. }
  498. if (span.range.start().line() > line_index
  499. || (span.range.start().line() == line_index && span.range.start().column() >= start_of_visual_line + visual_line_text.length())) {
  500. // no more spans in this line, moving on
  501. break;
  502. }
  503. if (span.range.start().line() == span.range.end().line() && span.range.end().column() < span.range.start().column()) {
  504. dbgln_if(TEXTEDITOR_DEBUG, "span from {}:{} to {}:{} has negative length => ignoring", span.range.start().line(), span.range.start().column(), span.range.end().line(), span.range.end().column());
  505. ++span_index;
  506. continue;
  507. }
  508. if (span.range.end().line() == line_index && span.range.end().column() < start_of_visual_line + next_column) {
  509. dbgln_if(TEXTEDITOR_DEBUG, "spans not sorted (span end {}:{} is before current position {}:{}) => ignoring",
  510. span.range.end().line(), span.range.end().column(), line_index, start_of_visual_line + next_column);
  511. ++span_index;
  512. continue;
  513. }
  514. size_t span_start;
  515. if (span.range.start().line() < line_index || span.range.start().column() < start_of_visual_line) {
  516. span_start = 0;
  517. } else {
  518. span_start = span.range.start().column() - start_of_visual_line;
  519. }
  520. if (span_start < next_column) {
  521. dbgln_if(TEXTEDITOR_DEBUG, "span started before the current position, maybe two spans overlap? (span start {} is before current position {}) => ignoring", span_start, next_column);
  522. ++span_index;
  523. continue;
  524. }
  525. size_t span_end;
  526. bool span_consumned;
  527. if (span.range.end().line() > line_index || span.range.end().column() > start_of_visual_line + visual_line_text.length()) {
  528. span_end = visual_line_text.length();
  529. span_consumned = false;
  530. } else {
  531. span_end = span.range.end().column() - start_of_visual_line;
  532. span_consumned = true;
  533. }
  534. if (span_start != next_column) {
  535. // draw unspanned text between spans
  536. draw_text_helper(next_column, span_start, unspanned_font, { unspanned_color });
  537. }
  538. auto font = unspanned_font;
  539. if (span.attributes.bold) {
  540. if (auto bold_font = Gfx::FontDatabase::the().get(font->family(), font->presentation_size(), 700, 0))
  541. font = bold_font;
  542. }
  543. draw_text_helper(span_start, span_end, font, span.attributes);
  544. next_column = span_end;
  545. if (!span_consumned) {
  546. // continue with same span on next line
  547. break;
  548. } else {
  549. ++span_index;
  550. }
  551. }
  552. // draw unspanned text after last span
  553. if (next_column < visual_line_text.length()) {
  554. draw_text_helper(next_column, visual_line_text.length(), unspanned_font, { unspanned_color });
  555. }
  556. // consume all spans that should end this line
  557. // this is necessary since the spans can include the new line character
  558. while (is_last_visual_line && span_index < document().spans().size()) {
  559. auto& span = document().spans()[span_index];
  560. if (span.range.end().line() == line_index) {
  561. ++span_index;
  562. } else {
  563. break;
  564. }
  565. }
  566. }
  567. if (m_visualize_trailing_whitespace && line.ends_in_whitespace()) {
  568. size_t physical_column;
  569. auto last_non_whitespace_column = line.last_non_whitespace_column();
  570. if (last_non_whitespace_column.has_value())
  571. physical_column = last_non_whitespace_column.value() + 1;
  572. else
  573. physical_column = 0;
  574. size_t end_of_visual_line = (start_of_visual_line + visual_line_text.length());
  575. if (physical_column < end_of_visual_line) {
  576. size_t visual_column = physical_column > start_of_visual_line ? (physical_column - start_of_visual_line) : 0;
  577. Gfx::IntRect whitespace_rect {
  578. content_x_for_position({ line_index, visual_column }),
  579. visual_line_rect.y(),
  580. text_width_for_font(visual_line_text.substring_view(visual_column, visual_line_text.length() - visual_column), font()),
  581. visual_line_rect.height()
  582. };
  583. painter.fill_rect_with_dither_pattern(whitespace_rect, Color(), Color(255, 192, 192));
  584. }
  585. }
  586. if (m_visualize_leading_whitespace && line.leading_spaces() > 0) {
  587. size_t physical_column = line.leading_spaces();
  588. if (start_of_visual_line < physical_column) {
  589. size_t end_of_leading_whitespace = min(physical_column - start_of_visual_line, visual_line_text.length());
  590. Gfx::IntRect whitespace_rect {
  591. content_x_for_position({ line_index, start_of_visual_line }),
  592. visual_line_rect.y(),
  593. text_width_for_font(visual_line_text.substring_view(0, end_of_leading_whitespace), font()),
  594. visual_line_rect.height()
  595. };
  596. painter.fill_rect_with_dither_pattern(whitespace_rect, Color(), Color(192, 255, 192));
  597. }
  598. }
  599. if (physical_line_has_selection && window()->focused_widget() == this) {
  600. size_t start_of_selection_within_visual_line = (size_t)max(0, (int)selection_start_column_within_line - (int)start_of_visual_line);
  601. size_t end_of_selection_within_visual_line = selection_end_column_within_line - start_of_visual_line;
  602. bool current_visual_line_has_selection = start_of_selection_within_visual_line != end_of_selection_within_visual_line
  603. && ((line_index != selection.start().line() && line_index != selection.end().line())
  604. || (visual_line_index >= first_visual_line_with_selection && visual_line_index <= last_visual_line_with_selection));
  605. if (current_visual_line_has_selection) {
  606. bool selection_begins_on_current_visual_line = visual_line_index == first_visual_line_with_selection;
  607. bool selection_ends_on_current_visual_line = visual_line_index == last_visual_line_with_selection;
  608. int selection_left = selection_begins_on_current_visual_line
  609. ? content_x_for_position({ line_index, (size_t)selection_start_column_within_line })
  610. : m_horizontal_content_padding;
  611. int selection_right = selection_ends_on_current_visual_line
  612. ? content_x_for_position({ line_index, (size_t)selection_end_column_within_line })
  613. : visual_line_rect.right() + 1;
  614. Gfx::IntRect selection_rect {
  615. selection_left,
  616. visual_line_rect.y(),
  617. selection_right - selection_left,
  618. visual_line_rect.height()
  619. };
  620. Color background_color = window()->is_active() ? palette().selection() : palette().inactive_selection();
  621. Color text_color = window()->is_active() ? palette().selection_text() : palette().inactive_selection_text();
  622. painter.fill_rect(selection_rect, background_color);
  623. if (visual_line_text.code_points()) {
  624. Utf32View visual_selected_text {
  625. visual_line_text.code_points() + start_of_selection_within_visual_line,
  626. end_of_selection_within_visual_line - start_of_selection_within_visual_line
  627. };
  628. draw_text(selection_rect, visual_selected_text, font(), Gfx::TextAlignment::CenterLeft, { text_color });
  629. }
  630. }
  631. }
  632. ++visual_line_index;
  633. return IterationDecision::Continue;
  634. });
  635. }
  636. if (is_enabled() && is_focused() && m_cursor_state && !is_displayonly())
  637. painter.fill_rect(cursor_content_rect(), palette().text_cursor());
  638. }
  639. void TextEditor::select_all()
  640. {
  641. TextPosition start_of_document { 0, 0 };
  642. TextPosition end_of_document { line_count() - 1, line(line_count() - 1).length() };
  643. m_selection.set(end_of_document, start_of_document);
  644. did_update_selection();
  645. set_cursor(start_of_document);
  646. update();
  647. }
  648. void TextEditor::keydown_event(KeyEvent& event)
  649. {
  650. if (m_autocomplete_box && m_autocomplete_box->is_visible() && (event.key() == KeyCode::Key_Return || event.key() == KeyCode::Key_Tab)) {
  651. TemporaryChange change { m_should_keep_autocomplete_box, true };
  652. if (m_autocomplete_box->apply_suggestion() == AutocompleteProvider::Entry::HideAutocompleteAfterApplying::Yes)
  653. hide_autocomplete();
  654. else
  655. try_update_autocomplete();
  656. return;
  657. }
  658. if (m_autocomplete_box && m_autocomplete_box->is_visible() && event.key() == KeyCode::Key_Escape) {
  659. hide_autocomplete();
  660. return;
  661. }
  662. if (m_autocomplete_box && m_autocomplete_box->is_visible() && event.key() == KeyCode::Key_Up) {
  663. m_autocomplete_box->previous_suggestion();
  664. return;
  665. }
  666. if (m_autocomplete_box && m_autocomplete_box->is_visible() && event.key() == KeyCode::Key_Down) {
  667. m_autocomplete_box->next_suggestion();
  668. return;
  669. }
  670. if (is_single_line()) {
  671. if (event.key() == KeyCode::Key_Tab)
  672. return AbstractScrollableWidget::keydown_event(event);
  673. if (event.modifiers() == KeyModifier::Mod_Shift && event.key() == KeyCode::Key_Return) {
  674. if (on_shift_return_pressed)
  675. on_shift_return_pressed();
  676. return;
  677. }
  678. if (event.key() == KeyCode::Key_Return) {
  679. if (on_return_pressed)
  680. on_return_pressed();
  681. return;
  682. }
  683. if (event.key() == KeyCode::Key_Up) {
  684. if (on_up_pressed)
  685. on_up_pressed();
  686. return;
  687. }
  688. if (event.key() == KeyCode::Key_Down) {
  689. if (on_down_pressed)
  690. on_down_pressed();
  691. return;
  692. }
  693. if (event.key() == KeyCode::Key_PageUp) {
  694. if (on_pageup_pressed)
  695. on_pageup_pressed();
  696. return;
  697. }
  698. if (event.key() == KeyCode::Key_PageDown) {
  699. if (on_pagedown_pressed)
  700. on_pagedown_pressed();
  701. return;
  702. }
  703. } else if (!is_multi_line()) {
  704. VERIFY_NOT_REACHED();
  705. }
  706. ArmedScopeGuard update_autocomplete { [&] {
  707. try_update_autocomplete();
  708. } };
  709. if (is_multi_line() && !event.shift() && !event.alt() && event.ctrl() && event.key() == KeyCode::Key_Space) {
  710. if (m_autocomplete_provider) {
  711. try_show_autocomplete(UserRequestedAutocomplete::Yes);
  712. update_autocomplete.disarm();
  713. return;
  714. }
  715. }
  716. if (m_editing_engine->on_key(event))
  717. return;
  718. if (event.key() == KeyCode::Key_Escape) {
  719. if (on_escape_pressed)
  720. on_escape_pressed();
  721. return;
  722. }
  723. if (event.modifiers() == Mod_Shift && event.key() == KeyCode::Key_Delete) {
  724. if (m_autocomplete_box)
  725. hide_autocomplete();
  726. return;
  727. }
  728. if (event.key() == KeyCode::Key_Delete) {
  729. if (!is_editable())
  730. return;
  731. if (m_autocomplete_box)
  732. hide_autocomplete();
  733. if (has_selection()) {
  734. delete_selection();
  735. did_update_selection();
  736. return;
  737. }
  738. if (m_cursor.column() < current_line().length()) {
  739. // Delete within line
  740. int erase_count = 1;
  741. if (event.modifiers() == Mod_Ctrl) {
  742. auto word_break_pos = document().first_word_break_after(m_cursor);
  743. erase_count = word_break_pos.column() - m_cursor.column();
  744. }
  745. TextRange erased_range(m_cursor, { m_cursor.line(), m_cursor.column() + erase_count });
  746. execute<RemoveTextCommand>(document().text_in_range(erased_range), erased_range);
  747. return;
  748. }
  749. if (m_cursor.column() == current_line().length() && m_cursor.line() != line_count() - 1) {
  750. // Delete at end of line; merge with next line
  751. size_t erase_count = 0;
  752. if (event.modifiers() == Mod_Ctrl) {
  753. erase_count = document().first_word_break_after({ m_cursor.line() + 1, 0 }).column();
  754. }
  755. TextRange erased_range(m_cursor, { m_cursor.line() + 1, erase_count });
  756. execute<RemoveTextCommand>(document().text_in_range(erased_range), erased_range);
  757. return;
  758. }
  759. return;
  760. }
  761. if (event.key() == KeyCode::Key_Backspace) {
  762. if (!is_editable())
  763. return;
  764. if (m_autocomplete_box)
  765. hide_autocomplete();
  766. if (has_selection()) {
  767. delete_selection();
  768. did_update_selection();
  769. return;
  770. }
  771. if (m_cursor.column() > 0) {
  772. int erase_count = 1;
  773. if (event.modifiers() == Mod_Ctrl) {
  774. auto word_break_pos = document().first_word_break_before(m_cursor, true);
  775. erase_count = m_cursor.column() - word_break_pos.column();
  776. } else if (current_line().first_non_whitespace_column() >= m_cursor.column()) {
  777. int new_column;
  778. if (m_cursor.column() % m_soft_tab_width == 0)
  779. new_column = m_cursor.column() - m_soft_tab_width;
  780. else
  781. new_column = (m_cursor.column() / m_soft_tab_width) * m_soft_tab_width;
  782. erase_count = m_cursor.column() - new_column;
  783. }
  784. // Backspace within line
  785. TextRange erased_range({ m_cursor.line(), m_cursor.column() - erase_count }, m_cursor);
  786. auto erased_text = document().text_in_range(erased_range);
  787. execute<RemoveTextCommand>(erased_text, erased_range);
  788. return;
  789. }
  790. if (m_cursor.column() == 0 && m_cursor.line() != 0) {
  791. // Backspace at column 0; merge with previous line
  792. size_t previous_length = line(m_cursor.line() - 1).length();
  793. TextRange erased_range({ m_cursor.line() - 1, previous_length }, m_cursor);
  794. execute<RemoveTextCommand>("\n", erased_range);
  795. return;
  796. }
  797. return;
  798. }
  799. if (!event.ctrl() && !event.alt() && event.code_point() != 0) {
  800. TemporaryChange change { m_should_keep_autocomplete_box, true };
  801. add_code_point(event.code_point());
  802. return;
  803. }
  804. event.ignore();
  805. }
  806. void TextEditor::delete_previous_word()
  807. {
  808. TextRange to_erase(document().first_word_before(m_cursor, true), m_cursor);
  809. execute<RemoveTextCommand>(document().text_in_range(to_erase), to_erase);
  810. }
  811. void TextEditor::delete_current_line()
  812. {
  813. if (has_selection())
  814. return delete_selection();
  815. TextPosition start;
  816. TextPosition end;
  817. if (m_cursor.line() == 0 && line_count() == 1) {
  818. start = { 0, 0 };
  819. end = { 0, line(0).length() };
  820. } else if (m_cursor.line() == line_count() - 1) {
  821. start = { m_cursor.line() - 1, line(m_cursor.line() - 1).length() };
  822. end = { m_cursor.line(), line(m_cursor.line()).length() };
  823. } else {
  824. start = { m_cursor.line(), 0 };
  825. end = { m_cursor.line() + 1, 0 };
  826. }
  827. TextRange erased_range(start, end);
  828. execute<RemoveTextCommand>(document().text_in_range(erased_range), erased_range);
  829. }
  830. void TextEditor::delete_previous_char()
  831. {
  832. if (!is_editable())
  833. return;
  834. if (has_selection())
  835. return delete_selection();
  836. TextRange to_erase({ m_cursor.line(), m_cursor.column() - 1 }, m_cursor);
  837. if (m_cursor.column() == 0 && m_cursor.line() != 0) {
  838. size_t prev_line_len = line(m_cursor.line() - 1).length();
  839. to_erase.set_start({ m_cursor.line() - 1, prev_line_len });
  840. }
  841. execute<RemoveTextCommand>(document().text_in_range(to_erase), to_erase);
  842. }
  843. void TextEditor::delete_from_line_start_to_cursor()
  844. {
  845. TextPosition start(m_cursor.line(), current_line().first_non_whitespace_column());
  846. TextRange to_erase(start, m_cursor);
  847. execute<RemoveTextCommand>(document().text_in_range(to_erase), to_erase);
  848. }
  849. void TextEditor::do_delete()
  850. {
  851. if (!is_editable())
  852. return;
  853. if (has_selection())
  854. return delete_selection();
  855. if (m_cursor.column() < current_line().length()) {
  856. // Delete within line
  857. TextRange erased_range(m_cursor, { m_cursor.line(), m_cursor.column() + 1 });
  858. execute<RemoveTextCommand>(document().text_in_range(erased_range), erased_range);
  859. return;
  860. }
  861. if (m_cursor.column() == current_line().length() && m_cursor.line() != line_count() - 1) {
  862. // Delete at end of line; merge with next line
  863. TextRange erased_range(m_cursor, { m_cursor.line() + 1, 0 });
  864. execute<RemoveTextCommand>(document().text_in_range(erased_range), erased_range);
  865. return;
  866. }
  867. }
  868. void TextEditor::add_code_point(u32 code_point)
  869. {
  870. if (!is_editable())
  871. return;
  872. StringBuilder sb;
  873. sb.append_code_point(code_point);
  874. if (should_autocomplete_automatically()) {
  875. if (sb.string_view().is_whitespace())
  876. m_autocomplete_timer->stop();
  877. else
  878. m_autocomplete_timer->start();
  879. }
  880. insert_at_cursor_or_replace_selection(sb.to_string());
  881. };
  882. void TextEditor::reset_cursor_blink()
  883. {
  884. m_cursor_state = true;
  885. update_cursor();
  886. stop_timer();
  887. start_timer(500);
  888. }
  889. void TextEditor::update_selection(bool is_selecting)
  890. {
  891. if (is_selecting && !selection().is_valid()) {
  892. selection().set(cursor(), {});
  893. did_update_selection();
  894. update();
  895. return;
  896. }
  897. if (!is_selecting && selection().is_valid()) {
  898. selection().clear();
  899. did_update_selection();
  900. update();
  901. return;
  902. }
  903. if (is_selecting && selection().start().is_valid()) {
  904. selection().set_end(cursor());
  905. did_update_selection();
  906. update();
  907. return;
  908. }
  909. }
  910. int TextEditor::content_x_for_position(TextPosition const& position) const
  911. {
  912. auto& line = this->line(position.line());
  913. int x_offset = 0;
  914. switch (m_text_alignment) {
  915. case Gfx::TextAlignment::CenterLeft:
  916. for_each_visual_line(position.line(), [&](Gfx::IntRect const&, auto& visual_line_view, size_t start_of_visual_line, bool is_last_visual_line) {
  917. size_t offset_in_visual_line = position.column() - start_of_visual_line;
  918. auto before_line_end = is_last_visual_line ? (offset_in_visual_line <= visual_line_view.length()) : (offset_in_visual_line < visual_line_view.length());
  919. if (position.column() >= start_of_visual_line && before_line_end) {
  920. if (offset_in_visual_line == 0) {
  921. x_offset = 0;
  922. } else {
  923. x_offset = text_width_for_font(visual_line_view.substring_view(0, offset_in_visual_line), font());
  924. x_offset += font().glyph_spacing();
  925. }
  926. return IterationDecision::Break;
  927. }
  928. return IterationDecision::Continue;
  929. });
  930. return m_horizontal_content_padding + ((is_single_line() && icon()) ? (icon_size() + icon_padding()) : 0) + x_offset;
  931. case Gfx::TextAlignment::CenterRight:
  932. // FIXME
  933. VERIFY(!is_wrapping_enabled());
  934. return content_width() - m_horizontal_content_padding - (line.length() * fixed_glyph_width()) + (position.column() * fixed_glyph_width());
  935. default:
  936. VERIFY_NOT_REACHED();
  937. }
  938. }
  939. int TextEditor::text_width_for_font(auto const& text, Gfx::Font const& font) const
  940. {
  941. if (m_substitution_code_point)
  942. return font.width(substitution_code_point_view(text.length()));
  943. else
  944. return font.width(text);
  945. }
  946. Utf32View TextEditor::substitution_code_point_view(size_t length) const
  947. {
  948. VERIFY(m_substitution_code_point);
  949. if (!m_substitution_string_data)
  950. m_substitution_string_data = make<Vector<u32>>();
  951. if (!m_substitution_string_data->is_empty())
  952. VERIFY(m_substitution_string_data->first() == m_substitution_code_point);
  953. while (m_substitution_string_data->size() < length)
  954. m_substitution_string_data->append(m_substitution_code_point);
  955. return Utf32View { m_substitution_string_data->data(), length };
  956. }
  957. Gfx::IntRect TextEditor::content_rect_for_position(TextPosition const& position) const
  958. {
  959. if (!position.is_valid())
  960. return {};
  961. VERIFY(!lines().is_empty());
  962. VERIFY(position.column() <= (current_line().length() + 1));
  963. int x = content_x_for_position(position);
  964. if (is_single_line()) {
  965. Gfx::IntRect rect { x, 0, 1, line_height() };
  966. rect.center_vertically_within({ {}, frame_inner_rect().size() });
  967. return rect;
  968. }
  969. Gfx::IntRect rect;
  970. for_each_visual_line(position.line(), [&](Gfx::IntRect const& visual_line_rect, auto& view, size_t start_of_visual_line, bool is_last_visual_line) {
  971. auto before_line_end = is_last_visual_line ? ((position.column() - start_of_visual_line) <= view.length()) : ((position.column() - start_of_visual_line) < view.length());
  972. if (position.column() >= start_of_visual_line && before_line_end) {
  973. // NOTE: We have to subtract the horizontal padding here since it's part of the visual line rect
  974. // *and* included in what we get from content_x_for_position().
  975. rect = {
  976. visual_line_rect.x() + x - (m_horizontal_content_padding),
  977. visual_line_rect.y(),
  978. m_editing_engine->cursor_width() == CursorWidth::WIDE ? 7 : 1,
  979. line_height()
  980. };
  981. return IterationDecision::Break;
  982. }
  983. return IterationDecision::Continue;
  984. });
  985. return rect;
  986. }
  987. Gfx::IntRect TextEditor::cursor_content_rect() const
  988. {
  989. return content_rect_for_position(m_cursor);
  990. }
  991. Gfx::IntRect TextEditor::line_widget_rect(size_t line_index) const
  992. {
  993. auto rect = line_content_rect(line_index);
  994. rect.set_x(frame_thickness());
  995. rect.set_width(frame_inner_rect().width());
  996. rect.translate_by(0, -(vertical_scrollbar().value()));
  997. rect.translate_by(0, frame_thickness());
  998. rect.intersect(frame_inner_rect());
  999. return rect;
  1000. }
  1001. void TextEditor::scroll_position_into_view(TextPosition const& position)
  1002. {
  1003. auto rect = content_rect_for_position(position);
  1004. if (position.column() == 0)
  1005. rect.set_x(content_x_for_position({ position.line(), 0 }) - 2);
  1006. else if (position.column() == line(position.line()).length())
  1007. rect.set_x(content_x_for_position({ position.line(), line(position.line()).length() }) + 2);
  1008. scroll_into_view(rect, true, true);
  1009. }
  1010. void TextEditor::scroll_cursor_into_view()
  1011. {
  1012. if (!m_reflow_deferred)
  1013. scroll_position_into_view(m_cursor);
  1014. }
  1015. Gfx::IntRect TextEditor::line_content_rect(size_t line_index) const
  1016. {
  1017. auto& line = this->line(line_index);
  1018. if (is_single_line()) {
  1019. Gfx::IntRect line_rect = { content_x_for_position({ line_index, 0 }), 0, text_width_for_font(line.view(), font()), font().glyph_height() + 4 };
  1020. line_rect.center_vertically_within({ {}, frame_inner_rect().size() });
  1021. return line_rect;
  1022. }
  1023. if (is_wrapping_enabled())
  1024. return m_line_visual_data[line_index].visual_rect;
  1025. return {
  1026. content_x_for_position({ line_index, 0 }),
  1027. (int)line_index * line_height(),
  1028. text_width_for_font(line.view(), font()),
  1029. line_height()
  1030. };
  1031. }
  1032. void TextEditor::set_cursor_and_focus_line(size_t line, size_t column)
  1033. {
  1034. u_int index_max = line_count() - 1;
  1035. set_cursor(line, column);
  1036. if (line > 1 && line < index_max) {
  1037. int headroom = frame_inner_rect().height() / 3;
  1038. do {
  1039. auto line_data = m_line_visual_data[line];
  1040. headroom -= line_data.visual_rect.height();
  1041. line--;
  1042. } while (line > 0 && headroom > 0);
  1043. Gfx::IntRect rect = { 0, line_content_rect(line).y(),
  1044. 1, frame_inner_rect().height() };
  1045. scroll_into_view(rect, false, true);
  1046. }
  1047. }
  1048. void TextEditor::update_cursor()
  1049. {
  1050. update(line_widget_rect(m_cursor.line()));
  1051. }
  1052. void TextEditor::set_cursor(size_t line, size_t column)
  1053. {
  1054. set_cursor({ line, column });
  1055. }
  1056. void TextEditor::set_cursor(TextPosition const& a_position)
  1057. {
  1058. VERIFY(!lines().is_empty());
  1059. TextPosition position = a_position;
  1060. if (position.line() >= line_count())
  1061. position.set_line(line_count() - 1);
  1062. if (position.column() > lines()[position.line()].length())
  1063. position.set_column(lines()[position.line()].length());
  1064. if (m_cursor != position && is_visual_data_up_to_date()) {
  1065. // NOTE: If the old cursor is no longer valid, repaint everything just in case.
  1066. auto old_cursor_line_rect = m_cursor.line() < line_count()
  1067. ? line_widget_rect(m_cursor.line())
  1068. : rect();
  1069. m_cursor = position;
  1070. m_cursor_state = true;
  1071. scroll_cursor_into_view();
  1072. update(old_cursor_line_rect);
  1073. update_cursor();
  1074. } else if (m_cursor != position) {
  1075. m_cursor = position;
  1076. m_cursor_state = true;
  1077. }
  1078. cursor_did_change();
  1079. if (on_cursor_change)
  1080. on_cursor_change();
  1081. if (m_highlighter)
  1082. m_highlighter->cursor_did_change();
  1083. }
  1084. void TextEditor::focusin_event(FocusEvent& event)
  1085. {
  1086. if (event.source() == FocusSource::Keyboard)
  1087. select_all();
  1088. m_cursor_state = true;
  1089. update_cursor();
  1090. stop_timer();
  1091. start_timer(500);
  1092. if (on_focusin)
  1093. on_focusin();
  1094. }
  1095. void TextEditor::focusout_event(FocusEvent&)
  1096. {
  1097. if (is_displayonly() && has_selection())
  1098. m_selection.clear();
  1099. stop_timer();
  1100. if (on_focusout)
  1101. on_focusout();
  1102. }
  1103. void TextEditor::timer_event(Core::TimerEvent&)
  1104. {
  1105. m_cursor_state = !m_cursor_state;
  1106. if (is_focused())
  1107. update_cursor();
  1108. }
  1109. bool TextEditor::write_to_file(String const& path)
  1110. {
  1111. auto file = Core::File::construct(path);
  1112. if (!file->open(Core::OpenMode::WriteOnly | Core::OpenMode::Truncate)) {
  1113. warnln("Error opening {}: {}", path, strerror(file->error()));
  1114. return false;
  1115. }
  1116. return write_to_file(*file);
  1117. }
  1118. bool TextEditor::write_to_file(Core::File& file)
  1119. {
  1120. off_t file_size = 0;
  1121. if (line_count() == 1 && line(0).is_empty()) {
  1122. // Truncate to zero.
  1123. } else {
  1124. // Compute the final file size and ftruncate() to make writing fast.
  1125. // FIXME: Remove this once the kernel is smart enough to do this instead.
  1126. for (size_t i = 0; i < line_count(); ++i)
  1127. file_size += line(i).length();
  1128. file_size += line_count();
  1129. }
  1130. if (!file.truncate(file_size)) {
  1131. perror("ftruncate");
  1132. return false;
  1133. }
  1134. if (file_size == 0) {
  1135. // A size 0 file doesn't need a data copy.
  1136. } else {
  1137. for (size_t i = 0; i < line_count(); ++i) {
  1138. auto& line = this->line(i);
  1139. if (line.length()) {
  1140. auto line_as_utf8 = line.to_utf8();
  1141. ssize_t nwritten = file.write(line_as_utf8);
  1142. if (nwritten < 0) {
  1143. perror("write");
  1144. return false;
  1145. }
  1146. }
  1147. char ch = '\n';
  1148. ssize_t nwritten = file.write((u8*)&ch, 1);
  1149. if (nwritten != 1) {
  1150. perror("write");
  1151. return false;
  1152. }
  1153. }
  1154. }
  1155. document().set_unmodified();
  1156. return true;
  1157. }
  1158. String TextEditor::text() const
  1159. {
  1160. return document().text();
  1161. }
  1162. void TextEditor::clear()
  1163. {
  1164. document().remove_all_lines();
  1165. document().append_line(make<TextDocumentLine>(document()));
  1166. m_selection.clear();
  1167. did_update_selection();
  1168. set_cursor(0, 0);
  1169. update();
  1170. }
  1171. String TextEditor::selected_text() const
  1172. {
  1173. if (!has_selection())
  1174. return {};
  1175. return document().text_in_range(m_selection);
  1176. }
  1177. size_t TextEditor::number_of_selected_words() const
  1178. {
  1179. if (!has_selection())
  1180. return 0;
  1181. size_t word_count = 0;
  1182. bool in_word = false;
  1183. auto selected_text = this->selected_text();
  1184. for (char c : selected_text) {
  1185. if (in_word && is_ascii_space(c)) {
  1186. in_word = false;
  1187. word_count++;
  1188. continue;
  1189. }
  1190. if (!in_word && !is_ascii_space(c))
  1191. in_word = true;
  1192. }
  1193. if (in_word)
  1194. word_count++;
  1195. return word_count;
  1196. }
  1197. size_t TextEditor::number_of_words() const
  1198. {
  1199. if (document().is_empty())
  1200. return 0;
  1201. size_t word_count = 0;
  1202. bool in_word = false;
  1203. auto text = this->text();
  1204. for (char c : text) {
  1205. if (in_word && is_ascii_space(c)) {
  1206. in_word = false;
  1207. word_count++;
  1208. continue;
  1209. }
  1210. if (!in_word && !is_ascii_space(c))
  1211. in_word = true;
  1212. }
  1213. if (in_word)
  1214. word_count++;
  1215. return word_count;
  1216. }
  1217. void TextEditor::delete_selection()
  1218. {
  1219. auto selection = normalized_selection();
  1220. auto selected = selected_text();
  1221. m_selection.clear();
  1222. execute<RemoveTextCommand>(selected, selection);
  1223. did_update_selection();
  1224. did_change();
  1225. set_cursor(selection.start());
  1226. update();
  1227. }
  1228. void TextEditor::delete_text_range(TextRange range)
  1229. {
  1230. auto normalized_range = range.normalized();
  1231. execute<RemoveTextCommand>(document().text_in_range(normalized_range), normalized_range);
  1232. did_change();
  1233. set_cursor(normalized_range.start());
  1234. update();
  1235. }
  1236. void TextEditor::insert_at_cursor_or_replace_selection(StringView text)
  1237. {
  1238. ReflowDeferrer defer(*this);
  1239. VERIFY(is_editable());
  1240. if (has_selection())
  1241. delete_selection();
  1242. // Check if adding a newline leaves the previous line as just whitespace.
  1243. auto const clear_length = m_cursor.column();
  1244. auto const should_clear_last_line = text == "\n"
  1245. && clear_length > 0
  1246. && current_line().leading_spaces() == clear_length;
  1247. execute<InsertTextCommand>(text, m_cursor);
  1248. if (should_clear_last_line) { // If it does leave just whitespace, clear it.
  1249. auto const original_cursor_position = cursor();
  1250. TextPosition start(original_cursor_position.line() - 1, 0);
  1251. TextPosition end(original_cursor_position.line() - 1, clear_length);
  1252. TextRange erased_range(start, end);
  1253. execute<RemoveTextCommand>(document().text_in_range(erased_range), erased_range);
  1254. set_cursor(original_cursor_position);
  1255. }
  1256. }
  1257. void TextEditor::cut()
  1258. {
  1259. if (!is_editable())
  1260. return;
  1261. auto selected_text = this->selected_text();
  1262. dbgln_if(TEXTEDITOR_DEBUG, "Cut: \"{}\"", selected_text);
  1263. Clipboard::the().set_plain_text(selected_text);
  1264. delete_selection();
  1265. }
  1266. void TextEditor::copy()
  1267. {
  1268. auto selected_text = this->selected_text();
  1269. dbgln_if(TEXTEDITOR_DEBUG, "Copy: \"{}\"\n", selected_text);
  1270. Clipboard::the().set_plain_text(selected_text);
  1271. }
  1272. void TextEditor::paste()
  1273. {
  1274. if (!is_editable())
  1275. return;
  1276. auto [data, mime_type, _] = GUI::Clipboard::the().fetch_data_and_type();
  1277. if (!mime_type.starts_with("text/"))
  1278. return;
  1279. if (data.is_empty())
  1280. return;
  1281. dbgln_if(TEXTEDITOR_DEBUG, "Paste: \"{}\"", String::copy(data));
  1282. TemporaryChange change(m_automatic_indentation_enabled, false);
  1283. insert_at_cursor_or_replace_selection(data);
  1284. }
  1285. void TextEditor::defer_reflow()
  1286. {
  1287. ++m_reflow_deferred;
  1288. }
  1289. void TextEditor::undefer_reflow()
  1290. {
  1291. VERIFY(m_reflow_deferred);
  1292. if (!--m_reflow_deferred) {
  1293. if (m_reflow_requested) {
  1294. recompute_all_visual_lines();
  1295. scroll_cursor_into_view();
  1296. }
  1297. }
  1298. }
  1299. void TextEditor::try_show_autocomplete(UserRequestedAutocomplete user_requested_autocomplete)
  1300. {
  1301. force_update_autocomplete([&, user_requested_autocomplete = move(user_requested_autocomplete)] {
  1302. if (user_requested_autocomplete == Yes || m_autocomplete_box->has_suggestions()) {
  1303. auto position = content_rect_for_position(cursor()).translated(0, -visible_content_rect().y()).bottom_right().translated(screen_relative_rect().top_left().translated(ruler_width(), 0).translated(10, 5));
  1304. m_autocomplete_box->show(position);
  1305. }
  1306. });
  1307. }
  1308. void TextEditor::try_update_autocomplete(Function<void()> callback)
  1309. {
  1310. if (m_autocomplete_box && m_autocomplete_box->is_visible())
  1311. force_update_autocomplete(move(callback));
  1312. }
  1313. void TextEditor::force_update_autocomplete(Function<void()> callback)
  1314. {
  1315. if (m_autocomplete_provider) {
  1316. m_autocomplete_provider->provide_completions([&, callback = move(callback)](auto completions) {
  1317. m_autocomplete_box->update_suggestions(move(completions));
  1318. if (callback)
  1319. callback();
  1320. });
  1321. }
  1322. }
  1323. void TextEditor::hide_autocomplete_if_needed()
  1324. {
  1325. if (!m_should_keep_autocomplete_box)
  1326. hide_autocomplete();
  1327. }
  1328. void TextEditor::hide_autocomplete()
  1329. {
  1330. if (m_autocomplete_box) {
  1331. m_autocomplete_box->close();
  1332. if (m_autocomplete_timer)
  1333. m_autocomplete_timer->stop();
  1334. }
  1335. }
  1336. void TextEditor::enter_event(Core::Event&)
  1337. {
  1338. m_automatic_selection_scroll_timer->stop();
  1339. }
  1340. void TextEditor::leave_event(Core::Event&)
  1341. {
  1342. if (m_in_drag_select)
  1343. m_automatic_selection_scroll_timer->start();
  1344. }
  1345. void TextEditor::did_change(AllowCallback allow_callback)
  1346. {
  1347. update_content_size();
  1348. recompute_all_visual_lines();
  1349. hide_autocomplete_if_needed();
  1350. m_needs_rehighlight = true;
  1351. if (!m_has_pending_change_notification) {
  1352. m_has_pending_change_notification = true;
  1353. deferred_invoke([this, allow_callback] {
  1354. m_has_pending_change_notification = false;
  1355. if (on_change && allow_callback == AllowCallback::Yes)
  1356. on_change();
  1357. });
  1358. }
  1359. }
  1360. void TextEditor::set_mode(const Mode mode)
  1361. {
  1362. if (m_mode == mode)
  1363. return;
  1364. m_mode = mode;
  1365. switch (mode) {
  1366. case Editable:
  1367. m_cut_action->set_enabled(has_selection() && !text_is_secret());
  1368. m_paste_action->set_enabled(true);
  1369. set_accepts_emoji_input(true);
  1370. break;
  1371. case DisplayOnly:
  1372. case ReadOnly:
  1373. m_cut_action->set_enabled(false);
  1374. m_paste_action->set_enabled(false);
  1375. set_accepts_emoji_input(false);
  1376. break;
  1377. default:
  1378. VERIFY_NOT_REACHED();
  1379. }
  1380. if (!is_displayonly())
  1381. set_override_cursor(Gfx::StandardCursor::IBeam);
  1382. else
  1383. set_override_cursor(Gfx::StandardCursor::None);
  1384. }
  1385. void TextEditor::did_update_selection()
  1386. {
  1387. m_cut_action->set_enabled(is_editable() && has_selection() && !text_is_secret());
  1388. m_copy_action->set_enabled(has_selection() && !text_is_secret());
  1389. if (on_selection_change)
  1390. on_selection_change();
  1391. if (is_wrapping_enabled()) {
  1392. // FIXME: Try to repaint less.
  1393. update();
  1394. }
  1395. }
  1396. void TextEditor::context_menu_event(ContextMenuEvent& event)
  1397. {
  1398. if (is_displayonly())
  1399. return;
  1400. if (!m_context_menu) {
  1401. m_context_menu = Menu::construct();
  1402. m_context_menu->add_action(undo_action());
  1403. m_context_menu->add_action(redo_action());
  1404. m_context_menu->add_separator();
  1405. m_context_menu->add_action(cut_action());
  1406. m_context_menu->add_action(copy_action());
  1407. m_context_menu->add_action(paste_action());
  1408. m_context_menu->add_separator();
  1409. m_context_menu->add_action(select_all_action());
  1410. if (is_multi_line()) {
  1411. m_context_menu->add_separator();
  1412. m_context_menu->add_action(go_to_line_action());
  1413. }
  1414. if (!m_custom_context_menu_actions.is_empty()) {
  1415. m_context_menu->add_separator();
  1416. for (auto& action : m_custom_context_menu_actions) {
  1417. m_context_menu->add_action(action);
  1418. }
  1419. }
  1420. }
  1421. m_context_menu->popup(event.screen_position());
  1422. }
  1423. void TextEditor::set_text_alignment(Gfx::TextAlignment alignment)
  1424. {
  1425. if (m_text_alignment == alignment)
  1426. return;
  1427. m_text_alignment = alignment;
  1428. update();
  1429. }
  1430. void TextEditor::resize_event(ResizeEvent& event)
  1431. {
  1432. AbstractScrollableWidget::resize_event(event);
  1433. update_content_size();
  1434. recompute_all_visual_lines();
  1435. }
  1436. void TextEditor::theme_change_event(ThemeChangeEvent& event)
  1437. {
  1438. AbstractScrollableWidget::theme_change_event(event);
  1439. m_needs_rehighlight = true;
  1440. }
  1441. void TextEditor::set_selection(TextRange const& selection)
  1442. {
  1443. if (m_selection == selection)
  1444. return;
  1445. m_selection = selection;
  1446. set_cursor(m_selection.end());
  1447. scroll_position_into_view(normalized_selection().start());
  1448. update();
  1449. }
  1450. void TextEditor::clear_selection()
  1451. {
  1452. if (!has_selection())
  1453. return;
  1454. m_selection.clear();
  1455. update();
  1456. }
  1457. void TextEditor::recompute_all_visual_lines()
  1458. {
  1459. if (m_reflow_deferred) {
  1460. m_reflow_requested = true;
  1461. return;
  1462. }
  1463. m_reflow_requested = false;
  1464. int y_offset = 0;
  1465. for (size_t line_index = 0; line_index < line_count(); ++line_index) {
  1466. recompute_visual_lines(line_index);
  1467. m_line_visual_data[line_index].visual_rect.set_y(y_offset);
  1468. y_offset += m_line_visual_data[line_index].visual_rect.height();
  1469. }
  1470. update_content_size();
  1471. }
  1472. void TextEditor::ensure_cursor_is_valid()
  1473. {
  1474. auto new_cursor = m_cursor;
  1475. if (new_cursor.line() >= line_count())
  1476. new_cursor.set_line(line_count() - 1);
  1477. if (new_cursor.column() > line(new_cursor.line()).length())
  1478. new_cursor.set_column(line(new_cursor.line()).length());
  1479. if (m_cursor != new_cursor)
  1480. set_cursor(new_cursor);
  1481. }
  1482. size_t TextEditor::visual_line_containing(size_t line_index, size_t column) const
  1483. {
  1484. size_t visual_line_index = 0;
  1485. for_each_visual_line(line_index, [&](Gfx::IntRect const&, auto& view, size_t start_of_visual_line, [[maybe_unused]] bool is_last_visual_line) {
  1486. if (column >= start_of_visual_line && ((column - start_of_visual_line) < view.length()))
  1487. return IterationDecision::Break;
  1488. ++visual_line_index;
  1489. return IterationDecision::Continue;
  1490. });
  1491. return visual_line_index;
  1492. }
  1493. void TextEditor::recompute_visual_lines(size_t line_index)
  1494. {
  1495. auto& line = document().line(line_index);
  1496. auto& visual_data = m_line_visual_data[line_index];
  1497. visual_data.visual_line_breaks.clear_with_capacity();
  1498. int available_width = visible_text_rect_in_inner_coordinates().width();
  1499. if (is_wrapping_enabled()) {
  1500. int line_width_so_far = 0;
  1501. size_t last_whitespace_index = 0;
  1502. size_t line_width_since_last_whitespace = 0;
  1503. auto glyph_spacing = font().glyph_spacing();
  1504. for (size_t i = 0; i < line.length(); ++i) {
  1505. auto code_point = line.code_points()[i];
  1506. if (is_ascii_space(code_point)) {
  1507. last_whitespace_index = i;
  1508. line_width_since_last_whitespace = 0;
  1509. }
  1510. auto glyph_width = font().glyph_or_emoji_width(code_point);
  1511. line_width_since_last_whitespace += glyph_width + glyph_spacing;
  1512. if ((line_width_so_far + glyph_width + glyph_spacing) > available_width) {
  1513. if (m_wrapping_mode == WrappingMode::WrapAtWords && last_whitespace_index != 0) {
  1514. // Plus 1 to get the first letter of the word.
  1515. visual_data.visual_line_breaks.append(last_whitespace_index + 1);
  1516. line_width_so_far = line_width_since_last_whitespace;
  1517. last_whitespace_index = 0;
  1518. line_width_since_last_whitespace = 0;
  1519. } else {
  1520. visual_data.visual_line_breaks.append(i);
  1521. line_width_so_far = glyph_width + glyph_spacing;
  1522. }
  1523. continue;
  1524. }
  1525. line_width_so_far += glyph_width + glyph_spacing;
  1526. }
  1527. }
  1528. visual_data.visual_line_breaks.append(line.length());
  1529. if (is_wrapping_enabled())
  1530. visual_data.visual_rect = { m_horizontal_content_padding, 0, available_width, static_cast<int>(visual_data.visual_line_breaks.size()) * line_height() };
  1531. else
  1532. visual_data.visual_rect = { m_horizontal_content_padding, 0, text_width_for_font(line.view(), font()), line_height() };
  1533. }
  1534. template<typename Callback>
  1535. void TextEditor::for_each_visual_line(size_t line_index, Callback callback) const
  1536. {
  1537. auto editor_visible_text_rect = visible_text_rect_in_inner_coordinates();
  1538. size_t start_of_line = 0;
  1539. size_t visual_line_index = 0;
  1540. auto& line = document().line(line_index);
  1541. auto& visual_data = m_line_visual_data[line_index];
  1542. for (auto visual_line_break : visual_data.visual_line_breaks) {
  1543. auto visual_line_view = Utf32View(line.code_points() + start_of_line, visual_line_break - start_of_line);
  1544. Gfx::IntRect visual_line_rect {
  1545. visual_data.visual_rect.x(),
  1546. visual_data.visual_rect.y() + ((int)visual_line_index * line_height()),
  1547. text_width_for_font(visual_line_view, font()) + font().glyph_spacing(),
  1548. line_height()
  1549. };
  1550. if (is_right_text_alignment(text_alignment()))
  1551. visual_line_rect.set_right_without_resize(editor_visible_text_rect.right());
  1552. if (is_single_line()) {
  1553. visual_line_rect.center_vertically_within(editor_visible_text_rect);
  1554. if (m_icon)
  1555. visual_line_rect.translate_by(icon_size() + icon_padding(), 0);
  1556. }
  1557. if (callback(visual_line_rect, visual_line_view, start_of_line, visual_line_index == visual_data.visual_line_breaks.size() - 1) == IterationDecision::Break)
  1558. break;
  1559. start_of_line = visual_line_break;
  1560. ++visual_line_index;
  1561. }
  1562. }
  1563. void TextEditor::set_wrapping_mode(WrappingMode mode)
  1564. {
  1565. if (m_wrapping_mode == mode)
  1566. return;
  1567. m_wrapping_mode = mode;
  1568. horizontal_scrollbar().set_visible(m_wrapping_mode == WrappingMode::NoWrap);
  1569. update_content_size();
  1570. recompute_all_visual_lines();
  1571. update();
  1572. }
  1573. void TextEditor::add_custom_context_menu_action(Action& action)
  1574. {
  1575. m_custom_context_menu_actions.append(action);
  1576. }
  1577. void TextEditor::did_change_font()
  1578. {
  1579. vertical_scrollbar().set_step(line_height());
  1580. recompute_all_visual_lines();
  1581. update();
  1582. AbstractScrollableWidget::did_change_font();
  1583. }
  1584. void TextEditor::document_did_append_line()
  1585. {
  1586. m_line_visual_data.append(make<LineVisualData>());
  1587. recompute_all_visual_lines();
  1588. update();
  1589. }
  1590. void TextEditor::document_did_remove_line(size_t line_index)
  1591. {
  1592. m_line_visual_data.remove(line_index);
  1593. recompute_all_visual_lines();
  1594. update();
  1595. }
  1596. void TextEditor::document_did_remove_all_lines()
  1597. {
  1598. m_line_visual_data.clear();
  1599. recompute_all_visual_lines();
  1600. update();
  1601. }
  1602. void TextEditor::document_did_insert_line(size_t line_index)
  1603. {
  1604. m_line_visual_data.insert(line_index, make<LineVisualData>());
  1605. recompute_all_visual_lines();
  1606. update();
  1607. }
  1608. void TextEditor::document_did_change(AllowCallback allow_callback)
  1609. {
  1610. did_change(allow_callback);
  1611. update();
  1612. }
  1613. void TextEditor::document_did_update_undo_stack()
  1614. {
  1615. auto make_action_text = [](auto prefix, auto suffix) {
  1616. StringBuilder builder;
  1617. builder.append(prefix);
  1618. if (suffix.has_value()) {
  1619. builder.append(' ');
  1620. builder.append(suffix.value());
  1621. }
  1622. return builder.to_string();
  1623. };
  1624. m_undo_action->set_enabled(can_undo() && !text_is_secret());
  1625. m_redo_action->set_enabled(can_redo() && !text_is_secret());
  1626. m_undo_action->set_text(make_action_text("&Undo", document().undo_stack().undo_action_text()));
  1627. m_redo_action->set_text(make_action_text("&Redo", document().undo_stack().redo_action_text()));
  1628. // FIXME: This is currently firing more often than it should.
  1629. // Ideally we'd only send this out when the undo stack modified state actually changes.
  1630. if (on_modified_change)
  1631. on_modified_change(document().is_modified());
  1632. }
  1633. void TextEditor::document_did_set_text(AllowCallback allow_callback)
  1634. {
  1635. m_line_visual_data.clear();
  1636. for (size_t i = 0; i < m_document->line_count(); ++i)
  1637. m_line_visual_data.append(make<LineVisualData>());
  1638. document_did_change(allow_callback);
  1639. }
  1640. void TextEditor::document_did_set_cursor(TextPosition const& position)
  1641. {
  1642. set_cursor(position);
  1643. }
  1644. void TextEditor::cursor_did_change()
  1645. {
  1646. hide_autocomplete_if_needed();
  1647. }
  1648. void TextEditor::clipboard_content_did_change(String const& mime_type)
  1649. {
  1650. m_paste_action->set_enabled(is_editable() && mime_type.starts_with("text/"));
  1651. }
  1652. void TextEditor::set_document(TextDocument& document)
  1653. {
  1654. if (m_document.ptr() == &document)
  1655. return;
  1656. if (m_document)
  1657. m_document->unregister_client(*this);
  1658. m_document = document;
  1659. m_line_visual_data.clear();
  1660. for (size_t i = 0; i < m_document->line_count(); ++i) {
  1661. m_line_visual_data.append(make<LineVisualData>());
  1662. }
  1663. set_cursor(0, 0);
  1664. if (has_selection())
  1665. m_selection.clear();
  1666. recompute_all_visual_lines();
  1667. update();
  1668. m_document->register_client(*this);
  1669. }
  1670. void TextEditor::rehighlight_if_needed()
  1671. {
  1672. if (!m_needs_rehighlight)
  1673. return;
  1674. force_rehighlight();
  1675. }
  1676. void TextEditor::force_rehighlight()
  1677. {
  1678. if (m_highlighter)
  1679. m_highlighter->rehighlight(palette());
  1680. m_needs_rehighlight = false;
  1681. }
  1682. Syntax::Highlighter const* TextEditor::syntax_highlighter() const
  1683. {
  1684. return m_highlighter.ptr();
  1685. }
  1686. Syntax::Highlighter* TextEditor::syntax_highlighter()
  1687. {
  1688. return m_highlighter.ptr();
  1689. }
  1690. void TextEditor::set_syntax_highlighter(OwnPtr<Syntax::Highlighter> highlighter)
  1691. {
  1692. if (m_highlighter)
  1693. m_highlighter->detach();
  1694. m_highlighter = move(highlighter);
  1695. if (m_highlighter) {
  1696. m_highlighter->attach(*this);
  1697. m_needs_rehighlight = true;
  1698. } else
  1699. document().set_spans({});
  1700. }
  1701. AutocompleteProvider const* TextEditor::autocomplete_provider() const
  1702. {
  1703. return m_autocomplete_provider.ptr();
  1704. }
  1705. void TextEditor::set_autocomplete_provider(OwnPtr<AutocompleteProvider>&& provider)
  1706. {
  1707. if (m_autocomplete_provider)
  1708. m_autocomplete_provider->detach();
  1709. m_autocomplete_provider = move(provider);
  1710. if (m_autocomplete_provider) {
  1711. m_autocomplete_provider->attach(*this);
  1712. if (!m_autocomplete_box)
  1713. m_autocomplete_box = make<AutocompleteBox>(*this);
  1714. }
  1715. if (m_autocomplete_box)
  1716. hide_autocomplete();
  1717. }
  1718. EditingEngine const* TextEditor::editing_engine() const
  1719. {
  1720. return m_editing_engine.ptr();
  1721. }
  1722. void TextEditor::set_editing_engine(OwnPtr<EditingEngine> editing_engine)
  1723. {
  1724. if (m_editing_engine)
  1725. m_editing_engine->detach();
  1726. m_editing_engine = move(editing_engine);
  1727. VERIFY(m_editing_engine);
  1728. m_editing_engine->attach(*this);
  1729. m_cursor_state = true;
  1730. update_cursor();
  1731. stop_timer();
  1732. start_timer(500);
  1733. }
  1734. int TextEditor::line_height() const
  1735. {
  1736. return font().glyph_height() + m_line_spacing;
  1737. }
  1738. int TextEditor::fixed_glyph_width() const
  1739. {
  1740. VERIFY(font().is_fixed_width());
  1741. return font().glyph_width(' ');
  1742. }
  1743. void TextEditor::set_icon(Gfx::Bitmap const* icon)
  1744. {
  1745. if (m_icon == icon)
  1746. return;
  1747. m_icon = icon;
  1748. update();
  1749. }
  1750. void TextEditor::set_visualize_trailing_whitespace(bool enabled)
  1751. {
  1752. if (m_visualize_trailing_whitespace == enabled)
  1753. return;
  1754. m_visualize_trailing_whitespace = enabled;
  1755. update();
  1756. }
  1757. void TextEditor::set_visualize_leading_whitespace(bool enabled)
  1758. {
  1759. if (m_visualize_leading_whitespace == enabled)
  1760. return;
  1761. m_visualize_leading_whitespace = enabled;
  1762. update();
  1763. }
  1764. void TextEditor::set_should_autocomplete_automatically(bool value)
  1765. {
  1766. if (value == should_autocomplete_automatically())
  1767. return;
  1768. if (value) {
  1769. VERIFY(m_autocomplete_provider);
  1770. m_autocomplete_timer = Core::Timer::create_single_shot(m_automatic_autocomplete_delay_ms, [this] {
  1771. if (m_autocomplete_box && !m_autocomplete_box->is_visible())
  1772. try_show_autocomplete(UserRequestedAutocomplete::No);
  1773. });
  1774. return;
  1775. }
  1776. remove_child(*m_autocomplete_timer);
  1777. m_autocomplete_timer = nullptr;
  1778. }
  1779. void TextEditor::set_substitution_code_point(u32 code_point)
  1780. {
  1781. VERIFY(is_unicode(code_point));
  1782. m_substitution_string_data.clear();
  1783. m_substitution_code_point = code_point;
  1784. }
  1785. int TextEditor::number_of_visible_lines() const
  1786. {
  1787. return visible_content_rect().height() / line_height();
  1788. }
  1789. void TextEditor::set_ruler_visible(bool visible)
  1790. {
  1791. if (m_ruler_visible == visible)
  1792. return;
  1793. m_ruler_visible = visible;
  1794. recompute_all_visual_lines();
  1795. update();
  1796. }
  1797. void TextEditor::set_gutter_visible(bool visible)
  1798. {
  1799. if (m_gutter_visible == visible)
  1800. return;
  1801. m_gutter_visible = visible;
  1802. recompute_all_visual_lines();
  1803. update();
  1804. }
  1805. void TextEditor::set_cursor_line_highlighting(bool highlighted)
  1806. {
  1807. if (m_cursor_line_highlighting == highlighted)
  1808. return;
  1809. m_cursor_line_highlighting = highlighted;
  1810. update();
  1811. }
  1812. void TextEditor::undo()
  1813. {
  1814. clear_selection();
  1815. document().undo();
  1816. }
  1817. void TextEditor::redo()
  1818. {
  1819. clear_selection();
  1820. document().redo();
  1821. }
  1822. void TextEditor::set_text_is_secret(bool text_is_secret)
  1823. {
  1824. m_text_is_secret = text_is_secret;
  1825. document_did_update_undo_stack();
  1826. did_update_selection();
  1827. }
  1828. }