GTextEditor.cpp 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755
  1. #include <AK/QuickSort.h>
  2. #include <AK/StringBuilder.h>
  3. #include <Kernel/KeyCode.h>
  4. #include <LibGUI/GAction.h>
  5. #include <LibGUI/GClipboard.h>
  6. #include <LibGUI/GFontDatabase.h>
  7. #include <LibGUI/GMenu.h>
  8. #include <LibGUI/GPainter.h>
  9. #include <LibGUI/GScrollBar.h>
  10. #include <LibGUI/GTextEditor.h>
  11. #include <LibGUI/GWindow.h>
  12. #include <ctype.h>
  13. #include <fcntl.h>
  14. #include <stdio.h>
  15. #include <unistd.h>
  16. //#define DEBUG_GTEXTEDITOR
  17. GTextEditor::GTextEditor(GWidget* parent)
  18. : GTextEditor(Type::MultiLine, parent)
  19. {
  20. }
  21. GTextEditor::GTextEditor(Type type, GWidget* parent)
  22. : GScrollableWidget(parent)
  23. , m_type(type)
  24. {
  25. set_document(GTextDocument::create());
  26. set_frame_shape(FrameShape::Container);
  27. set_frame_shadow(FrameShadow::Sunken);
  28. set_frame_thickness(2);
  29. set_scrollbars_enabled(is_multi_line());
  30. set_font(GFontDatabase::the().get_by_name("Csilla Thin"));
  31. // FIXME: Recompute vertical scrollbar step size on font change.
  32. vertical_scrollbar().set_step(line_height());
  33. m_cursor = { 0, 0 };
  34. create_actions();
  35. // TODO: Instead of a repating timer, this we should call a delayed 2 sec timer when the user types.
  36. m_undo_timer = CTimer::construct(
  37. 2000, [&] {
  38. update_undo_timer();
  39. },
  40. this);
  41. }
  42. GTextEditor::~GTextEditor()
  43. {
  44. if (m_document)
  45. m_document->unregister_client(*this);
  46. }
  47. void GTextEditor::create_actions()
  48. {
  49. m_undo_action = GCommonActions::make_undo_action([&](auto&) { undo(); }, this);
  50. m_redo_action = GCommonActions::make_redo_action([&](auto&) { redo(); }, this);
  51. m_undo_action->set_enabled(false);
  52. m_redo_action->set_enabled(false);
  53. m_cut_action = GCommonActions::make_cut_action([&](auto&) { cut(); }, this);
  54. m_copy_action = GCommonActions::make_copy_action([&](auto&) { copy(); }, this);
  55. m_paste_action = GCommonActions::make_paste_action([&](auto&) { paste(); }, this);
  56. m_delete_action = GCommonActions::make_delete_action([&](auto&) { do_delete(); }, this);
  57. }
  58. void GTextEditor::set_text(const StringView& text)
  59. {
  60. if (is_single_line() && text.length() == line(0).length() && !memcmp(text.characters_without_null_termination(), line(0).characters(), text.length()))
  61. return;
  62. m_selection.clear();
  63. document().set_text(text);
  64. update_content_size();
  65. recompute_all_visual_lines();
  66. if (is_single_line())
  67. set_cursor(0, line(0).length());
  68. else
  69. set_cursor(0, 0);
  70. did_update_selection();
  71. update();
  72. }
  73. void GTextEditor::update_content_size()
  74. {
  75. int content_width = 0;
  76. int content_height = 0;
  77. for (auto& line : m_line_visual_data) {
  78. content_width = max(line.visual_rect.width(), content_width);
  79. content_height += line.visual_rect.height();
  80. }
  81. content_width += m_horizontal_content_padding * 2;
  82. if (is_right_text_alignment(m_text_alignment))
  83. content_width = max(frame_inner_rect().width(), content_width);
  84. set_content_size({ content_width, content_height });
  85. set_size_occupied_by_fixed_elements({ ruler_width(), 0 });
  86. }
  87. GTextPosition GTextEditor::text_position_at(const Point& a_position) const
  88. {
  89. auto position = a_position;
  90. position.move_by(horizontal_scrollbar().value(), vertical_scrollbar().value());
  91. position.move_by(-(m_horizontal_content_padding + ruler_width()), 0);
  92. position.move_by(-frame_thickness(), -frame_thickness());
  93. int line_index = -1;
  94. if (is_line_wrapping_enabled()) {
  95. for (int i = 0; i < lines().size(); ++i) {
  96. auto& rect = m_line_visual_data[i].visual_rect;
  97. if (position.y() >= rect.top() && position.y() <= rect.bottom()) {
  98. line_index = i;
  99. break;
  100. }
  101. if (position.y() > rect.bottom())
  102. line_index = lines().size() - 1;
  103. }
  104. } else {
  105. line_index = position.y() / line_height();
  106. }
  107. line_index = max(0, min(line_index, line_count() - 1));
  108. int column_index;
  109. switch (m_text_alignment) {
  110. case TextAlignment::CenterLeft:
  111. column_index = (position.x() + glyph_width() / 2) / glyph_width();
  112. if (is_line_wrapping_enabled()) {
  113. for_each_visual_line(line_index, [&](const Rect& rect, const StringView&, int start_of_line) {
  114. if (rect.contains_vertically(position.y())) {
  115. column_index += start_of_line;
  116. return IterationDecision::Break;
  117. }
  118. return IterationDecision::Continue;
  119. });
  120. }
  121. break;
  122. case TextAlignment::CenterRight:
  123. // FIXME: Support right-aligned line wrapping, I guess.
  124. ASSERT(!is_line_wrapping_enabled());
  125. column_index = (position.x() - content_x_for_position({ line_index, 0 }) + glyph_width() / 2) / glyph_width();
  126. break;
  127. default:
  128. ASSERT_NOT_REACHED();
  129. }
  130. column_index = max(0, min(column_index, lines()[line_index].length()));
  131. return { line_index, column_index };
  132. }
  133. void GTextEditor::doubleclick_event(GMouseEvent& event)
  134. {
  135. if (event.button() != GMouseButton::Left)
  136. return;
  137. // NOTE: This ensures that spans are updated before we look at them.
  138. flush_pending_change_notification_if_needed();
  139. m_triple_click_timer.start();
  140. m_in_drag_select = false;
  141. auto start = text_position_at(event.position());
  142. auto end = start;
  143. auto& line = lines()[start.line()];
  144. if (!document().has_spans()) {
  145. while (start.column() > 0) {
  146. if (isspace(line.characters()[start.column() - 1]))
  147. break;
  148. start.set_column(start.column() - 1);
  149. }
  150. while (end.column() < line.length()) {
  151. if (isspace(line.characters()[end.column()]))
  152. break;
  153. end.set_column(end.column() + 1);
  154. }
  155. } else {
  156. for (auto& span : document().spans()) {
  157. if (!span.range.contains(start))
  158. continue;
  159. start = span.range.start();
  160. end = span.range.end();
  161. end.set_column(end.column() + 1);
  162. break;
  163. }
  164. }
  165. m_selection.set(start, end);
  166. set_cursor(end);
  167. update();
  168. did_update_selection();
  169. }
  170. void GTextEditor::mousedown_event(GMouseEvent& event)
  171. {
  172. if (event.button() != GMouseButton::Left) {
  173. return;
  174. }
  175. if (m_triple_click_timer.is_valid() && m_triple_click_timer.elapsed() < 250) {
  176. m_triple_click_timer = CElapsedTimer();
  177. GTextPosition start;
  178. GTextPosition end;
  179. if (is_multi_line()) {
  180. // select *current* line
  181. start = GTextPosition(m_cursor.line(), 0);
  182. end = GTextPosition(m_cursor.line(), lines()[m_cursor.line()].length());
  183. } else {
  184. // select *whole* line
  185. start = GTextPosition(0, 0);
  186. end = GTextPosition(line_count() - 1, lines()[line_count() - 1].length());
  187. }
  188. m_selection.set(start, end);
  189. set_cursor(end);
  190. return;
  191. }
  192. if (event.modifiers() & Mod_Shift) {
  193. if (!has_selection())
  194. m_selection.set(m_cursor, {});
  195. } else {
  196. m_selection.clear();
  197. }
  198. m_in_drag_select = true;
  199. set_cursor(text_position_at(event.position()));
  200. if (!(event.modifiers() & Mod_Shift)) {
  201. if (!has_selection())
  202. m_selection.set(m_cursor, {});
  203. }
  204. if (m_selection.start().is_valid() && m_selection.start() != m_cursor)
  205. m_selection.set_end(m_cursor);
  206. // FIXME: Only update the relevant rects.
  207. update();
  208. did_update_selection();
  209. }
  210. void GTextEditor::mouseup_event(GMouseEvent& event)
  211. {
  212. if (event.button() == GMouseButton::Left) {
  213. if (m_in_drag_select) {
  214. m_in_drag_select = false;
  215. }
  216. return;
  217. }
  218. }
  219. void GTextEditor::mousemove_event(GMouseEvent& event)
  220. {
  221. if (m_in_drag_select) {
  222. set_cursor(text_position_at(event.position()));
  223. m_selection.set_end(m_cursor);
  224. did_update_selection();
  225. update();
  226. return;
  227. }
  228. }
  229. int GTextEditor::ruler_width() const
  230. {
  231. if (!m_ruler_visible)
  232. return 0;
  233. // FIXME: Resize based on needed space.
  234. return 5 * font().glyph_width('x') + 4;
  235. }
  236. Rect GTextEditor::ruler_content_rect(int line_index) const
  237. {
  238. if (!m_ruler_visible)
  239. return {};
  240. return {
  241. 0 - ruler_width() + horizontal_scrollbar().value(),
  242. line_content_rect(line_index).y(),
  243. ruler_width(),
  244. line_content_rect(line_index).height()
  245. };
  246. }
  247. Rect GTextEditor::ruler_rect_in_inner_coordinates() const
  248. {
  249. return { 0, 0, ruler_width(), height() - height_occupied_by_horizontal_scrollbar() };
  250. }
  251. Rect GTextEditor::visible_text_rect_in_inner_coordinates() const
  252. {
  253. return {
  254. m_horizontal_content_padding + (m_ruler_visible ? (ruler_rect_in_inner_coordinates().right() + 1) : 0),
  255. 0,
  256. frame_inner_rect().width() - (m_horizontal_content_padding * 2) - width_occupied_by_vertical_scrollbar() - ruler_width(),
  257. frame_inner_rect().height() - height_occupied_by_horizontal_scrollbar()
  258. };
  259. }
  260. void GTextEditor::paint_event(GPaintEvent& event)
  261. {
  262. // NOTE: This ensures that spans are updated before we look at them.
  263. flush_pending_change_notification_if_needed();
  264. GFrame::paint_event(event);
  265. GPainter painter(*this);
  266. painter.add_clip_rect(widget_inner_rect());
  267. painter.add_clip_rect(event.rect());
  268. painter.fill_rect(event.rect(), Color::White);
  269. painter.translate(frame_thickness(), frame_thickness());
  270. auto ruler_rect = ruler_rect_in_inner_coordinates();
  271. if (m_ruler_visible) {
  272. painter.fill_rect(ruler_rect, Color::WarmGray);
  273. painter.draw_line(ruler_rect.top_right(), ruler_rect.bottom_right(), Color::DarkGray);
  274. }
  275. painter.translate(-horizontal_scrollbar().value(), -vertical_scrollbar().value());
  276. if (m_ruler_visible)
  277. painter.translate(ruler_width(), 0);
  278. int first_visible_line = text_position_at(event.rect().top_left()).line();
  279. int last_visible_line = text_position_at(event.rect().bottom_right()).line();
  280. auto selection = normalized_selection();
  281. bool has_selection = selection.is_valid();
  282. if (m_ruler_visible) {
  283. for (int i = first_visible_line; i <= last_visible_line; ++i) {
  284. bool is_current_line = i == m_cursor.line();
  285. auto ruler_line_rect = ruler_content_rect(i);
  286. painter.draw_text(
  287. ruler_line_rect.shrunken(2, 0).translated(0, m_line_spacing / 2),
  288. String::number(i + 1),
  289. is_current_line ? Font::default_bold_font() : font(),
  290. TextAlignment::TopRight,
  291. is_current_line ? Color::DarkGray : Color::MidGray);
  292. }
  293. }
  294. Rect text_clip_rect {
  295. (m_ruler_visible ? (ruler_rect_in_inner_coordinates().right() + frame_thickness() + 1) : frame_thickness()),
  296. frame_thickness(),
  297. width() - width_occupied_by_vertical_scrollbar() - ruler_width(),
  298. height() - height_occupied_by_horizontal_scrollbar()
  299. };
  300. painter.add_clip_rect(text_clip_rect);
  301. for (int line_index = first_visible_line; line_index <= last_visible_line; ++line_index) {
  302. auto& line = lines()[line_index];
  303. bool physical_line_has_selection = has_selection && line_index >= selection.start().line() && line_index <= selection.end().line();
  304. int first_visual_line_with_selection = -1;
  305. int last_visual_line_with_selection = -1;
  306. if (physical_line_has_selection) {
  307. if (selection.start().line() < line_index)
  308. first_visual_line_with_selection = 0;
  309. else
  310. first_visual_line_with_selection = visual_line_containing(line_index, selection.start().column());
  311. if (selection.end().line() > line_index)
  312. last_visual_line_with_selection = m_line_visual_data[line_index].visual_line_breaks.size();
  313. else
  314. last_visual_line_with_selection = visual_line_containing(line_index, selection.end().column());
  315. }
  316. int selection_start_column_within_line = selection.start().line() == line_index ? selection.start().column() : 0;
  317. int selection_end_column_within_line = selection.end().line() == line_index ? selection.end().column() : line.length();
  318. int visual_line_index = 0;
  319. for_each_visual_line(line_index, [&](const Rect& visual_line_rect, const StringView& visual_line_text, int start_of_visual_line) {
  320. if (is_multi_line() && line_index == m_cursor.line())
  321. painter.fill_rect(visual_line_rect, Color(230, 230, 230));
  322. #ifdef DEBUG_GTEXTEDITOR
  323. painter.draw_rect(visual_line_rect, Color::Cyan);
  324. #endif
  325. if (!document().has_spans()) {
  326. // Fast-path for plain text
  327. painter.draw_text(visual_line_rect, visual_line_text, m_text_alignment, Color::Black);
  328. } else {
  329. int advance = font().glyph_width(' ') + font().glyph_spacing();
  330. Rect character_rect = { visual_line_rect.location(), { font().glyph_width(' '), line_height() } };
  331. for (int i = 0; i < visual_line_text.length(); ++i) {
  332. const Font* font = &this->font();
  333. Color color;
  334. Optional<Color> background_color;
  335. GTextPosition physical_position(line_index, start_of_visual_line + i);
  336. // FIXME: This is *horribly* inefficient.
  337. for (auto& span : document().spans()) {
  338. if (!span.range.contains(physical_position))
  339. continue;
  340. color = span.color;
  341. if (span.font)
  342. font = span.font;
  343. background_color = span.background_color;
  344. break;
  345. }
  346. if (background_color.has_value())
  347. painter.fill_rect(character_rect, background_color.value());
  348. painter.draw_text(character_rect, visual_line_text.substring_view(i, 1), *font, m_text_alignment, color);
  349. character_rect.move_by(advance, 0);
  350. }
  351. }
  352. bool physical_line_has_selection = has_selection && line_index >= selection.start().line() && line_index <= selection.end().line();
  353. if (physical_line_has_selection) {
  354. bool current_visual_line_has_selection = (line_index != selection.start().line() && line_index != selection.end().line())
  355. || (visual_line_index >= first_visual_line_with_selection && visual_line_index <= last_visual_line_with_selection);
  356. if (current_visual_line_has_selection) {
  357. bool selection_begins_on_current_visual_line = visual_line_index == first_visual_line_with_selection;
  358. bool selection_ends_on_current_visual_line = visual_line_index == last_visual_line_with_selection;
  359. int selection_left = selection_begins_on_current_visual_line
  360. ? content_x_for_position({ line_index, selection_start_column_within_line })
  361. : m_horizontal_content_padding;
  362. int selection_right = selection_ends_on_current_visual_line
  363. ? content_x_for_position({ line_index, selection_end_column_within_line })
  364. : visual_line_rect.right() + 1;
  365. Rect selection_rect {
  366. selection_left,
  367. visual_line_rect.y(),
  368. selection_right - selection_left,
  369. visual_line_rect.height()
  370. };
  371. painter.fill_rect(selection_rect, Color::from_rgb(0x955233));
  372. int start_of_selection_within_visual_line = max(0, selection_start_column_within_line - start_of_visual_line);
  373. int end_of_selection_within_visual_line = selection_end_column_within_line - start_of_visual_line;
  374. StringView visual_selected_text {
  375. visual_line_text.characters_without_null_termination() + start_of_selection_within_visual_line,
  376. end_of_selection_within_visual_line - start_of_selection_within_visual_line
  377. };
  378. painter.draw_text(selection_rect, visual_selected_text, TextAlignment::CenterLeft, Color::White);
  379. }
  380. }
  381. ++visual_line_index;
  382. return IterationDecision::Continue;
  383. });
  384. }
  385. if (is_focused() && m_cursor_state)
  386. painter.fill_rect(cursor_content_rect(), Color::Red);
  387. }
  388. void GTextEditor::toggle_selection_if_needed_for_event(const GKeyEvent& event)
  389. {
  390. if (event.shift() && !m_selection.is_valid()) {
  391. m_selection.set(m_cursor, {});
  392. did_update_selection();
  393. update();
  394. return;
  395. }
  396. if (!event.shift() && m_selection.is_valid()) {
  397. m_selection.clear();
  398. did_update_selection();
  399. update();
  400. return;
  401. }
  402. }
  403. void GTextEditor::select_all()
  404. {
  405. GTextPosition start_of_document { 0, 0 };
  406. GTextPosition end_of_document { line_count() - 1, lines()[line_count() - 1].length() };
  407. m_selection.set(start_of_document, end_of_document);
  408. did_update_selection();
  409. set_cursor(end_of_document);
  410. update();
  411. }
  412. void GTextEditor::undo()
  413. {
  414. if (!can_undo())
  415. return;
  416. auto& undo_container = m_undo_stack[m_undo_stack_index];
  417. auto& undo_vector = undo_container.m_undo_vector;
  418. //If we try to undo a empty vector, delete it and skip over.
  419. if (undo_vector.is_empty()) {
  420. m_undo_stack.remove(m_undo_stack_index);
  421. undo();
  422. return;
  423. }
  424. for (int i = 0; i < undo_vector.size(); i++) {
  425. auto& undo_command = undo_vector[i];
  426. undo_command.undo();
  427. }
  428. m_undo_stack_index++;
  429. did_change();
  430. }
  431. void GTextEditor::redo()
  432. {
  433. if (!can_redo())
  434. return;
  435. auto& undo_container = m_undo_stack[m_undo_stack_index - 1];
  436. auto& redo_vector = undo_container.m_undo_vector;
  437. for (int i = redo_vector.size() - 1; i >= 0; i--) {
  438. auto& undo_command = redo_vector[i];
  439. undo_command.redo();
  440. }
  441. m_undo_stack_index--;
  442. did_change();
  443. }
  444. void GTextEditor::get_selection_line_boundaries(int& first_line, int& last_line)
  445. {
  446. auto selection = normalized_selection();
  447. if (!selection.is_valid()) {
  448. first_line = m_cursor.line();
  449. last_line = m_cursor.line();
  450. return;
  451. }
  452. first_line = selection.start().line();
  453. last_line = selection.end().line();
  454. if (first_line != last_line && selection.end().column() == 0)
  455. last_line -= 1;
  456. }
  457. void GTextEditor::move_selected_lines_up()
  458. {
  459. int first_line;
  460. int last_line;
  461. get_selection_line_boundaries(first_line, last_line);
  462. if (first_line == 0)
  463. return;
  464. auto& lines = document().lines();
  465. lines.insert(last_line, lines.take(first_line - 1));
  466. m_cursor = { first_line - 1, 0 };
  467. if (has_selection()) {
  468. m_selection.set_start({ first_line - 1, 0 });
  469. m_selection.set_end({ last_line - 1, line(last_line - 1).length() });
  470. }
  471. did_change();
  472. update();
  473. }
  474. void GTextEditor::move_selected_lines_down()
  475. {
  476. int first_line;
  477. int last_line;
  478. get_selection_line_boundaries(first_line, last_line);
  479. auto& lines = document().lines();
  480. if (last_line >= (lines.size() - 1))
  481. return;
  482. lines.insert(first_line, lines.take(last_line + 1));
  483. m_cursor = { first_line + 1, 0 };
  484. if (has_selection()) {
  485. m_selection.set_start({ first_line + 1, 0 });
  486. m_selection.set_end({ last_line + 1, line(last_line + 1).length() });
  487. }
  488. did_change();
  489. update();
  490. }
  491. void GTextEditor::sort_selected_lines()
  492. {
  493. if (is_readonly())
  494. return;
  495. if (!has_selection())
  496. return;
  497. int first_line;
  498. int last_line;
  499. get_selection_line_boundaries(first_line, last_line);
  500. auto& lines = document().lines();
  501. auto start = lines.begin() + first_line;
  502. auto end = lines.begin() + last_line + 1;
  503. quick_sort(start, end, [](auto& a, auto& b) {
  504. return strcmp(a.characters(), b.characters()) < 0;
  505. });
  506. did_change();
  507. update();
  508. }
  509. void GTextEditor::keydown_event(GKeyEvent& event)
  510. {
  511. if (is_single_line() && event.key() == KeyCode::Key_Tab)
  512. return GWidget::keydown_event(event);
  513. if (is_single_line() && event.key() == KeyCode::Key_Return) {
  514. if (on_return_pressed)
  515. on_return_pressed();
  516. return;
  517. }
  518. if (event.key() == KeyCode::Key_Escape) {
  519. if (on_escape_pressed)
  520. on_escape_pressed();
  521. return;
  522. }
  523. if (event.key() == KeyCode::Key_Up) {
  524. if (m_cursor.line() > 0) {
  525. if (event.ctrl() && event.shift()) {
  526. move_selected_lines_up();
  527. return;
  528. }
  529. int new_line = m_cursor.line() - 1;
  530. int new_column = min(m_cursor.column(), lines()[new_line].length());
  531. toggle_selection_if_needed_for_event(event);
  532. set_cursor(new_line, new_column);
  533. if (event.shift() && m_selection.start().is_valid()) {
  534. m_selection.set_end(m_cursor);
  535. did_update_selection();
  536. }
  537. }
  538. return;
  539. }
  540. if (event.key() == KeyCode::Key_Down) {
  541. if (m_cursor.line() < (lines().size() - 1)) {
  542. if (event.ctrl() && event.shift()) {
  543. move_selected_lines_down();
  544. return;
  545. }
  546. int new_line = m_cursor.line() + 1;
  547. int new_column = min(m_cursor.column(), lines()[new_line].length());
  548. toggle_selection_if_needed_for_event(event);
  549. set_cursor(new_line, new_column);
  550. if (event.shift() && m_selection.start().is_valid()) {
  551. m_selection.set_end(m_cursor);
  552. did_update_selection();
  553. }
  554. }
  555. return;
  556. }
  557. if (event.key() == KeyCode::Key_PageUp) {
  558. if (m_cursor.line() > 0) {
  559. int new_line = max(0, m_cursor.line() - visible_content_rect().height() / line_height());
  560. int new_column = min(m_cursor.column(), lines()[new_line].length());
  561. toggle_selection_if_needed_for_event(event);
  562. set_cursor(new_line, new_column);
  563. if (event.shift() && m_selection.start().is_valid()) {
  564. m_selection.set_end(m_cursor);
  565. did_update_selection();
  566. }
  567. }
  568. return;
  569. }
  570. if (event.key() == KeyCode::Key_PageDown) {
  571. if (m_cursor.line() < (lines().size() - 1)) {
  572. int new_line = min(line_count() - 1, m_cursor.line() + visible_content_rect().height() / line_height());
  573. int new_column = min(m_cursor.column(), lines()[new_line].length());
  574. toggle_selection_if_needed_for_event(event);
  575. set_cursor(new_line, new_column);
  576. if (event.shift() && m_selection.start().is_valid()) {
  577. m_selection.set_end(m_cursor);
  578. did_update_selection();
  579. }
  580. }
  581. return;
  582. }
  583. if (event.key() == KeyCode::Key_Left) {
  584. if (event.ctrl() && document().has_spans()) {
  585. // FIXME: Do something nice when the document has no spans.
  586. auto span = document().first_non_skippable_span_before(m_cursor);
  587. GTextPosition new_cursor = !span.has_value()
  588. ? GTextPosition(0, 0)
  589. : span.value().range.start();
  590. toggle_selection_if_needed_for_event(event);
  591. set_cursor(new_cursor);
  592. if (event.shift() && m_selection.start().is_valid()) {
  593. m_selection.set_end(m_cursor);
  594. did_update_selection();
  595. }
  596. return;
  597. }
  598. if (m_cursor.column() > 0) {
  599. int new_column = m_cursor.column() - 1;
  600. toggle_selection_if_needed_for_event(event);
  601. set_cursor(m_cursor.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. } else if (m_cursor.line() > 0) {
  607. int new_line = m_cursor.line() - 1;
  608. int new_column = lines()[new_line].length();
  609. toggle_selection_if_needed_for_event(event);
  610. set_cursor(new_line, new_column);
  611. if (event.shift() && m_selection.start().is_valid()) {
  612. m_selection.set_end(m_cursor);
  613. did_update_selection();
  614. }
  615. }
  616. return;
  617. }
  618. if (event.key() == KeyCode::Key_Right) {
  619. if (event.ctrl() && document().has_spans()) {
  620. // FIXME: Do something nice when the document has no spans.
  621. auto span = document().first_non_skippable_span_after(m_cursor);
  622. GTextPosition new_cursor = !span.has_value()
  623. ? document().spans().last().range.end()
  624. : span.value().range.start();
  625. toggle_selection_if_needed_for_event(event);
  626. set_cursor(new_cursor);
  627. if (event.shift() && m_selection.start().is_valid()) {
  628. m_selection.set_end(m_cursor);
  629. did_update_selection();
  630. }
  631. return;
  632. }
  633. int new_line = m_cursor.line();
  634. int new_column = m_cursor.column();
  635. if (m_cursor.column() < current_line().length()) {
  636. new_line = m_cursor.line();
  637. new_column = m_cursor.column() + 1;
  638. } else if (m_cursor.line() != line_count() - 1) {
  639. new_line = m_cursor.line() + 1;
  640. new_column = 0;
  641. }
  642. toggle_selection_if_needed_for_event(event);
  643. set_cursor(new_line, new_column);
  644. if (event.shift() && m_selection.start().is_valid()) {
  645. m_selection.set_end(m_cursor);
  646. did_update_selection();
  647. }
  648. return;
  649. }
  650. if (!event.ctrl() && event.key() == KeyCode::Key_Home) {
  651. int first_nonspace_column = current_line().first_non_whitespace_column();
  652. toggle_selection_if_needed_for_event(event);
  653. if (m_cursor.column() == first_nonspace_column)
  654. set_cursor(m_cursor.line(), 0);
  655. else
  656. set_cursor(m_cursor.line(), first_nonspace_column);
  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_End) {
  664. toggle_selection_if_needed_for_event(event);
  665. set_cursor(m_cursor.line(), current_line().length());
  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_Home) {
  673. toggle_selection_if_needed_for_event(event);
  674. set_cursor(0, 0);
  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.ctrl() && event.key() == KeyCode::Key_End) {
  682. toggle_selection_if_needed_for_event(event);
  683. set_cursor(line_count() - 1, lines()[line_count() - 1].length());
  684. if (event.shift() && m_selection.start().is_valid()) {
  685. m_selection.set_end(m_cursor);
  686. did_update_selection();
  687. }
  688. return;
  689. }
  690. if (event.modifiers() == Mod_Ctrl && event.key() == KeyCode::Key_A) {
  691. select_all();
  692. return;
  693. }
  694. if (event.alt() && event.shift() && event.key() == KeyCode::Key_S) {
  695. sort_selected_lines();
  696. return;
  697. }
  698. if (event.key() == KeyCode::Key_Backspace) {
  699. if (is_readonly())
  700. return;
  701. if (has_selection()) {
  702. delete_selection();
  703. did_update_selection();
  704. return;
  705. }
  706. if (m_cursor.column() > 0) {
  707. int erase_count = 1;
  708. if (current_line().first_non_whitespace_column() >= m_cursor.column()) {
  709. int new_column;
  710. if (m_cursor.column() % m_soft_tab_width == 0)
  711. new_column = m_cursor.column() - m_soft_tab_width;
  712. else
  713. new_column = (m_cursor.column() / m_soft_tab_width) * m_soft_tab_width;
  714. erase_count = m_cursor.column() - new_column;
  715. }
  716. // Backspace within line
  717. for (int i = 0; i < erase_count; ++i) {
  718. int row = m_cursor.line();
  719. int column = m_cursor.column() - 1 - i;
  720. add_to_undo_stack(make<RemoveCharacterCommand>(*this, document().line(row).characters()[column], GTextPosition(row, column)));
  721. current_line().remove(document(), m_cursor.column() - 1 - i);
  722. }
  723. update_content_size();
  724. set_cursor(m_cursor.line(), m_cursor.column() - erase_count);
  725. did_change();
  726. return;
  727. }
  728. if (m_cursor.column() == 0 && m_cursor.line() != 0) {
  729. // Backspace at column 0; merge with previous line
  730. auto& previous_line = lines()[m_cursor.line() - 1];
  731. int previous_length = previous_line.length();
  732. int row = m_cursor.line();
  733. int column = previous_length;
  734. add_to_undo_stack(make<RemoveLineCommand>(*this, String(lines()[m_cursor.line()].view()), GTextPosition(row, column), true));
  735. previous_line.append(document(), current_line().characters(), current_line().length());
  736. document().remove_line(m_cursor.line());
  737. update_content_size();
  738. update();
  739. set_cursor(m_cursor.line() - 1, previous_length);
  740. did_change();
  741. return;
  742. }
  743. return;
  744. }
  745. if (event.modifiers() == Mod_Shift && event.key() == KeyCode::Key_Delete) {
  746. if (is_readonly())
  747. return;
  748. delete_current_line();
  749. return;
  750. }
  751. if (event.key() == KeyCode::Key_Delete) {
  752. if (is_readonly())
  753. return;
  754. do_delete();
  755. return;
  756. }
  757. if (!is_readonly() && !event.ctrl() && !event.alt() && !event.text().is_empty())
  758. insert_at_cursor_or_replace_selection(event.text());
  759. }
  760. void GTextEditor::delete_current_line()
  761. {
  762. if (has_selection())
  763. return delete_selection();
  764. document().remove_line(m_cursor.line());
  765. if (lines().is_empty())
  766. document().append_line(make<GTextDocumentLine>(document()));
  767. m_cursor.set_column(0);
  768. update_content_size();
  769. update();
  770. }
  771. void GTextEditor::do_delete()
  772. {
  773. if (is_readonly())
  774. return;
  775. if (has_selection())
  776. return delete_selection();
  777. if (m_cursor.column() < current_line().length()) {
  778. // Delete within line
  779. current_line().remove(document(), m_cursor.column());
  780. did_change();
  781. update_cursor();
  782. return;
  783. }
  784. if (m_cursor.column() == current_line().length() && m_cursor.line() != line_count() - 1) {
  785. // Delete at end of line; merge with next line
  786. auto& next_line = lines()[m_cursor.line() + 1];
  787. int previous_length = current_line().length();
  788. current_line().append(document(), next_line.characters(), next_line.length());
  789. document().remove_line(m_cursor.line() + 1);
  790. update();
  791. did_change();
  792. set_cursor(m_cursor.line(), previous_length);
  793. return;
  794. }
  795. }
  796. void GTextEditor::insert_at_cursor(const StringView& text)
  797. {
  798. // FIXME: This should obviously not be implemented this way.
  799. for (int i = 0; i < text.length(); ++i) {
  800. insert_at_cursor(text[i]);
  801. }
  802. }
  803. void GTextEditor::insert_at_cursor(char ch)
  804. {
  805. bool at_head = m_cursor.column() == 0;
  806. bool at_tail = m_cursor.column() == current_line().length();
  807. if (ch == '\n') {
  808. if (at_tail || at_head) {
  809. String new_line_contents;
  810. if (m_automatic_indentation_enabled && at_tail) {
  811. int leading_spaces = 0;
  812. auto& old_line = lines()[m_cursor.line()];
  813. for (int i = 0; i < old_line.length(); ++i) {
  814. if (old_line.characters()[i] == ' ')
  815. ++leading_spaces;
  816. else
  817. break;
  818. }
  819. if (leading_spaces)
  820. new_line_contents = String::repeated(' ', leading_spaces);
  821. }
  822. int row = m_cursor.line();
  823. int column = m_cursor.column() + 1;
  824. Vector<char> line_content;
  825. for (int i = m_cursor.column(); i < document().lines()[row].length(); i++)
  826. line_content.append(document().lines()[row].characters()[i]);
  827. add_to_undo_stack(make<CreateLineCommand>(*this, line_content, GTextPosition(row, column)));
  828. document().insert_line(m_cursor.line() + (at_tail ? 1 : 0), make<GTextDocumentLine>(document(), new_line_contents));
  829. update();
  830. did_change();
  831. set_cursor(m_cursor.line() + 1, lines()[m_cursor.line() + 1].length());
  832. return;
  833. }
  834. auto new_line = make<GTextDocumentLine>(document());
  835. new_line->append(document(), current_line().characters() + m_cursor.column(), current_line().length() - m_cursor.column());
  836. int row = m_cursor.line();
  837. int column = m_cursor.column() + 1;
  838. Vector<char> line_content;
  839. for (int i = 0; i < new_line->length(); i++)
  840. line_content.append(new_line->characters()[i]);
  841. add_to_undo_stack(make<CreateLineCommand>(*this, line_content, GTextPosition(row, column)));
  842. current_line().truncate(document(), m_cursor.column());
  843. document().insert_line(m_cursor.line() + 1, move(new_line));
  844. update();
  845. did_change();
  846. set_cursor(m_cursor.line() + 1, 0);
  847. return;
  848. }
  849. if (ch == '\t') {
  850. int next_soft_tab_stop = ((m_cursor.column() + m_soft_tab_width) / m_soft_tab_width) * m_soft_tab_width;
  851. int spaces_to_insert = next_soft_tab_stop - m_cursor.column();
  852. for (int i = 0; i < spaces_to_insert; ++i) {
  853. current_line().insert(document(), m_cursor.column(), ' ');
  854. }
  855. did_change();
  856. set_cursor(m_cursor.line(), next_soft_tab_stop);
  857. return;
  858. }
  859. current_line().insert(document(), m_cursor.column(), ch);
  860. did_change();
  861. set_cursor(m_cursor.line(), m_cursor.column() + 1);
  862. add_to_undo_stack(make<InsertCharacterCommand>(*this, ch, m_cursor));
  863. }
  864. int GTextEditor::content_x_for_position(const GTextPosition& position) const
  865. {
  866. auto& line = lines()[position.line()];
  867. int x_offset = -1;
  868. switch (m_text_alignment) {
  869. case TextAlignment::CenterLeft:
  870. for_each_visual_line(position.line(), [&](const Rect&, const StringView& view, int start_of_visual_line) {
  871. if (position.column() >= start_of_visual_line && ((position.column() - start_of_visual_line) <= view.length())) {
  872. x_offset = (position.column() - start_of_visual_line) * glyph_width();
  873. return IterationDecision::Break;
  874. }
  875. return IterationDecision::Continue;
  876. });
  877. return m_horizontal_content_padding + x_offset;
  878. case TextAlignment::CenterRight:
  879. // FIXME
  880. ASSERT(!is_line_wrapping_enabled());
  881. return content_width() - m_horizontal_content_padding - (line.length() * glyph_width()) + (position.column() * glyph_width());
  882. default:
  883. ASSERT_NOT_REACHED();
  884. }
  885. }
  886. Rect GTextEditor::content_rect_for_position(const GTextPosition& position) const
  887. {
  888. if (!position.is_valid())
  889. return {};
  890. ASSERT(!lines().is_empty());
  891. ASSERT(position.column() <= (current_line().length() + 1));
  892. int x = content_x_for_position(position);
  893. if (is_single_line()) {
  894. Rect rect { x, 0, 1, font().glyph_height() + 2 };
  895. rect.center_vertically_within({ {}, frame_inner_rect().size() });
  896. return rect;
  897. }
  898. Rect rect;
  899. for_each_visual_line(position.line(), [&](const Rect& visual_line_rect, const StringView& view, int start_of_visual_line) {
  900. if (position.column() >= start_of_visual_line && ((position.column() - start_of_visual_line) <= view.length())) {
  901. // NOTE: We have to subtract the horizontal padding here since it's part of the visual line rect
  902. // *and* included in what we get from content_x_for_position().
  903. rect = {
  904. visual_line_rect.x() + x - (m_horizontal_content_padding),
  905. visual_line_rect.y(),
  906. 1,
  907. line_height()
  908. };
  909. return IterationDecision::Break;
  910. }
  911. return IterationDecision::Continue;
  912. });
  913. return rect;
  914. }
  915. Rect GTextEditor::cursor_content_rect() const
  916. {
  917. return content_rect_for_position(m_cursor);
  918. }
  919. Rect GTextEditor::line_widget_rect(int line_index) const
  920. {
  921. auto rect = line_content_rect(line_index);
  922. rect.set_x(frame_thickness());
  923. rect.set_width(frame_inner_rect().width());
  924. rect.move_by(0, -(vertical_scrollbar().value()));
  925. rect.move_by(0, frame_thickness());
  926. rect.intersect(frame_inner_rect());
  927. return rect;
  928. }
  929. void GTextEditor::scroll_position_into_view(const GTextPosition& position)
  930. {
  931. auto rect = content_rect_for_position(position);
  932. if (position.column() == 0)
  933. rect.set_x(content_x_for_position({ position.line(), 0 }) - 2);
  934. else if (position.column() == lines()[position.line()].length())
  935. rect.set_x(content_x_for_position({ position.line(), lines()[position.line()].length() }) + 2);
  936. scroll_into_view(rect, true, true);
  937. }
  938. void GTextEditor::scroll_cursor_into_view()
  939. {
  940. scroll_position_into_view(m_cursor);
  941. }
  942. Rect GTextEditor::line_content_rect(int line_index) const
  943. {
  944. auto& line = lines()[line_index];
  945. if (is_single_line()) {
  946. Rect line_rect = { content_x_for_position({ line_index, 0 }), 0, line.length() * glyph_width(), font().glyph_height() + 2 };
  947. line_rect.center_vertically_within({ {}, frame_inner_rect().size() });
  948. return line_rect;
  949. }
  950. if (is_line_wrapping_enabled())
  951. return m_line_visual_data[line_index].visual_rect;
  952. return {
  953. content_x_for_position({ line_index, 0 }),
  954. line_index * line_height(),
  955. line.length() * glyph_width(),
  956. line_height()
  957. };
  958. }
  959. void GTextEditor::update_cursor()
  960. {
  961. update(line_widget_rect(m_cursor.line()));
  962. }
  963. void GTextEditor::update_undo_timer()
  964. {
  965. if (m_undo_stack.is_empty())
  966. return;
  967. auto& undo_vector = m_undo_stack[0].m_undo_vector;
  968. if (undo_vector.size() == m_last_updated_undo_vector_size && !undo_vector.is_empty()) {
  969. auto undo_commands_container = make<UndoCommandsContainer>();
  970. m_undo_stack.prepend(move(undo_commands_container));
  971. // Note: Remove dbg() if we're 100% sure there are no bugs left.
  972. dbg() << "Undo stack increased to " << m_undo_stack.size();
  973. // Shift the index to the left since we're adding an empty container.
  974. if (m_undo_stack_index > 0)
  975. m_undo_stack_index++;
  976. }
  977. m_last_updated_undo_vector_size = undo_vector.size();
  978. }
  979. void GTextEditor::set_cursor(int line, int column)
  980. {
  981. set_cursor({ line, column });
  982. }
  983. void GTextEditor::set_cursor(const GTextPosition& a_position)
  984. {
  985. ASSERT(!lines().is_empty());
  986. GTextPosition position = a_position;
  987. if (position.line() >= lines().size())
  988. position.set_line(lines().size() - 1);
  989. if (position.column() > lines()[position.line()].length())
  990. position.set_column(lines()[position.line()].length());
  991. if (m_cursor != position) {
  992. // NOTE: If the old cursor is no longer valid, repaint everything just in case.
  993. auto old_cursor_line_rect = m_cursor.line() < lines().size()
  994. ? line_widget_rect(m_cursor.line())
  995. : rect();
  996. m_cursor = position;
  997. m_cursor_state = true;
  998. scroll_cursor_into_view();
  999. update(old_cursor_line_rect);
  1000. update_cursor();
  1001. }
  1002. cursor_did_change();
  1003. if (on_cursor_change)
  1004. on_cursor_change();
  1005. }
  1006. void GTextEditor::focusin_event(CEvent&)
  1007. {
  1008. update_cursor();
  1009. start_timer(500);
  1010. }
  1011. void GTextEditor::focusout_event(CEvent&)
  1012. {
  1013. stop_timer();
  1014. }
  1015. void GTextEditor::timer_event(CTimerEvent&)
  1016. {
  1017. m_cursor_state = !m_cursor_state;
  1018. if (is_focused())
  1019. update_cursor();
  1020. }
  1021. bool GTextEditor::write_to_file(const StringView& path)
  1022. {
  1023. int fd = open_with_path_length(path.characters_without_null_termination(), path.length(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
  1024. if (fd < 0) {
  1025. perror("open");
  1026. return false;
  1027. }
  1028. // Compute the final file size and ftruncate() to make writing fast.
  1029. // FIXME: Remove this once the kernel is smart enough to do this instead.
  1030. off_t file_size = 0;
  1031. for (int i = 0; i < lines().size(); ++i)
  1032. file_size += lines()[i].length();
  1033. file_size += lines().size() - 1;
  1034. int rc = ftruncate(fd, file_size);
  1035. if (rc < 0) {
  1036. perror("ftruncate");
  1037. return false;
  1038. }
  1039. for (int i = 0; i < lines().size(); ++i) {
  1040. auto& line = lines()[i];
  1041. if (line.length()) {
  1042. ssize_t nwritten = write(fd, line.characters(), line.length());
  1043. if (nwritten < 0) {
  1044. perror("write");
  1045. close(fd);
  1046. return false;
  1047. }
  1048. }
  1049. if (i != lines().size() - 1) {
  1050. char ch = '\n';
  1051. ssize_t nwritten = write(fd, &ch, 1);
  1052. if (nwritten != 1) {
  1053. perror("write");
  1054. close(fd);
  1055. return false;
  1056. }
  1057. }
  1058. }
  1059. close(fd);
  1060. return true;
  1061. }
  1062. String GTextEditor::text() const
  1063. {
  1064. StringBuilder builder;
  1065. for (int i = 0; i < line_count(); ++i) {
  1066. auto& line = lines()[i];
  1067. builder.append(line.characters(), line.length());
  1068. if (i != line_count() - 1)
  1069. builder.append('\n');
  1070. }
  1071. return builder.to_string();
  1072. }
  1073. void GTextEditor::clear()
  1074. {
  1075. document().remove_all_lines();
  1076. document().append_line(make<GTextDocumentLine>(document()));
  1077. m_selection.clear();
  1078. did_update_selection();
  1079. set_cursor(0, 0);
  1080. update();
  1081. }
  1082. String GTextEditor::selected_text() const
  1083. {
  1084. if (!has_selection())
  1085. return {};
  1086. return document().text_in_range(m_selection);
  1087. }
  1088. void GTextEditor::delete_selection()
  1089. {
  1090. if (!has_selection())
  1091. return;
  1092. auto selection = normalized_selection();
  1093. // First delete all the lines in between the first and last one.
  1094. for (int i = selection.start().line() + 1; i < selection.end().line();) {
  1095. int row = i;
  1096. int column = lines()[i].length();
  1097. add_to_undo_stack(make<RemoveLineCommand>(*this, String(lines()[i].view()), GTextPosition(row, column), false));
  1098. document().remove_line(i);
  1099. selection.end().set_line(selection.end().line() - 1);
  1100. }
  1101. if (selection.start().line() == selection.end().line()) {
  1102. // Delete within same line.
  1103. auto& line = lines()[selection.start().line()];
  1104. bool whole_line_is_selected = selection.start().column() == 0 && selection.end().column() == line.length();
  1105. for (int i = selection.end().column() - 1; i >= selection.start().column(); i--) {
  1106. int row = selection.start().line();
  1107. int column = i;
  1108. add_to_undo_stack(make<RemoveCharacterCommand>(*this, document().line(row).characters()[column], GTextPosition(row, column)));
  1109. }
  1110. if (whole_line_is_selected) {
  1111. line.clear(document());
  1112. } else {
  1113. auto before_selection = String(line.characters(), line.length()).substring(0, selection.start().column());
  1114. auto after_selection = String(line.characters(), line.length()).substring(selection.end().column(), line.length() - selection.end().column());
  1115. StringBuilder builder(before_selection.length() + after_selection.length());
  1116. builder.append(before_selection);
  1117. builder.append(after_selection);
  1118. line.set_text(document(), builder.to_string());
  1119. }
  1120. } else {
  1121. // Delete across a newline, merging lines.
  1122. ASSERT(selection.start().line() == selection.end().line() - 1);
  1123. auto& first_line = lines()[selection.start().line()];
  1124. auto& second_line = lines()[selection.end().line()];
  1125. auto before_selection = String(first_line.characters(), first_line.length()).substring(0, selection.start().column());
  1126. auto after_selection = String(second_line.characters(), second_line.length()).substring(selection.end().column(), second_line.length() - selection.end().column());
  1127. StringBuilder builder(before_selection.length() + after_selection.length());
  1128. builder.append(before_selection);
  1129. builder.append(after_selection);
  1130. for (int i = first_line.length() - 1; i > selection.start().column() - 1; i--) {
  1131. int row = selection.start().line();
  1132. int column = i;
  1133. add_to_undo_stack(make<RemoveCharacterCommand>(*this, document().line(row).characters()[column], GTextPosition(row, column)));
  1134. }
  1135. add_to_undo_stack(make<RemoveLineCommand>(*this, String(second_line.view()), selection.end(), false));
  1136. first_line.set_text(document(), builder.to_string());
  1137. document().remove_line(selection.end().line());
  1138. for (int i = (first_line.length()) - after_selection.length(); i < first_line.length(); i++)
  1139. add_to_undo_stack(make<InsertCharacterCommand>(*this, first_line.characters()[i], GTextPosition(selection.start().line(), i + 1)));
  1140. }
  1141. if (lines().is_empty()) {
  1142. document().append_line(make<GTextDocumentLine>(document()));
  1143. }
  1144. m_selection.clear();
  1145. did_update_selection();
  1146. did_change();
  1147. set_cursor(selection.start());
  1148. update();
  1149. }
  1150. void GTextEditor::insert_at_cursor_or_replace_selection(const StringView& text)
  1151. {
  1152. ASSERT(!is_readonly());
  1153. if (has_selection())
  1154. delete_selection();
  1155. insert_at_cursor(text);
  1156. }
  1157. void GTextEditor::cut()
  1158. {
  1159. if (is_readonly())
  1160. return;
  1161. auto selected_text = this->selected_text();
  1162. printf("Cut: \"%s\"\n", selected_text.characters());
  1163. GClipboard::the().set_data(selected_text);
  1164. delete_selection();
  1165. }
  1166. void GTextEditor::copy()
  1167. {
  1168. auto selected_text = this->selected_text();
  1169. printf("Copy: \"%s\"\n", selected_text.characters());
  1170. GClipboard::the().set_data(selected_text);
  1171. }
  1172. void GTextEditor::paste()
  1173. {
  1174. if (is_readonly())
  1175. return;
  1176. auto paste_text = GClipboard::the().data();
  1177. printf("Paste: \"%s\"\n", paste_text.characters());
  1178. insert_at_cursor_or_replace_selection(paste_text);
  1179. }
  1180. void GTextEditor::enter_event(CEvent&)
  1181. {
  1182. ASSERT(window());
  1183. window()->set_override_cursor(GStandardCursor::IBeam);
  1184. }
  1185. void GTextEditor::leave_event(CEvent&)
  1186. {
  1187. ASSERT(window());
  1188. window()->set_override_cursor(GStandardCursor::None);
  1189. }
  1190. void GTextEditor::did_change()
  1191. {
  1192. ASSERT(!is_readonly());
  1193. update_content_size();
  1194. recompute_all_visual_lines();
  1195. m_undo_action->set_enabled(can_undo());
  1196. m_redo_action->set_enabled(can_redo());
  1197. if (!m_has_pending_change_notification) {
  1198. m_has_pending_change_notification = true;
  1199. deferred_invoke([this](auto&) {
  1200. if (!m_has_pending_change_notification)
  1201. return;
  1202. if (on_change)
  1203. on_change();
  1204. m_has_pending_change_notification = false;
  1205. });
  1206. }
  1207. }
  1208. void GTextEditor::set_readonly(bool readonly)
  1209. {
  1210. if (m_readonly == readonly)
  1211. return;
  1212. m_readonly = readonly;
  1213. m_cut_action->set_enabled(!is_readonly() && has_selection());
  1214. m_delete_action->set_enabled(!is_readonly());
  1215. m_paste_action->set_enabled(!is_readonly());
  1216. }
  1217. void GTextEditor::did_update_selection()
  1218. {
  1219. m_cut_action->set_enabled(!is_readonly() && has_selection());
  1220. m_copy_action->set_enabled(has_selection());
  1221. if (on_selection_change)
  1222. on_selection_change();
  1223. if (is_line_wrapping_enabled()) {
  1224. // FIXME: Try to repaint less.
  1225. update();
  1226. }
  1227. }
  1228. void GTextEditor::context_menu_event(GContextMenuEvent& event)
  1229. {
  1230. if (!m_context_menu) {
  1231. m_context_menu = make<GMenu>();
  1232. m_context_menu->add_action(undo_action());
  1233. m_context_menu->add_action(redo_action());
  1234. m_context_menu->add_separator();
  1235. m_context_menu->add_action(cut_action());
  1236. m_context_menu->add_action(copy_action());
  1237. m_context_menu->add_action(paste_action());
  1238. m_context_menu->add_action(delete_action());
  1239. if (!m_custom_context_menu_actions.is_empty()) {
  1240. m_context_menu->add_separator();
  1241. for (auto& action : m_custom_context_menu_actions) {
  1242. m_context_menu->add_action(action);
  1243. }
  1244. }
  1245. }
  1246. m_context_menu->popup(event.screen_position());
  1247. }
  1248. void GTextEditor::set_text_alignment(TextAlignment alignment)
  1249. {
  1250. if (m_text_alignment == alignment)
  1251. return;
  1252. m_text_alignment = alignment;
  1253. update();
  1254. }
  1255. void GTextEditor::resize_event(GResizeEvent& event)
  1256. {
  1257. GScrollableWidget::resize_event(event);
  1258. update_content_size();
  1259. recompute_all_visual_lines();
  1260. }
  1261. void GTextEditor::set_selection(const GTextRange& selection)
  1262. {
  1263. if (m_selection == selection)
  1264. return;
  1265. m_selection = selection;
  1266. set_cursor(m_selection.end());
  1267. scroll_position_into_view(normalized_selection().start());
  1268. update();
  1269. }
  1270. void GTextEditor::recompute_all_visual_lines()
  1271. {
  1272. int y_offset = 0;
  1273. for (int line_index = 0; line_index < line_count(); ++line_index) {
  1274. recompute_visual_lines(line_index);
  1275. m_line_visual_data[line_index].visual_rect.set_y(y_offset);
  1276. y_offset += m_line_visual_data[line_index].visual_rect.height();
  1277. }
  1278. update_content_size();
  1279. }
  1280. void GTextEditor::ensure_cursor_is_valid()
  1281. {
  1282. if (cursor().column() > lines()[cursor().line()].length())
  1283. set_cursor(cursor().line(), cursor().column() - (lines()[cursor().line()].length() - cursor().column()));
  1284. }
  1285. void GTextEditor::add_to_undo_stack(NonnullOwnPtr<UndoCommand> undo_command)
  1286. {
  1287. if (m_undo_stack.is_empty()) {
  1288. auto undo_commands_container = make<UndoCommandsContainer>();
  1289. m_undo_stack.prepend(move(undo_commands_container));
  1290. }
  1291. // Clear the elements of the stack before the m_undo_stack_index (Excluding our new element)
  1292. for (int i = 1; i < m_undo_stack_index; i++)
  1293. m_undo_stack.remove(1);
  1294. if (m_undo_stack_index > 0 && !m_undo_stack.is_empty())
  1295. m_undo_stack[0].m_undo_vector.clear();
  1296. m_undo_stack_index = 0;
  1297. m_undo_stack[0].m_undo_vector.prepend(move(undo_command));
  1298. }
  1299. int GTextEditor::visual_line_containing(int line_index, int column) const
  1300. {
  1301. int visual_line_index = 0;
  1302. for_each_visual_line(line_index, [&](const Rect&, const StringView& view, int start_of_visual_line) {
  1303. if (column >= start_of_visual_line && ((column - start_of_visual_line) < view.length()))
  1304. return IterationDecision::Break;
  1305. ++visual_line_index;
  1306. return IterationDecision::Continue;
  1307. });
  1308. return visual_line_index;
  1309. }
  1310. void GTextEditor::recompute_visual_lines(int line_index)
  1311. {
  1312. auto& line = document().line(line_index);
  1313. auto& visual_data = m_line_visual_data[line_index];
  1314. visual_data.visual_line_breaks.clear_with_capacity();
  1315. int available_width = visible_text_rect_in_inner_coordinates().width();
  1316. if (is_line_wrapping_enabled()) {
  1317. int line_width_so_far = 0;
  1318. for (int i = 0; i < line.length(); ++i) {
  1319. auto ch = line.characters()[i];
  1320. auto glyph_width = font().glyph_width(ch);
  1321. if ((line_width_so_far + glyph_width) > available_width) {
  1322. visual_data.visual_line_breaks.append(i);
  1323. line_width_so_far = glyph_width;
  1324. continue;
  1325. }
  1326. line_width_so_far += glyph_width;
  1327. }
  1328. }
  1329. visual_data.visual_line_breaks.append(line.length());
  1330. if (is_line_wrapping_enabled())
  1331. visual_data.visual_rect = { m_horizontal_content_padding, 0, available_width, visual_data.visual_line_breaks.size() * line_height() };
  1332. else
  1333. visual_data.visual_rect = { m_horizontal_content_padding, 0, font().width(line.view()), line_height() };
  1334. }
  1335. template<typename Callback>
  1336. void GTextEditor::for_each_visual_line(int line_index, Callback callback) const
  1337. {
  1338. auto editor_visible_text_rect = visible_text_rect_in_inner_coordinates();
  1339. int start_of_line = 0;
  1340. int visual_line_index = 0;
  1341. auto& line = document().line(line_index);
  1342. auto& visual_data = m_line_visual_data[line_index];
  1343. for (auto visual_line_break : visual_data.visual_line_breaks) {
  1344. auto visual_line_view = StringView(line.characters() + start_of_line, visual_line_break - start_of_line);
  1345. Rect visual_line_rect {
  1346. visual_data.visual_rect.x(),
  1347. visual_data.visual_rect.y() + (visual_line_index * line_height()),
  1348. font().width(visual_line_view),
  1349. line_height()
  1350. };
  1351. if (is_right_text_alignment(text_alignment()))
  1352. visual_line_rect.set_right_without_resize(editor_visible_text_rect.right());
  1353. if (!is_multi_line())
  1354. visual_line_rect.center_vertically_within(editor_visible_text_rect);
  1355. if (callback(visual_line_rect, visual_line_view, start_of_line) == IterationDecision::Break)
  1356. break;
  1357. start_of_line = visual_line_break;
  1358. ++visual_line_index;
  1359. }
  1360. }
  1361. void GTextEditor::set_line_wrapping_enabled(bool enabled)
  1362. {
  1363. if (m_line_wrapping_enabled == enabled)
  1364. return;
  1365. m_line_wrapping_enabled = enabled;
  1366. horizontal_scrollbar().set_visible(!m_line_wrapping_enabled);
  1367. update_content_size();
  1368. recompute_all_visual_lines();
  1369. update();
  1370. }
  1371. void GTextEditor::add_custom_context_menu_action(GAction& action)
  1372. {
  1373. m_custom_context_menu_actions.append(action);
  1374. }
  1375. void GTextEditor::did_change_font()
  1376. {
  1377. vertical_scrollbar().set_step(line_height());
  1378. GWidget::did_change_font();
  1379. }
  1380. void GTextEditor::document_did_append_line()
  1381. {
  1382. m_line_visual_data.append(make<LineVisualData>());
  1383. recompute_all_visual_lines();
  1384. update();
  1385. }
  1386. void GTextEditor::document_did_remove_line(int line_index)
  1387. {
  1388. m_line_visual_data.remove(line_index);
  1389. recompute_all_visual_lines();
  1390. update();
  1391. }
  1392. void GTextEditor::document_did_remove_all_lines()
  1393. {
  1394. m_line_visual_data.clear();
  1395. recompute_all_visual_lines();
  1396. update();
  1397. }
  1398. void GTextEditor::document_did_insert_line(int line_index)
  1399. {
  1400. m_line_visual_data.insert(line_index, make<LineVisualData>());
  1401. recompute_all_visual_lines();
  1402. update();
  1403. }
  1404. void GTextEditor::document_did_change()
  1405. {
  1406. recompute_all_visual_lines();
  1407. update();
  1408. }
  1409. void GTextEditor::set_document(GTextDocument& document)
  1410. {
  1411. if (m_document.ptr() == &document)
  1412. return;
  1413. if (m_document)
  1414. m_document->unregister_client(*this);
  1415. m_document = document;
  1416. m_line_visual_data.clear();
  1417. for (int i = 0; i < m_document->line_count(); ++i) {
  1418. m_line_visual_data.append(make<LineVisualData>());
  1419. }
  1420. m_cursor = { 0, 0 };
  1421. recompute_all_visual_lines();
  1422. update();
  1423. m_document->register_client(*this);
  1424. }
  1425. GTextEditor::UndoCommand::UndoCommand(GTextEditor& text_editor)
  1426. : m_text_editor(text_editor)
  1427. {
  1428. }
  1429. GTextEditor::UndoCommand::~UndoCommand()
  1430. {
  1431. }
  1432. void GTextEditor::UndoCommand::undo() {}
  1433. void GTextEditor::UndoCommand::redo() {}
  1434. GTextEditor::InsertCharacterCommand::InsertCharacterCommand(GTextEditor& text_editor, char ch, GTextPosition text_position)
  1435. : UndoCommand(text_editor)
  1436. , m_character(ch)
  1437. , m_text_position(text_position)
  1438. {
  1439. }
  1440. GTextEditor::RemoveCharacterCommand::RemoveCharacterCommand(GTextEditor& text_editor, char ch, GTextPosition text_position)
  1441. : UndoCommand(text_editor)
  1442. , m_character(ch)
  1443. , m_text_position(text_position)
  1444. {
  1445. }
  1446. GTextEditor::RemoveLineCommand::RemoveLineCommand(GTextEditor& text_editor, String line_content, GTextPosition text_position, bool has_merged_content)
  1447. : UndoCommand(text_editor)
  1448. , m_line_content(line_content)
  1449. , m_text_position(text_position)
  1450. , m_has_merged_content(has_merged_content)
  1451. {
  1452. }
  1453. GTextEditor::CreateLineCommand::CreateLineCommand(GTextEditor& text_editor, Vector<char> line_content, GTextPosition text_position)
  1454. : UndoCommand(text_editor)
  1455. , m_line_content(line_content)
  1456. , m_text_position(text_position)
  1457. {
  1458. }
  1459. void GTextEditor::InsertCharacterCommand::undo()
  1460. {
  1461. m_text_editor.lines()[m_text_position.line()].remove(m_text_editor.document(), (m_text_position.column() - 1));
  1462. m_text_editor.ensure_cursor_is_valid();
  1463. }
  1464. void GTextEditor::InsertCharacterCommand::redo()
  1465. {
  1466. m_text_editor.lines()[m_text_position.line()].insert(m_text_editor.document(), m_text_position.column() - 1, m_character);
  1467. }
  1468. void GTextEditor::RemoveCharacterCommand::undo()
  1469. {
  1470. m_text_editor.lines()[m_text_position.line()].insert(m_text_editor.document(), m_text_position.column(), m_character);
  1471. }
  1472. void GTextEditor::RemoveCharacterCommand::redo()
  1473. {
  1474. m_text_editor.lines()[m_text_position.line()].remove(m_text_editor.document(), (m_text_position.column()));
  1475. m_text_editor.ensure_cursor_is_valid();
  1476. }
  1477. void GTextEditor::RemoveLineCommand::undo()
  1478. {
  1479. // Insert back the line
  1480. m_text_editor.document().insert_line(m_text_position.line(), make<GTextDocumentLine>(m_text_editor.document(), m_line_content));
  1481. // Remove the merged line contents
  1482. if (m_has_merged_content) {
  1483. for (int i = m_line_content.length() - 1; i >= 0; i--)
  1484. m_text_editor.document().lines()[m_text_position.line() - 1].remove(m_text_editor.document(), (m_text_position.column()) + i);
  1485. }
  1486. }
  1487. void GTextEditor::RemoveLineCommand::redo()
  1488. {
  1489. // Remove the created line
  1490. m_text_editor.document().remove_line(m_text_position.line());
  1491. // Add back the line contents
  1492. if (m_has_merged_content) {
  1493. for (int i = 0; i < m_line_content.length(); i++)
  1494. m_text_editor.document().lines()[m_text_position.line() - 1].insert(m_text_editor.document(), (m_text_position.column()) + i, m_line_content[i]);
  1495. }
  1496. }
  1497. void GTextEditor::CreateLineCommand::undo()
  1498. {
  1499. // Insert back the created line portion
  1500. for (int i = 0; i < m_line_content.size(); i++)
  1501. m_text_editor.document().lines()[m_text_position.line()].insert(m_text_editor.document(), (m_text_position.column() - 1) + i, m_line_content[i]);
  1502. // Move the cursor up a row back before the split.
  1503. m_text_editor.set_cursor(m_text_position.line(), m_text_editor.document().lines()[m_text_position.line()].length());
  1504. // Remove the created line
  1505. m_text_editor.document().remove_line(m_text_position.line() + 1);
  1506. }
  1507. void GTextEditor::CreateLineCommand::redo()
  1508. {
  1509. // Remove the characters that we're inserted back
  1510. for (int i = m_line_content.size() - 1; i >= 0; i--)
  1511. m_text_editor.document().lines()[m_text_position.line()].remove(m_text_editor.document(), (m_text_position.column()) + i);
  1512. m_text_editor.ensure_cursor_is_valid();
  1513. // Then we want to add BACK the created line
  1514. m_text_editor.document().insert_line(m_text_position.line() + 1, make<GTextDocumentLine>(m_text_editor.document(), ""));
  1515. for (int i = 0; i < m_line_content.size(); i++)
  1516. m_text_editor.document().lines()[m_text_position.line() + 1].insert(m_text_editor.document(), i, m_line_content[i]);
  1517. }
  1518. void GTextEditor::flush_pending_change_notification_if_needed()
  1519. {
  1520. if (!m_has_pending_change_notification)
  1521. return;
  1522. if (on_change)
  1523. on_change();
  1524. m_has_pending_change_notification = false;
  1525. }