TextEditor.cpp 83 KB

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