TextEditor.cpp 67 KB

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