TextEditor.cpp 69 KB

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