TextEditor.cpp 53 KB

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