TextEditor.cpp 87 KB

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