TextEditor.cpp 72 KB

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