TextEditor.cpp 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512
  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(GFontDatabase::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. painter.draw_text(visual_line_rect, visual_line_text, m_text_alignment, palette().color(foreground_role()));
  362. } else {
  363. int advance = font().glyph_width(' ') + font().glyph_spacing();
  364. Gfx::Rect character_rect = { visual_line_rect.location(), { font().glyph_width(' '), line_height() } };
  365. for (size_t i = 0; i < visual_line_text.length(); ++i) {
  366. const Gfx::Font* font = &this->font();
  367. Color color;
  368. Optional<Color> background_color;
  369. TextPosition physical_position(line_index, start_of_visual_line + i);
  370. // FIXME: This is *horribly* inefficient.
  371. for (auto& span : document().spans()) {
  372. if (!span.range.contains(physical_position))
  373. continue;
  374. color = span.color;
  375. if (span.font)
  376. font = span.font;
  377. background_color = span.background_color;
  378. break;
  379. }
  380. if (background_color.has_value())
  381. painter.fill_rect(character_rect, background_color.value());
  382. painter.draw_text(character_rect, visual_line_text.substring_view(i, 1), *font, m_text_alignment, color);
  383. character_rect.move_by(advance, 0);
  384. }
  385. }
  386. bool physical_line_has_selection = has_selection && line_index >= selection.start().line() && line_index <= selection.end().line();
  387. if (physical_line_has_selection) {
  388. bool current_visual_line_has_selection = (line_index != selection.start().line() && line_index != selection.end().line())
  389. || (visual_line_index >= first_visual_line_with_selection && visual_line_index <= last_visual_line_with_selection);
  390. if (current_visual_line_has_selection) {
  391. bool selection_begins_on_current_visual_line = visual_line_index == first_visual_line_with_selection;
  392. bool selection_ends_on_current_visual_line = visual_line_index == last_visual_line_with_selection;
  393. int selection_left = selection_begins_on_current_visual_line
  394. ? content_x_for_position({ line_index, (size_t)selection_start_column_within_line })
  395. : m_horizontal_content_padding;
  396. int selection_right = selection_ends_on_current_visual_line
  397. ? content_x_for_position({ line_index, (size_t)selection_end_column_within_line })
  398. : visual_line_rect.right() + 1;
  399. Gfx::Rect selection_rect {
  400. selection_left,
  401. visual_line_rect.y(),
  402. selection_right - selection_left,
  403. visual_line_rect.height()
  404. };
  405. Color background_color = is_focused() ? palette().selection() : palette().inactive_selection();
  406. Color text_color = is_focused() ? palette().selection_text() : palette().inactive_selection_text();
  407. painter.fill_rect(selection_rect, background_color);
  408. size_t start_of_selection_within_visual_line = (size_t)max(0, (int)selection_start_column_within_line - (int)start_of_visual_line);
  409. size_t end_of_selection_within_visual_line = selection_end_column_within_line - start_of_visual_line;
  410. StringView visual_selected_text {
  411. visual_line_text.characters_without_null_termination() + start_of_selection_within_visual_line,
  412. end_of_selection_within_visual_line - start_of_selection_within_visual_line
  413. };
  414. painter.draw_text(selection_rect, visual_selected_text, Gfx::TextAlignment::CenterLeft, text_color);
  415. }
  416. }
  417. ++visual_line_index;
  418. return IterationDecision::Continue;
  419. });
  420. }
  421. if (is_focused() && m_cursor_state)
  422. painter.fill_rect(cursor_content_rect(), palette().text_cursor());
  423. }
  424. void TextEditor::toggle_selection_if_needed_for_event(const KeyEvent& event)
  425. {
  426. if (event.shift() && !m_selection.is_valid()) {
  427. m_selection.set(m_cursor, {});
  428. did_update_selection();
  429. update();
  430. return;
  431. }
  432. if (!event.shift() && m_selection.is_valid()) {
  433. m_selection.clear();
  434. did_update_selection();
  435. update();
  436. return;
  437. }
  438. }
  439. void TextEditor::select_all()
  440. {
  441. TextPosition start_of_document { 0, 0 };
  442. TextPosition end_of_document { line_count() - 1, line(line_count() - 1).length() };
  443. m_selection.set(start_of_document, end_of_document);
  444. did_update_selection();
  445. set_cursor(end_of_document);
  446. update();
  447. }
  448. void TextEditor::get_selection_line_boundaries(size_t& first_line, size_t& last_line)
  449. {
  450. auto selection = normalized_selection();
  451. if (!selection.is_valid()) {
  452. first_line = m_cursor.line();
  453. last_line = m_cursor.line();
  454. return;
  455. }
  456. first_line = selection.start().line();
  457. last_line = selection.end().line();
  458. if (first_line != last_line && selection.end().column() == 0)
  459. last_line -= 1;
  460. }
  461. void TextEditor::move_selected_lines_up()
  462. {
  463. size_t first_line;
  464. size_t last_line;
  465. get_selection_line_boundaries(first_line, last_line);
  466. if (first_line == 0)
  467. return;
  468. auto& lines = document().lines();
  469. lines.insert((int)last_line, lines.take((int)first_line - 1));
  470. m_cursor = { first_line - 1, 0 };
  471. if (has_selection()) {
  472. m_selection.set_start({ first_line - 1, 0 });
  473. m_selection.set_end({ last_line - 1, line(last_line - 1).length() });
  474. }
  475. did_change();
  476. update();
  477. }
  478. void TextEditor::move_selected_lines_down()
  479. {
  480. size_t first_line;
  481. size_t last_line;
  482. get_selection_line_boundaries(first_line, last_line);
  483. auto& lines = document().lines();
  484. if (last_line >= (size_t)(lines.size() - 1))
  485. return;
  486. lines.insert((int)first_line, lines.take((int)last_line + 1));
  487. m_cursor = { first_line + 1, 0 };
  488. if (has_selection()) {
  489. m_selection.set_start({ first_line + 1, 0 });
  490. m_selection.set_end({ last_line + 1, line(last_line + 1).length() });
  491. }
  492. did_change();
  493. update();
  494. }
  495. void TextEditor::sort_selected_lines()
  496. {
  497. if (is_readonly())
  498. return;
  499. if (!has_selection())
  500. return;
  501. size_t first_line;
  502. size_t last_line;
  503. get_selection_line_boundaries(first_line, last_line);
  504. auto& lines = document().lines();
  505. auto start = lines.begin() + (int)first_line;
  506. auto end = lines.begin() + (int)last_line + 1;
  507. quick_sort(start, end, [](auto& a, auto& b) {
  508. return strcmp(a.characters(), b.characters()) < 0;
  509. });
  510. did_change();
  511. update();
  512. }
  513. void TextEditor::keydown_event(KeyEvent& event)
  514. {
  515. if (is_single_line() && event.key() == KeyCode::Key_Tab)
  516. return Widget::keydown_event(event);
  517. if (is_single_line() && event.key() == KeyCode::Key_Return) {
  518. if (on_return_pressed)
  519. on_return_pressed();
  520. return;
  521. }
  522. if (event.key() == KeyCode::Key_Escape) {
  523. if (on_escape_pressed)
  524. on_escape_pressed();
  525. return;
  526. }
  527. if (is_multi_line() && event.key() == KeyCode::Key_Up) {
  528. if (m_cursor.line() > 0) {
  529. if (event.ctrl() && event.shift()) {
  530. move_selected_lines_up();
  531. return;
  532. }
  533. size_t new_line = m_cursor.line() - 1;
  534. size_t new_column = min(m_cursor.column(), line(new_line).length());
  535. toggle_selection_if_needed_for_event(event);
  536. set_cursor(new_line, new_column);
  537. if (event.shift() && m_selection.start().is_valid()) {
  538. m_selection.set_end(m_cursor);
  539. did_update_selection();
  540. }
  541. }
  542. return;
  543. }
  544. if (is_multi_line() && event.key() == KeyCode::Key_Down) {
  545. if (m_cursor.line() < (line_count() - 1)) {
  546. if (event.ctrl() && event.shift()) {
  547. move_selected_lines_down();
  548. return;
  549. }
  550. size_t new_line = m_cursor.line() + 1;
  551. size_t new_column = min(m_cursor.column(), line(new_line).length());
  552. toggle_selection_if_needed_for_event(event);
  553. set_cursor(new_line, new_column);
  554. if (event.shift() && m_selection.start().is_valid()) {
  555. m_selection.set_end(m_cursor);
  556. did_update_selection();
  557. }
  558. }
  559. return;
  560. }
  561. if (is_multi_line() && event.key() == KeyCode::Key_PageUp) {
  562. if (m_cursor.line() > 0) {
  563. size_t page_step = (size_t)visible_content_rect().height() / (size_t)line_height();
  564. size_t new_line = m_cursor.line() < page_step ? 0 : m_cursor.line() - page_step;
  565. size_t new_column = min(m_cursor.column(), line(new_line).length());
  566. toggle_selection_if_needed_for_event(event);
  567. set_cursor(new_line, new_column);
  568. if (event.shift() && m_selection.start().is_valid()) {
  569. m_selection.set_end(m_cursor);
  570. did_update_selection();
  571. }
  572. }
  573. return;
  574. }
  575. if (is_multi_line() && event.key() == KeyCode::Key_PageDown) {
  576. if (m_cursor.line() < (line_count() - 1)) {
  577. int new_line = min(line_count() - 1, m_cursor.line() + visible_content_rect().height() / line_height());
  578. int new_column = min(m_cursor.column(), lines()[new_line].length());
  579. toggle_selection_if_needed_for_event(event);
  580. set_cursor(new_line, new_column);
  581. if (event.shift() && m_selection.start().is_valid()) {
  582. m_selection.set_end(m_cursor);
  583. did_update_selection();
  584. }
  585. }
  586. return;
  587. }
  588. if (event.key() == KeyCode::Key_Left) {
  589. if (event.ctrl() && document().has_spans()) {
  590. // FIXME: Do something nice when the document has no spans.
  591. auto span = document().first_non_skippable_span_before(m_cursor);
  592. TextPosition new_cursor = !span.has_value()
  593. ? TextPosition(0, 0)
  594. : span.value().range.start();
  595. toggle_selection_if_needed_for_event(event);
  596. set_cursor(new_cursor);
  597. if (event.shift() && m_selection.start().is_valid()) {
  598. m_selection.set_end(m_cursor);
  599. did_update_selection();
  600. }
  601. return;
  602. }
  603. if (m_cursor.column() > 0) {
  604. int new_column = m_cursor.column() - 1;
  605. toggle_selection_if_needed_for_event(event);
  606. set_cursor(m_cursor.line(), new_column);
  607. if (event.shift() && m_selection.start().is_valid()) {
  608. m_selection.set_end(m_cursor);
  609. did_update_selection();
  610. }
  611. } else if (m_cursor.line() > 0) {
  612. int new_line = m_cursor.line() - 1;
  613. int new_column = lines()[new_line].length();
  614. toggle_selection_if_needed_for_event(event);
  615. set_cursor(new_line, new_column);
  616. if (event.shift() && m_selection.start().is_valid()) {
  617. m_selection.set_end(m_cursor);
  618. did_update_selection();
  619. }
  620. }
  621. return;
  622. }
  623. if (event.key() == KeyCode::Key_Right) {
  624. if (event.ctrl() && document().has_spans()) {
  625. // FIXME: Do something nice when the document has no spans.
  626. auto span = document().first_non_skippable_span_after(m_cursor);
  627. TextPosition new_cursor = !span.has_value()
  628. ? document().spans().last().range.end()
  629. : span.value().range.start();
  630. toggle_selection_if_needed_for_event(event);
  631. set_cursor(new_cursor);
  632. if (event.shift() && m_selection.start().is_valid()) {
  633. m_selection.set_end(m_cursor);
  634. did_update_selection();
  635. }
  636. return;
  637. }
  638. int new_line = m_cursor.line();
  639. int new_column = m_cursor.column();
  640. if (m_cursor.column() < current_line().length()) {
  641. new_line = m_cursor.line();
  642. new_column = m_cursor.column() + 1;
  643. } else if (m_cursor.line() != line_count() - 1) {
  644. new_line = m_cursor.line() + 1;
  645. new_column = 0;
  646. }
  647. toggle_selection_if_needed_for_event(event);
  648. set_cursor(new_line, new_column);
  649. if (event.shift() && m_selection.start().is_valid()) {
  650. m_selection.set_end(m_cursor);
  651. did_update_selection();
  652. }
  653. return;
  654. }
  655. if (!event.ctrl() && event.key() == KeyCode::Key_Home) {
  656. size_t first_nonspace_column = current_line().first_non_whitespace_column();
  657. toggle_selection_if_needed_for_event(event);
  658. if (m_cursor.column() == first_nonspace_column)
  659. set_cursor(m_cursor.line(), 0);
  660. else
  661. set_cursor(m_cursor.line(), first_nonspace_column);
  662. if (event.shift() && m_selection.start().is_valid()) {
  663. m_selection.set_end(m_cursor);
  664. did_update_selection();
  665. }
  666. return;
  667. }
  668. if (!event.ctrl() && event.key() == KeyCode::Key_End) {
  669. toggle_selection_if_needed_for_event(event);
  670. set_cursor(m_cursor.line(), current_line().length());
  671. if (event.shift() && m_selection.start().is_valid()) {
  672. m_selection.set_end(m_cursor);
  673. did_update_selection();
  674. }
  675. return;
  676. }
  677. if (event.ctrl() && event.key() == KeyCode::Key_Home) {
  678. toggle_selection_if_needed_for_event(event);
  679. set_cursor(0, 0);
  680. if (event.shift() && m_selection.start().is_valid()) {
  681. m_selection.set_end(m_cursor);
  682. did_update_selection();
  683. }
  684. return;
  685. }
  686. if (event.ctrl() && event.key() == KeyCode::Key_End) {
  687. toggle_selection_if_needed_for_event(event);
  688. set_cursor(line_count() - 1, lines()[line_count() - 1].length());
  689. if (event.shift() && m_selection.start().is_valid()) {
  690. m_selection.set_end(m_cursor);
  691. did_update_selection();
  692. }
  693. return;
  694. }
  695. if (event.modifiers() == Mod_Ctrl && event.key() == KeyCode::Key_A) {
  696. select_all();
  697. return;
  698. }
  699. if (event.alt() && event.shift() && event.key() == KeyCode::Key_S) {
  700. sort_selected_lines();
  701. return;
  702. }
  703. if (event.key() == KeyCode::Key_Backspace) {
  704. if (is_readonly())
  705. return;
  706. if (has_selection()) {
  707. delete_selection();
  708. did_update_selection();
  709. return;
  710. }
  711. if (m_cursor.column() > 0) {
  712. int erase_count = 1;
  713. if (current_line().first_non_whitespace_column() >= m_cursor.column()) {
  714. int new_column;
  715. if (m_cursor.column() % m_soft_tab_width == 0)
  716. new_column = m_cursor.column() - m_soft_tab_width;
  717. else
  718. new_column = (m_cursor.column() / m_soft_tab_width) * m_soft_tab_width;
  719. erase_count = m_cursor.column() - new_column;
  720. }
  721. // Backspace within line
  722. TextRange erased_range({ m_cursor.line(), m_cursor.column() - erase_count }, m_cursor);
  723. auto erased_text = document().text_in_range(erased_range);
  724. execute<RemoveTextCommand>(erased_text, erased_range);
  725. return;
  726. }
  727. if (m_cursor.column() == 0 && m_cursor.line() != 0) {
  728. // Backspace at column 0; merge with previous line
  729. size_t previous_length = line(m_cursor.line() - 1).length();
  730. TextRange erased_range({ m_cursor.line() - 1, previous_length }, m_cursor);
  731. execute<RemoveTextCommand>("\n", erased_range);
  732. return;
  733. }
  734. return;
  735. }
  736. if (event.modifiers() == Mod_Shift && event.key() == KeyCode::Key_Delete) {
  737. if (is_readonly())
  738. return;
  739. delete_current_line();
  740. return;
  741. }
  742. if (event.key() == KeyCode::Key_Delete) {
  743. if (is_readonly())
  744. return;
  745. do_delete();
  746. return;
  747. }
  748. if (!is_readonly() && !event.ctrl() && !event.alt() && !event.text().is_empty()) {
  749. insert_at_cursor_or_replace_selection(event.text());
  750. return;
  751. }
  752. event.ignore();
  753. }
  754. void TextEditor::delete_current_line()
  755. {
  756. if (has_selection())
  757. return delete_selection();
  758. TextPosition start;
  759. TextPosition end;
  760. if (m_cursor.line() == 0 && line_count() == 1) {
  761. start = { 0, 0 };
  762. end = { 0, line(0).length() };
  763. } else if (m_cursor.line() == line_count() - 1) {
  764. start = { m_cursor.line() - 1, line(m_cursor.line()).length() };
  765. end = { m_cursor.line(), line(m_cursor.line()).length() };
  766. } else {
  767. start = { m_cursor.line(), 0 };
  768. end = { m_cursor.line() + 1, 0 };
  769. }
  770. TextRange erased_range(start, end);
  771. execute<RemoveTextCommand>(document().text_in_range(erased_range), erased_range);
  772. }
  773. void TextEditor::do_delete()
  774. {
  775. if (is_readonly())
  776. return;
  777. if (has_selection())
  778. return delete_selection();
  779. if (m_cursor.column() < current_line().length()) {
  780. // Delete within line
  781. TextRange erased_range(m_cursor, { m_cursor.line(), m_cursor.column() + 1 });
  782. execute<RemoveTextCommand>(document().text_in_range(erased_range), erased_range);
  783. return;
  784. }
  785. if (m_cursor.column() == current_line().length() && m_cursor.line() != line_count() - 1) {
  786. // Delete at end of line; merge with next line
  787. TextRange erased_range(m_cursor, { m_cursor.line() + 1, 0 });
  788. execute<RemoveTextCommand>(document().text_in_range(erased_range), erased_range);
  789. return;
  790. }
  791. }
  792. int TextEditor::content_x_for_position(const TextPosition& position) const
  793. {
  794. auto& line = this->line(position.line());
  795. int x_offset = -1;
  796. switch (m_text_alignment) {
  797. case Gfx::TextAlignment::CenterLeft:
  798. for_each_visual_line(position.line(), [&](const Gfx::Rect&, const StringView& view, size_t start_of_visual_line) {
  799. if (position.column() >= start_of_visual_line && ((position.column() - start_of_visual_line) <= view.length())) {
  800. x_offset = (position.column() - start_of_visual_line) * glyph_width();
  801. return IterationDecision::Break;
  802. }
  803. return IterationDecision::Continue;
  804. });
  805. return m_horizontal_content_padding + x_offset;
  806. case Gfx::TextAlignment::CenterRight:
  807. // FIXME
  808. ASSERT(!is_line_wrapping_enabled());
  809. return content_width() - m_horizontal_content_padding - (line.length() * glyph_width()) + (position.column() * glyph_width());
  810. default:
  811. ASSERT_NOT_REACHED();
  812. }
  813. }
  814. Gfx::Rect TextEditor::content_rect_for_position(const TextPosition& position) const
  815. {
  816. if (!position.is_valid())
  817. return {};
  818. ASSERT(!lines().is_empty());
  819. ASSERT(position.column() <= (current_line().length() + 1));
  820. int x = content_x_for_position(position);
  821. if (is_single_line()) {
  822. Gfx::Rect rect { x, 0, 1, font().glyph_height() + 2 };
  823. rect.center_vertically_within({ {}, frame_inner_rect().size() });
  824. return rect;
  825. }
  826. Gfx::Rect rect;
  827. for_each_visual_line(position.line(), [&](const Gfx::Rect& visual_line_rect, const StringView& view, size_t start_of_visual_line) {
  828. if (position.column() >= start_of_visual_line && ((position.column() - start_of_visual_line) <= view.length())) {
  829. // NOTE: We have to subtract the horizontal padding here since it's part of the visual line rect
  830. // *and* included in what we get from content_x_for_position().
  831. rect = {
  832. visual_line_rect.x() + x - (m_horizontal_content_padding),
  833. visual_line_rect.y(),
  834. 1,
  835. line_height()
  836. };
  837. return IterationDecision::Break;
  838. }
  839. return IterationDecision::Continue;
  840. });
  841. return rect;
  842. }
  843. Gfx::Rect TextEditor::cursor_content_rect() const
  844. {
  845. return content_rect_for_position(m_cursor);
  846. }
  847. Gfx::Rect TextEditor::line_widget_rect(size_t line_index) const
  848. {
  849. auto rect = line_content_rect(line_index);
  850. rect.set_x(frame_thickness());
  851. rect.set_width(frame_inner_rect().width());
  852. rect.move_by(0, -(vertical_scrollbar().value()));
  853. rect.move_by(0, frame_thickness());
  854. rect.intersect(frame_inner_rect());
  855. return rect;
  856. }
  857. void TextEditor::scroll_position_into_view(const TextPosition& position)
  858. {
  859. auto rect = content_rect_for_position(position);
  860. if (position.column() == 0)
  861. rect.set_x(content_x_for_position({ position.line(), 0 }) - 2);
  862. else if (position.column() == line(position.line()).length())
  863. rect.set_x(content_x_for_position({ position.line(), line(position.line()).length() }) + 2);
  864. scroll_into_view(rect, true, true);
  865. }
  866. void TextEditor::scroll_cursor_into_view()
  867. {
  868. scroll_position_into_view(m_cursor);
  869. }
  870. Gfx::Rect TextEditor::line_content_rect(size_t line_index) const
  871. {
  872. auto& line = this->line(line_index);
  873. if (is_single_line()) {
  874. Gfx::Rect line_rect = { content_x_for_position({ line_index, 0 }), 0, (int)line.length() * glyph_width(), font().glyph_height() + 2 };
  875. line_rect.center_vertically_within({ {}, frame_inner_rect().size() });
  876. return line_rect;
  877. }
  878. if (is_line_wrapping_enabled())
  879. return m_line_visual_data[line_index].visual_rect;
  880. return {
  881. content_x_for_position({ line_index, 0 }),
  882. (int)line_index * line_height(),
  883. (int)line.length() * glyph_width(),
  884. line_height()
  885. };
  886. }
  887. void TextEditor::update_cursor()
  888. {
  889. update(line_widget_rect(m_cursor.line()));
  890. }
  891. void TextEditor::set_cursor(size_t line, size_t column)
  892. {
  893. set_cursor({ line, column });
  894. }
  895. void TextEditor::set_cursor(const TextPosition& a_position)
  896. {
  897. ASSERT(!lines().is_empty());
  898. TextPosition position = a_position;
  899. if (position.line() >= line_count())
  900. position.set_line(line_count() - 1);
  901. if (position.column() > lines()[position.line()].length())
  902. position.set_column(lines()[position.line()].length());
  903. if (m_cursor != position) {
  904. // NOTE: If the old cursor is no longer valid, repaint everything just in case.
  905. auto old_cursor_line_rect = m_cursor.line() < line_count()
  906. ? line_widget_rect(m_cursor.line())
  907. : rect();
  908. m_cursor = position;
  909. m_cursor_state = true;
  910. scroll_cursor_into_view();
  911. update(old_cursor_line_rect);
  912. update_cursor();
  913. }
  914. cursor_did_change();
  915. if (on_cursor_change)
  916. on_cursor_change();
  917. if (m_highlighter)
  918. m_highlighter->cursor_did_change();
  919. }
  920. void TextEditor::focusin_event(Core::Event&)
  921. {
  922. update_cursor();
  923. start_timer(500);
  924. }
  925. void TextEditor::focusout_event(Core::Event&)
  926. {
  927. stop_timer();
  928. }
  929. void TextEditor::timer_event(Core::TimerEvent&)
  930. {
  931. m_cursor_state = !m_cursor_state;
  932. if (is_focused())
  933. update_cursor();
  934. }
  935. bool TextEditor::write_to_file(const StringView& path)
  936. {
  937. int fd = open_with_path_length(path.characters_without_null_termination(), path.length(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
  938. if (fd < 0) {
  939. perror("open");
  940. return false;
  941. }
  942. // Compute the final file size and ftruncate() to make writing fast.
  943. // FIXME: Remove this once the kernel is smart enough to do this instead.
  944. off_t file_size = 0;
  945. for (size_t i = 0; i < line_count(); ++i)
  946. file_size += line(i).length();
  947. file_size += line_count() - 1;
  948. int rc = ftruncate(fd, file_size);
  949. if (rc < 0) {
  950. perror("ftruncate");
  951. return false;
  952. }
  953. for (size_t i = 0; i < line_count(); ++i) {
  954. auto& line = this->line(i);
  955. if (line.length()) {
  956. ssize_t nwritten = write(fd, line.characters(), line.length());
  957. if (nwritten < 0) {
  958. perror("write");
  959. close(fd);
  960. return false;
  961. }
  962. }
  963. if (i != line_count() - 1) {
  964. char ch = '\n';
  965. ssize_t nwritten = write(fd, &ch, 1);
  966. if (nwritten != 1) {
  967. perror("write");
  968. close(fd);
  969. return false;
  970. }
  971. }
  972. }
  973. close(fd);
  974. return true;
  975. }
  976. String TextEditor::text() const
  977. {
  978. StringBuilder builder;
  979. for (size_t i = 0; i < line_count(); ++i) {
  980. auto& line = this->line(i);
  981. builder.append(line.characters(), line.length());
  982. if (i != line_count() - 1)
  983. builder.append('\n');
  984. }
  985. return builder.to_string();
  986. }
  987. void TextEditor::clear()
  988. {
  989. document().remove_all_lines();
  990. document().append_line(make<TextDocumentLine>(document()));
  991. m_selection.clear();
  992. did_update_selection();
  993. set_cursor(0, 0);
  994. update();
  995. }
  996. String TextEditor::selected_text() const
  997. {
  998. if (!has_selection())
  999. return {};
  1000. return document().text_in_range(m_selection);
  1001. }
  1002. void TextEditor::delete_selection()
  1003. {
  1004. auto selection = normalized_selection();
  1005. execute<RemoveTextCommand>(selected_text(), selection);
  1006. m_selection.clear();
  1007. did_update_selection();
  1008. did_change();
  1009. set_cursor(selection.start());
  1010. update();
  1011. }
  1012. void TextEditor::insert_at_cursor_or_replace_selection(const StringView& text)
  1013. {
  1014. ASSERT(!is_readonly());
  1015. if (has_selection())
  1016. delete_selection();
  1017. execute<InsertTextCommand>(text, m_cursor);
  1018. }
  1019. void TextEditor::cut()
  1020. {
  1021. if (is_readonly())
  1022. return;
  1023. auto selected_text = this->selected_text();
  1024. printf("Cut: \"%s\"\n", selected_text.characters());
  1025. Clipboard::the().set_data(selected_text);
  1026. delete_selection();
  1027. }
  1028. void TextEditor::copy()
  1029. {
  1030. auto selected_text = this->selected_text();
  1031. printf("Copy: \"%s\"\n", selected_text.characters());
  1032. Clipboard::the().set_data(selected_text);
  1033. }
  1034. void TextEditor::paste()
  1035. {
  1036. if (is_readonly())
  1037. return;
  1038. auto paste_text = Clipboard::the().data();
  1039. printf("Paste: \"%s\"\n", paste_text.characters());
  1040. TemporaryChange change(m_automatic_indentation_enabled, false);
  1041. insert_at_cursor_or_replace_selection(paste_text);
  1042. }
  1043. void TextEditor::enter_event(Core::Event&)
  1044. {
  1045. ASSERT(window());
  1046. window()->set_override_cursor(StandardCursor::IBeam);
  1047. }
  1048. void TextEditor::leave_event(Core::Event&)
  1049. {
  1050. ASSERT(window());
  1051. window()->set_override_cursor(StandardCursor::None);
  1052. }
  1053. void TextEditor::did_change()
  1054. {
  1055. update_content_size();
  1056. recompute_all_visual_lines();
  1057. m_undo_action->set_enabled(can_undo());
  1058. m_redo_action->set_enabled(can_redo());
  1059. if (!m_has_pending_change_notification) {
  1060. m_has_pending_change_notification = true;
  1061. deferred_invoke([this](auto&) {
  1062. if (!m_has_pending_change_notification)
  1063. return;
  1064. if (on_change)
  1065. on_change();
  1066. if (m_highlighter)
  1067. m_highlighter->rehighlight();
  1068. m_has_pending_change_notification = false;
  1069. });
  1070. }
  1071. }
  1072. void TextEditor::set_readonly(bool readonly)
  1073. {
  1074. if (m_readonly == readonly)
  1075. return;
  1076. m_readonly = readonly;
  1077. m_cut_action->set_enabled(!is_readonly() && has_selection());
  1078. m_delete_action->set_enabled(!is_readonly());
  1079. m_paste_action->set_enabled(!is_readonly());
  1080. }
  1081. void TextEditor::did_update_selection()
  1082. {
  1083. m_cut_action->set_enabled(!is_readonly() && has_selection());
  1084. m_copy_action->set_enabled(has_selection());
  1085. if (on_selection_change)
  1086. on_selection_change();
  1087. if (is_line_wrapping_enabled()) {
  1088. // FIXME: Try to repaint less.
  1089. update();
  1090. }
  1091. }
  1092. void TextEditor::context_menu_event(ContextMenuEvent& event)
  1093. {
  1094. if (!m_context_menu) {
  1095. m_context_menu = Menu::construct();
  1096. m_context_menu->add_action(undo_action());
  1097. m_context_menu->add_action(redo_action());
  1098. m_context_menu->add_separator();
  1099. m_context_menu->add_action(cut_action());
  1100. m_context_menu->add_action(copy_action());
  1101. m_context_menu->add_action(paste_action());
  1102. m_context_menu->add_action(delete_action());
  1103. if (is_multi_line()) {
  1104. m_context_menu->add_separator();
  1105. m_context_menu->add_action(go_to_line_action());
  1106. }
  1107. if (!m_custom_context_menu_actions.is_empty()) {
  1108. m_context_menu->add_separator();
  1109. for (auto& action : m_custom_context_menu_actions) {
  1110. m_context_menu->add_action(action);
  1111. }
  1112. }
  1113. }
  1114. m_context_menu->popup(event.screen_position());
  1115. }
  1116. void TextEditor::set_text_alignment(Gfx::TextAlignment alignment)
  1117. {
  1118. if (m_text_alignment == alignment)
  1119. return;
  1120. m_text_alignment = alignment;
  1121. update();
  1122. }
  1123. void TextEditor::resize_event(ResizeEvent& event)
  1124. {
  1125. ScrollableWidget::resize_event(event);
  1126. update_content_size();
  1127. recompute_all_visual_lines();
  1128. }
  1129. void TextEditor::set_selection(const TextRange& selection)
  1130. {
  1131. if (m_selection == selection)
  1132. return;
  1133. m_selection = selection;
  1134. set_cursor(m_selection.end());
  1135. scroll_position_into_view(normalized_selection().start());
  1136. update();
  1137. }
  1138. void TextEditor::clear_selection()
  1139. {
  1140. if (!has_selection())
  1141. return;
  1142. m_selection.clear();
  1143. update();
  1144. }
  1145. void TextEditor::recompute_all_visual_lines()
  1146. {
  1147. int y_offset = 0;
  1148. for (size_t line_index = 0; line_index < line_count(); ++line_index) {
  1149. recompute_visual_lines(line_index);
  1150. m_line_visual_data[line_index].visual_rect.set_y(y_offset);
  1151. y_offset += m_line_visual_data[line_index].visual_rect.height();
  1152. }
  1153. update_content_size();
  1154. }
  1155. void TextEditor::ensure_cursor_is_valid()
  1156. {
  1157. auto new_cursor = m_cursor;
  1158. if (new_cursor.line() >= line_count())
  1159. new_cursor.set_line(line_count() - 1);
  1160. if (new_cursor.column() > line(new_cursor.line()).length())
  1161. new_cursor.set_column(line(new_cursor.line()).length());
  1162. if (m_cursor != new_cursor)
  1163. set_cursor(new_cursor);
  1164. }
  1165. size_t TextEditor::visual_line_containing(size_t line_index, size_t column) const
  1166. {
  1167. size_t visual_line_index = 0;
  1168. for_each_visual_line(line_index, [&](const Gfx::Rect&, const StringView& view, size_t start_of_visual_line) {
  1169. if (column >= start_of_visual_line && ((column - start_of_visual_line) < view.length()))
  1170. return IterationDecision::Break;
  1171. ++visual_line_index;
  1172. return IterationDecision::Continue;
  1173. });
  1174. return visual_line_index;
  1175. }
  1176. void TextEditor::recompute_visual_lines(size_t line_index)
  1177. {
  1178. auto& line = document().line(line_index);
  1179. auto& visual_data = m_line_visual_data[line_index];
  1180. visual_data.visual_line_breaks.clear_with_capacity();
  1181. int available_width = visible_text_rect_in_inner_coordinates().width();
  1182. if (is_line_wrapping_enabled()) {
  1183. int line_width_so_far = 0;
  1184. for (size_t i = 0; i < line.length(); ++i) {
  1185. auto ch = line.characters()[i];
  1186. auto glyph_width = font().glyph_width(ch);
  1187. if ((line_width_so_far + glyph_width) > available_width) {
  1188. visual_data.visual_line_breaks.append(i);
  1189. line_width_so_far = glyph_width;
  1190. continue;
  1191. }
  1192. line_width_so_far += glyph_width;
  1193. }
  1194. }
  1195. visual_data.visual_line_breaks.append(line.length());
  1196. if (is_line_wrapping_enabled())
  1197. visual_data.visual_rect = { m_horizontal_content_padding, 0, available_width, static_cast<int>(visual_data.visual_line_breaks.size()) * line_height() };
  1198. else
  1199. visual_data.visual_rect = { m_horizontal_content_padding, 0, font().width(line.view()), line_height() };
  1200. }
  1201. template<typename Callback>
  1202. void TextEditor::for_each_visual_line(size_t line_index, Callback callback) const
  1203. {
  1204. auto editor_visible_text_rect = visible_text_rect_in_inner_coordinates();
  1205. size_t start_of_line = 0;
  1206. size_t visual_line_index = 0;
  1207. auto& line = document().line(line_index);
  1208. auto& visual_data = m_line_visual_data[line_index];
  1209. for (auto visual_line_break : visual_data.visual_line_breaks) {
  1210. auto visual_line_view = StringView(line.characters() + start_of_line, visual_line_break - start_of_line);
  1211. Gfx::Rect visual_line_rect {
  1212. visual_data.visual_rect.x(),
  1213. visual_data.visual_rect.y() + ((int)visual_line_index * line_height()),
  1214. font().width(visual_line_view),
  1215. line_height()
  1216. };
  1217. if (is_right_text_alignment(text_alignment()))
  1218. visual_line_rect.set_right_without_resize(editor_visible_text_rect.right());
  1219. if (!is_multi_line())
  1220. visual_line_rect.center_vertically_within(editor_visible_text_rect);
  1221. if (callback(visual_line_rect, visual_line_view, start_of_line) == IterationDecision::Break)
  1222. break;
  1223. start_of_line = visual_line_break;
  1224. ++visual_line_index;
  1225. }
  1226. }
  1227. void TextEditor::set_line_wrapping_enabled(bool enabled)
  1228. {
  1229. if (m_line_wrapping_enabled == enabled)
  1230. return;
  1231. m_line_wrapping_enabled = enabled;
  1232. horizontal_scrollbar().set_visible(!m_line_wrapping_enabled);
  1233. update_content_size();
  1234. recompute_all_visual_lines();
  1235. update();
  1236. }
  1237. void TextEditor::add_custom_context_menu_action(Action& action)
  1238. {
  1239. m_custom_context_menu_actions.append(action);
  1240. }
  1241. void TextEditor::did_change_font()
  1242. {
  1243. vertical_scrollbar().set_step(line_height());
  1244. recompute_all_visual_lines();
  1245. update();
  1246. Widget::did_change_font();
  1247. }
  1248. void TextEditor::document_did_append_line()
  1249. {
  1250. m_line_visual_data.append(make<LineVisualData>());
  1251. recompute_all_visual_lines();
  1252. update();
  1253. }
  1254. void TextEditor::document_did_remove_line(size_t line_index)
  1255. {
  1256. m_line_visual_data.remove(line_index);
  1257. recompute_all_visual_lines();
  1258. update();
  1259. }
  1260. void TextEditor::document_did_remove_all_lines()
  1261. {
  1262. m_line_visual_data.clear();
  1263. recompute_all_visual_lines();
  1264. update();
  1265. }
  1266. void TextEditor::document_did_insert_line(size_t line_index)
  1267. {
  1268. m_line_visual_data.insert(line_index, make<LineVisualData>());
  1269. recompute_all_visual_lines();
  1270. update();
  1271. }
  1272. void TextEditor::document_did_change()
  1273. {
  1274. did_change();
  1275. update();
  1276. }
  1277. void TextEditor::document_did_set_text()
  1278. {
  1279. m_line_visual_data.clear();
  1280. for (size_t i = 0; i < m_document->line_count(); ++i)
  1281. m_line_visual_data.append(make<LineVisualData>());
  1282. document_did_change();
  1283. }
  1284. void TextEditor::document_did_set_cursor(const TextPosition& position)
  1285. {
  1286. set_cursor(position);
  1287. }
  1288. void TextEditor::set_document(TextDocument& document)
  1289. {
  1290. if (m_document.ptr() == &document)
  1291. return;
  1292. if (m_document)
  1293. m_document->unregister_client(*this);
  1294. m_document = document;
  1295. m_line_visual_data.clear();
  1296. for (size_t i = 0; i < m_document->line_count(); ++i) {
  1297. m_line_visual_data.append(make<LineVisualData>());
  1298. }
  1299. m_cursor = { 0, 0 };
  1300. if (has_selection())
  1301. m_selection.clear();
  1302. recompute_all_visual_lines();
  1303. update();
  1304. m_document->register_client(*this);
  1305. }
  1306. void TextEditor::flush_pending_change_notification_if_needed()
  1307. {
  1308. if (!m_has_pending_change_notification)
  1309. return;
  1310. if (on_change)
  1311. on_change();
  1312. if (m_highlighter)
  1313. m_highlighter->rehighlight();
  1314. m_has_pending_change_notification = false;
  1315. }
  1316. void TextEditor::set_syntax_highlighter(OwnPtr<SyntaxHighlighter> highlighter)
  1317. {
  1318. if (m_highlighter)
  1319. m_highlighter->detach();
  1320. m_highlighter = move(highlighter);
  1321. if (m_highlighter) {
  1322. m_highlighter->attach(*this);
  1323. m_highlighter->rehighlight();
  1324. }
  1325. }
  1326. int TextEditor::line_height() const
  1327. {
  1328. return font().glyph_height() + m_line_spacing;
  1329. }
  1330. int TextEditor::glyph_width() const
  1331. {
  1332. return font().glyph_width('x');
  1333. }
  1334. }