GTextEditor.cpp 49 KB

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