TextEditor.cpp 71 KB

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