TextEditor.cpp 79 KB

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