TextEditor.cpp 57 KB

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