TextEditor.cpp 71 KB

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