TextEditor.cpp 52 KB

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