TextEditor.cpp 88 KB

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