TextEditor.cpp 75 KB

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