GTextEditor.cpp 48 KB

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