TextEditor.cpp 94 KB

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