TextEditor.cpp 77 KB

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