TextEditor.cpp 80 KB

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