GTextEditor.cpp 48 KB

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