TextEditor.cpp 52 KB

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