TextEditor.cpp 84 KB

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