TextEditor.cpp 50 KB

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