TextEditor.cpp 62 KB

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