GTextEditor.cpp 49 KB

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