TextEditor.cpp 81 KB

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