TextEditor.cpp 81 KB

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