TextEditor.cpp 71 KB

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