TextEditor.cpp 72 KB

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