TextEditor.cpp 93 KB

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