TextEditor.cpp 57 KB

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