GTextEditor.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960
  1. #include <LibGUI/GTextEditor.h>
  2. #include <LibGUI/GScrollBar.h>
  3. #include <LibGUI/GFontDatabase.h>
  4. #include <LibGUI/GClipboard.h>
  5. #include <LibGUI/GPainter.h>
  6. #include <LibGUI/GWindow.h>
  7. #include <LibGUI/GMenu.h>
  8. #include <LibGUI/GAction.h>
  9. #include <Kernel/KeyCode.h>
  10. #include <AK/StringBuilder.h>
  11. #include <unistd.h>
  12. #include <fcntl.h>
  13. #include <stdio.h>
  14. GTextEditor::GTextEditor(Type type, GWidget* parent)
  15. : GScrollableWidget(parent)
  16. , m_type(type)
  17. {
  18. set_frame_shape(FrameShape::Container);
  19. set_frame_shadow(FrameShadow::Sunken);
  20. set_frame_thickness(2);
  21. set_scrollbars_enabled(is_multi_line());
  22. set_font(GFontDatabase::the().get_by_name("Csilla Thin"));
  23. m_lines.append(make<Line>());
  24. m_cursor = { 0, 0 };
  25. create_actions();
  26. }
  27. GTextEditor::~GTextEditor()
  28. {
  29. }
  30. void GTextEditor::create_actions()
  31. {
  32. m_undo_action = GAction::create("Undo", { Mod_Ctrl, Key_Z }, GraphicsBitmap::load_from_file("/res/icons/16x16/undo.png"), [&] (const GAction&) {
  33. // FIXME: Undo
  34. }, this);
  35. m_redo_action = GAction::create("Redo", { Mod_Ctrl, Key_Y }, GraphicsBitmap::load_from_file("/res/icons/16x16/redo.png"), [&] (const GAction&) {
  36. // FIXME: Redo
  37. }, this);
  38. m_cut_action = GAction::create("Cut", { Mod_Ctrl, Key_X }, GraphicsBitmap::load_from_file("/res/icons/cut16.png"), [&] (const GAction&) {
  39. cut();
  40. }, this);
  41. m_copy_action = GAction::create("Copy", { Mod_Ctrl, Key_C }, GraphicsBitmap::load_from_file("/res/icons/16x16/edit-copy.png"), [&] (const GAction&) {
  42. copy();
  43. }, this);
  44. m_paste_action = GAction::create("Paste", { Mod_Ctrl, Key_V }, GraphicsBitmap::load_from_file("/res/icons/paste16.png"), [&] (const GAction&) {
  45. paste();
  46. }, this);
  47. m_delete_action = GAction::create("Delete", { 0, Key_Delete }, GraphicsBitmap::load_from_file("/res/icons/16x16/delete.png"), [&] (const GAction&) {
  48. do_delete();
  49. }, this);
  50. }
  51. void GTextEditor::set_text(const String& text)
  52. {
  53. if (is_single_line() && text.length() == m_lines[0]->length() && !memcmp(text.characters(), m_lines[0]->characters(), text.length()))
  54. return;
  55. m_selection.clear();
  56. m_lines.clear();
  57. int start_of_current_line = 0;
  58. auto add_line = [&] (int current_position) {
  59. int line_length = current_position - start_of_current_line;
  60. auto line = make<Line>();
  61. if (line_length)
  62. line->set_text(text.substring(start_of_current_line, current_position - start_of_current_line));
  63. m_lines.append(move(line));
  64. start_of_current_line = current_position + 1;
  65. };
  66. int i = 0;
  67. for (i = 0; i < text.length(); ++i) {
  68. if (text[i] == '\n')
  69. add_line(i);
  70. }
  71. add_line(i);
  72. update_content_size();
  73. if (is_single_line())
  74. set_cursor(0, m_lines[0]->length());
  75. else
  76. set_cursor(0, 0);
  77. did_update_selection();
  78. update();
  79. }
  80. void GTextEditor::update_content_size()
  81. {
  82. int content_width = 0;
  83. for (auto& line : m_lines)
  84. content_width = max(line->width(font()), content_width);
  85. content_width += m_horizontal_content_padding * 2;
  86. if (is_right_text_alignment(m_text_alignment))
  87. content_width = max(frame_inner_rect().width(), content_width);
  88. int content_height = line_count() * line_height();
  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. int line_index = position.y() / line_height();
  98. line_index = max(0, min(line_index, line_count() - 1));
  99. auto& line = *m_lines[line_index];
  100. int column_index;
  101. switch (m_text_alignment) {
  102. case TextAlignment::CenterLeft:
  103. column_index = position.x() / glyph_width();
  104. break;
  105. case TextAlignment::CenterRight:
  106. column_index = (position.x() - (content_width() - (line.length() * glyph_width()))) / glyph_width();
  107. break;
  108. default:
  109. ASSERT_NOT_REACHED();
  110. }
  111. column_index = max(0, min(column_index, m_lines[line_index]->length()));
  112. return { line_index, column_index };
  113. }
  114. void GTextEditor::mousedown_event(GMouseEvent& event)
  115. {
  116. if (event.button() == GMouseButton::Left) {
  117. if (event.modifiers() & Mod_Shift) {
  118. if (!has_selection())
  119. m_selection.set(m_cursor, { });
  120. } else {
  121. m_selection.clear();
  122. }
  123. m_in_drag_select = true;
  124. set_cursor(text_position_at(event.position()));
  125. if (!(event.modifiers() & Mod_Shift)) {
  126. if (!has_selection())
  127. m_selection.set(m_cursor, { });
  128. }
  129. if (m_selection.start().is_valid() && m_selection.start() != m_cursor)
  130. m_selection.set_end(m_cursor);
  131. // FIXME: Only update the relevant rects.
  132. update();
  133. did_update_selection();
  134. return;
  135. }
  136. }
  137. void GTextEditor::mouseup_event(GMouseEvent& event)
  138. {
  139. if (event.button() == GMouseButton::Left) {
  140. if (m_in_drag_select) {
  141. m_in_drag_select = false;
  142. }
  143. return;
  144. }
  145. }
  146. void GTextEditor::mousemove_event(GMouseEvent& event)
  147. {
  148. if (m_in_drag_select) {
  149. set_cursor(text_position_at(event.position()));
  150. m_selection.set_end(m_cursor);
  151. did_update_selection();
  152. update();
  153. return;
  154. }
  155. }
  156. int GTextEditor::ruler_width() const
  157. {
  158. if (!m_ruler_visible)
  159. return 0;
  160. // FIXME: Resize based on needed space.
  161. return 5 * font().glyph_width('x') + 4;
  162. }
  163. Rect GTextEditor::ruler_content_rect(int line_index) const
  164. {
  165. if (!m_ruler_visible)
  166. return { };
  167. return {
  168. 0 - ruler_width() + horizontal_scrollbar().value(),
  169. line_index * line_height(),
  170. ruler_width(),
  171. line_height()
  172. };
  173. }
  174. void GTextEditor::paint_event(GPaintEvent& event)
  175. {
  176. GFrame::paint_event(event);
  177. GPainter painter(*this);
  178. painter.add_clip_rect(widget_inner_rect());
  179. painter.add_clip_rect(event.rect());
  180. painter.fill_rect(event.rect(), Color::White);
  181. Rect ruler_rect { 0, 0, ruler_width(), height() - height_occupied_by_horizontal_scrollbar()};
  182. if (m_ruler_visible) {
  183. painter.fill_rect(ruler_rect, Color::LightGray);
  184. painter.draw_line(ruler_rect.top_right(), ruler_rect.bottom_right(), Color::DarkGray);
  185. }
  186. painter.translate(-horizontal_scrollbar().value(), -vertical_scrollbar().value());
  187. if (m_ruler_visible)
  188. painter.translate(ruler_width(), 0);
  189. int exposed_width = max(content_width(), frame_inner_rect().width());
  190. int first_visible_line = text_position_at(event.rect().top_left()).line();
  191. int last_visible_line = text_position_at(event.rect().bottom_right()).line();
  192. auto selection = normalized_selection();
  193. bool has_selection = selection.is_valid();
  194. if (m_ruler_visible) {
  195. for (int i = first_visible_line; i <= last_visible_line; ++i) {
  196. bool is_current_line = i == m_cursor.line();
  197. auto ruler_line_rect = ruler_content_rect(i);
  198. painter.draw_text(
  199. ruler_line_rect.shrunken(2, 0),
  200. String::format("%u", i),
  201. is_current_line ? Font::default_bold_font() : font(),
  202. TextAlignment::CenterRight,
  203. is_current_line ? Color::DarkGray : Color::MidGray
  204. );
  205. }
  206. }
  207. painter.add_clip_rect({ m_ruler_visible ? (ruler_rect.right() + 1) : 0, 0, width() - width_occupied_by_vertical_scrollbar() - ruler_width(), height() - height_occupied_by_horizontal_scrollbar() });
  208. for (int i = first_visible_line; i <= last_visible_line; ++i) {
  209. auto& line = *m_lines[i];
  210. auto line_rect = line_content_rect(i);
  211. // FIXME: Make sure we always fill the entire line.
  212. //line_rect.set_width(exposed_width);
  213. if (is_multi_line() && i == m_cursor.line())
  214. painter.fill_rect(line_rect, Color(230, 230, 230));
  215. painter.draw_text(line_rect, line.characters(), line.length(), m_text_alignment, Color::Black);
  216. bool line_has_selection = has_selection && i >= selection.start().line() && i <= selection.end().line();
  217. if (line_has_selection) {
  218. int selection_start_column_on_line = selection.start().line() == i ? selection.start().column() : 0;
  219. int selection_end_column_on_line = selection.end().line() == i ? selection.end().column() : line.length();
  220. int selection_left = content_x_for_position({ i, selection_start_column_on_line });
  221. int selection_right = content_x_for_position({ i, selection_end_column_on_line });;
  222. Rect selection_rect { selection_left, line_rect.y(), selection_right - selection_left, line_rect.height() };
  223. painter.fill_rect(selection_rect, Color::from_rgb(0x955233));
  224. painter.draw_text(selection_rect, line.characters() + selection_start_column_on_line, line.length() - selection_start_column_on_line - (line.length() - selection_end_column_on_line), TextAlignment::CenterLeft, Color::White);
  225. }
  226. }
  227. if (is_focused() && m_cursor_state)
  228. painter.fill_rect(cursor_content_rect(), Color::Red);
  229. }
  230. void GTextEditor::toggle_selection_if_needed_for_event(const GKeyEvent& event)
  231. {
  232. if (event.shift() && !m_selection.is_valid()) {
  233. m_selection.set(m_cursor, { });
  234. did_update_selection();
  235. update();
  236. return;
  237. }
  238. if (!event.shift() && m_selection.is_valid()) {
  239. m_selection.clear();
  240. did_update_selection();
  241. update();
  242. return;
  243. }
  244. }
  245. void GTextEditor::keydown_event(GKeyEvent& event)
  246. {
  247. if (event.key() == KeyCode::Key_Escape) {
  248. if (on_escape_pressed)
  249. on_escape_pressed();
  250. return;
  251. }
  252. if (event.key() == KeyCode::Key_Up) {
  253. if (m_cursor.line() > 0) {
  254. int new_line = m_cursor.line() - 1;
  255. int new_column = min(m_cursor.column(), m_lines[new_line]->length());
  256. toggle_selection_if_needed_for_event(event);
  257. set_cursor(new_line, new_column);
  258. if (m_selection.start().is_valid()) {
  259. m_selection.set_end(m_cursor);
  260. did_update_selection();
  261. }
  262. }
  263. return;
  264. }
  265. if (event.key() == KeyCode::Key_Down) {
  266. if (m_cursor.line() < (m_lines.size() - 1)) {
  267. int new_line = m_cursor.line() + 1;
  268. int new_column = min(m_cursor.column(), m_lines[new_line]->length());
  269. toggle_selection_if_needed_for_event(event);
  270. set_cursor(new_line, new_column);
  271. if (m_selection.start().is_valid()) {
  272. m_selection.set_end(m_cursor);
  273. did_update_selection();
  274. }
  275. }
  276. return;
  277. }
  278. if (event.key() == KeyCode::Key_PageUp) {
  279. if (m_cursor.line() > 0) {
  280. int new_line = max(0, m_cursor.line() - visible_content_rect().height() / line_height());
  281. int new_column = min(m_cursor.column(), m_lines[new_line]->length());
  282. toggle_selection_if_needed_for_event(event);
  283. set_cursor(new_line, new_column);
  284. if (m_selection.start().is_valid()) {
  285. m_selection.set_end(m_cursor);
  286. did_update_selection();
  287. }
  288. }
  289. return;
  290. }
  291. if (event.key() == KeyCode::Key_PageDown) {
  292. if (m_cursor.line() < (m_lines.size() - 1)) {
  293. int new_line = min(line_count() - 1, m_cursor.line() + visible_content_rect().height() / line_height());
  294. int new_column = min(m_cursor.column(), m_lines[new_line]->length());
  295. toggle_selection_if_needed_for_event(event);
  296. set_cursor(new_line, new_column);
  297. if (m_selection.start().is_valid()) {
  298. m_selection.set_end(m_cursor);
  299. did_update_selection();
  300. }
  301. }
  302. return;
  303. }
  304. if (event.key() == KeyCode::Key_Left) {
  305. if (m_cursor.column() > 0) {
  306. int new_column = m_cursor.column() - 1;
  307. toggle_selection_if_needed_for_event(event);
  308. set_cursor(m_cursor.line(), new_column);
  309. if (m_selection.start().is_valid()) {
  310. m_selection.set_end(m_cursor);
  311. did_update_selection();
  312. }
  313. } else if (m_cursor.line() > 0) {
  314. int new_line = m_cursor.line() - 1;
  315. int new_column = m_lines[new_line]->length();
  316. toggle_selection_if_needed_for_event(event);
  317. set_cursor(new_line, new_column);
  318. if (m_selection.start().is_valid()) {
  319. m_selection.set_end(m_cursor);
  320. did_update_selection();
  321. }
  322. }
  323. return;
  324. }
  325. if (event.key() == KeyCode::Key_Right) {
  326. if (m_cursor.column() < current_line().length()) {
  327. int new_column = m_cursor.column() + 1;
  328. toggle_selection_if_needed_for_event(event);
  329. set_cursor(m_cursor.line(), new_column);
  330. if (m_selection.start().is_valid()) {
  331. m_selection.set_end(m_cursor);
  332. did_update_selection();
  333. }
  334. } else if (m_cursor.line() != line_count() - 1) {
  335. int new_line = m_cursor.line() + 1;
  336. int new_column = 0;
  337. toggle_selection_if_needed_for_event(event);
  338. set_cursor(new_line, new_column);
  339. if (m_selection.start().is_valid()) {
  340. m_selection.set_end(m_cursor);
  341. did_update_selection();
  342. }
  343. }
  344. return;
  345. }
  346. if (!event.ctrl() && event.key() == KeyCode::Key_Home) {
  347. toggle_selection_if_needed_for_event(event);
  348. set_cursor(m_cursor.line(), 0);
  349. if (m_selection.start().is_valid()) {
  350. m_selection.set_end(m_cursor);
  351. did_update_selection();
  352. }
  353. return;
  354. }
  355. if (!event.ctrl() && event.key() == KeyCode::Key_End) {
  356. toggle_selection_if_needed_for_event(event);
  357. set_cursor(m_cursor.line(), current_line().length());
  358. if (m_selection.start().is_valid()) {
  359. m_selection.set_end(m_cursor);
  360. did_update_selection();
  361. }
  362. return;
  363. }
  364. if (event.ctrl() && event.key() == KeyCode::Key_Home) {
  365. toggle_selection_if_needed_for_event(event);
  366. set_cursor(0, 0);
  367. if (m_selection.start().is_valid()) {
  368. m_selection.set_end(m_cursor);
  369. did_update_selection();
  370. }
  371. return;
  372. }
  373. if (event.ctrl() && event.key() == KeyCode::Key_End) {
  374. toggle_selection_if_needed_for_event(event);
  375. set_cursor(line_count() - 1, m_lines[line_count() - 1]->length());
  376. if (m_selection.start().is_valid()) {
  377. m_selection.set_end(m_cursor);
  378. did_update_selection();
  379. }
  380. return;
  381. }
  382. if (event.modifiers() == Mod_Ctrl && event.key() == KeyCode::Key_A) {
  383. GTextPosition start_of_document { 0, 0 };
  384. GTextPosition end_of_document { line_count() - 1, m_lines[line_count() - 1]->length() };
  385. m_selection.set(start_of_document, end_of_document);
  386. did_update_selection();
  387. set_cursor(end_of_document);
  388. update();
  389. return;
  390. }
  391. if (event.key() == KeyCode::Key_Backspace) {
  392. if (has_selection()) {
  393. delete_selection();
  394. did_update_selection();
  395. return;
  396. }
  397. if (m_cursor.column() > 0) {
  398. // Backspace within line
  399. current_line().remove(m_cursor.column() - 1);
  400. update_content_size();
  401. set_cursor(m_cursor.line(), m_cursor.column() - 1);
  402. return;
  403. }
  404. if (m_cursor.column() == 0 && m_cursor.line() != 0) {
  405. // Backspace at column 0; merge with previous line
  406. auto& previous_line = *m_lines[m_cursor.line() - 1];
  407. int previous_length = previous_line.length();
  408. previous_line.append(current_line().characters(), current_line().length());
  409. m_lines.remove(m_cursor.line());
  410. update_content_size();
  411. update();
  412. set_cursor(m_cursor.line() - 1, previous_length);
  413. return;
  414. }
  415. return;
  416. }
  417. if (event.modifiers() == Mod_Shift && event.key() == KeyCode::Key_Delete) {
  418. delete_current_line();
  419. return;
  420. }
  421. if (event.key() == KeyCode::Key_Delete) {
  422. do_delete();
  423. return;
  424. }
  425. if (!event.ctrl() && !event.alt() && !event.text().is_empty())
  426. insert_at_cursor_or_replace_selection(event.text());
  427. return GWidget::keydown_event(event);
  428. }
  429. void GTextEditor::delete_current_line()
  430. {
  431. if (has_selection())
  432. return delete_selection();
  433. m_lines.remove(m_cursor.line());
  434. if (m_lines.is_empty())
  435. m_lines.append(make<Line>());
  436. update_content_size();
  437. update();
  438. }
  439. void GTextEditor::do_delete()
  440. {
  441. if (has_selection())
  442. return delete_selection();
  443. if (m_cursor.column() < current_line().length()) {
  444. // Delete within line
  445. current_line().remove(m_cursor.column());
  446. update_cursor();
  447. did_change();
  448. return;
  449. }
  450. if (m_cursor.column() == current_line().length() && m_cursor.line() != line_count() - 1) {
  451. // Delete at end of line; merge with next line
  452. auto& next_line = *m_lines[m_cursor.line() + 1];
  453. int previous_length = current_line().length();
  454. current_line().append(next_line.characters(), next_line.length());
  455. m_lines.remove(m_cursor.line() + 1);
  456. update();
  457. set_cursor(m_cursor.line(), previous_length);
  458. did_change();
  459. return;
  460. }
  461. }
  462. void GTextEditor::insert_at_cursor(const String& text)
  463. {
  464. // FIXME: This should obviously not be implemented this way.
  465. for (int i = 0; i < text.length(); ++i) {
  466. insert_at_cursor(text[i]);
  467. }
  468. }
  469. void GTextEditor::insert_at_cursor(char ch)
  470. {
  471. bool at_head = m_cursor.column() == 0;
  472. bool at_tail = m_cursor.column() == current_line().length();
  473. if (ch == '\n') {
  474. if (is_single_line()) {
  475. if (on_return_pressed)
  476. on_return_pressed();
  477. return;
  478. }
  479. if (at_tail || at_head) {
  480. m_lines.insert(m_cursor.line() + (at_tail ? 1 : 0), make<Line>());
  481. update();
  482. set_cursor(m_cursor.line() + 1, 0);
  483. did_change();
  484. return;
  485. }
  486. auto new_line = make<Line>();
  487. new_line->append(current_line().characters() + m_cursor.column(), current_line().length() - m_cursor.column());
  488. current_line().truncate(m_cursor.column());
  489. m_lines.insert(m_cursor.line() + 1, move(new_line));
  490. update();
  491. set_cursor(m_cursor.line() + 1, 0);
  492. did_change();
  493. return;
  494. }
  495. if (ch == '\t') {
  496. int next_soft_tab_stop = ((m_cursor.column() + m_soft_tab_width) / m_soft_tab_width) * m_soft_tab_width;
  497. int spaces_to_insert = next_soft_tab_stop - m_cursor.column();
  498. for (int i = 0; i < spaces_to_insert; ++i) {
  499. current_line().insert(m_cursor.column(), ' ');
  500. }
  501. set_cursor(m_cursor.line(), next_soft_tab_stop);
  502. update_cursor();
  503. did_change();
  504. return;
  505. }
  506. current_line().insert(m_cursor.column(), ch);
  507. set_cursor(m_cursor.line(), m_cursor.column() + 1);
  508. update_cursor();
  509. did_change();
  510. }
  511. int GTextEditor::content_x_for_position(const GTextPosition& position) const
  512. {
  513. auto& line = *m_lines[position.line()];
  514. switch (m_text_alignment) {
  515. case TextAlignment::CenterLeft:
  516. return m_horizontal_content_padding + position.column() * glyph_width();
  517. case TextAlignment::CenterRight:
  518. return content_width() - m_horizontal_content_padding - (line.length() * glyph_width()) + (position.column() * glyph_width());
  519. default:
  520. ASSERT_NOT_REACHED();
  521. }
  522. }
  523. Rect GTextEditor::cursor_content_rect() const
  524. {
  525. if (!m_cursor.is_valid())
  526. return { };
  527. ASSERT(!m_lines.is_empty());
  528. ASSERT(m_cursor.column() <= (current_line().length() + 1));
  529. int cursor_x = content_x_for_position(m_cursor);
  530. if (is_single_line()) {
  531. Rect cursor_rect { cursor_x, 0, 1, font().glyph_height() + 2 };
  532. cursor_rect.center_vertically_within(rect());
  533. // FIXME: This would not be necessary if we knew more about the font and could center it based on baseline and x-height.
  534. cursor_rect.move_by(0, 1);
  535. return cursor_rect;
  536. }
  537. return { cursor_x, m_cursor.line() * line_height(), 1, line_height() };
  538. }
  539. Rect GTextEditor::line_widget_rect(int line_index) const
  540. {
  541. auto rect = line_content_rect(line_index);
  542. rect.set_x(frame_thickness());
  543. rect.set_width(frame_inner_rect().width());
  544. rect.move_by(0, -(vertical_scrollbar().value()));
  545. rect.intersect(this->rect());
  546. return rect;
  547. }
  548. void GTextEditor::scroll_cursor_into_view()
  549. {
  550. scroll_into_view(cursor_content_rect(), true, true);
  551. }
  552. Rect GTextEditor::line_content_rect(int line_index) const
  553. {
  554. auto& line = *m_lines[line_index];
  555. if (is_single_line()) {
  556. Rect line_rect = { content_x_for_position({ line_index, 0 }), 0, line.length() * glyph_width(), font().glyph_height() + 2 };
  557. line_rect.center_vertically_within(rect());
  558. // FIXME: This would not be necessary if we knew more about the font and could center it based on baseline and x-height.
  559. line_rect.move_by(0, 1);
  560. return line_rect;
  561. }
  562. return {
  563. content_x_for_position({ line_index, 0 }),
  564. line_index * line_height(),
  565. line.length() * glyph_width(),
  566. line_height()
  567. };
  568. }
  569. void GTextEditor::update_cursor()
  570. {
  571. update(line_widget_rect(m_cursor.line()));
  572. }
  573. void GTextEditor::set_cursor(int line, int column)
  574. {
  575. set_cursor({ line, column });
  576. }
  577. void GTextEditor::set_cursor(const GTextPosition& position)
  578. {
  579. ASSERT(!m_lines.is_empty());
  580. ASSERT(position.line() < m_lines.size());
  581. ASSERT(position.column() <= m_lines[position.line()]->length());
  582. if (m_cursor != position) {
  583. auto old_cursor_line_rect = line_widget_rect(m_cursor.line());
  584. m_cursor = position;
  585. m_cursor_state = true;
  586. scroll_cursor_into_view();
  587. update(old_cursor_line_rect);
  588. update_cursor();
  589. }
  590. if (on_cursor_change)
  591. on_cursor_change();
  592. }
  593. void GTextEditor::focusin_event(CEvent&)
  594. {
  595. update_cursor();
  596. start_timer(500);
  597. }
  598. void GTextEditor::focusout_event(CEvent&)
  599. {
  600. stop_timer();
  601. }
  602. void GTextEditor::timer_event(CTimerEvent&)
  603. {
  604. m_cursor_state = !m_cursor_state;
  605. if (is_focused())
  606. update_cursor();
  607. }
  608. GTextEditor::Line::Line()
  609. {
  610. clear();
  611. }
  612. void GTextEditor::Line::clear()
  613. {
  614. m_text.clear();
  615. m_text.append(0);
  616. }
  617. void GTextEditor::Line::set_text(const String& text)
  618. {
  619. if (text.length() == length() && !memcmp(text.characters(), characters(), length()))
  620. return;
  621. if (text.is_empty()) {
  622. clear();
  623. return;
  624. }
  625. m_text.resize(text.length() + 1);
  626. memcpy(m_text.data(), text.characters(), text.length() + 1);
  627. }
  628. int GTextEditor::Line::width(const Font& font) const
  629. {
  630. return font.glyph_width('x') * length();
  631. }
  632. void GTextEditor::Line::append(const char* characters, int length)
  633. {
  634. int old_length = m_text.size() - 1;
  635. m_text.resize(m_text.size() + length);
  636. memcpy(m_text.data() + old_length, characters, length);
  637. m_text.last() = 0;
  638. }
  639. void GTextEditor::Line::append(char ch)
  640. {
  641. insert(length(), ch);
  642. }
  643. void GTextEditor::Line::prepend(char ch)
  644. {
  645. insert(0, ch);
  646. }
  647. void GTextEditor::Line::insert(int index, char ch)
  648. {
  649. if (index == length()) {
  650. m_text.last() = ch;
  651. m_text.append(0);
  652. } else {
  653. m_text.insert(index, move(ch));
  654. }
  655. }
  656. void GTextEditor::Line::remove(int index)
  657. {
  658. if (index == length()) {
  659. m_text.take_last();
  660. m_text.last() = 0;
  661. } else {
  662. m_text.remove(index);
  663. }
  664. }
  665. void GTextEditor::Line::truncate(int length)
  666. {
  667. m_text.resize(length + 1);
  668. m_text.last() = 0;
  669. }
  670. bool GTextEditor::write_to_file(const String& path)
  671. {
  672. int fd = open(path.characters(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
  673. if (fd < 0) {
  674. perror("open");
  675. return false;
  676. }
  677. for (int i = 0; i < m_lines.size(); ++i) {
  678. auto& line = *m_lines[i];
  679. if (line.length()) {
  680. ssize_t nwritten = write(fd, line.characters(), line.length());
  681. if (nwritten < 0) {
  682. perror("write");
  683. close(fd);
  684. return false;
  685. }
  686. }
  687. if (i != m_lines.size() - 1) {
  688. char ch = '\n';
  689. ssize_t nwritten = write(fd, &ch, 1);
  690. if (nwritten != 1) {
  691. perror("write");
  692. close(fd);
  693. return false;
  694. }
  695. }
  696. }
  697. close(fd);
  698. return true;
  699. }
  700. String GTextEditor::text() const
  701. {
  702. StringBuilder builder;
  703. for (int i = 0; i < line_count(); ++i) {
  704. auto& line = *m_lines[i];
  705. builder.append(line.characters(), line.length());
  706. if (i != line_count() - 1)
  707. builder.append('\n');
  708. }
  709. return builder.to_string();
  710. }
  711. void GTextEditor::clear()
  712. {
  713. m_lines.clear();
  714. m_lines.append(make<Line>());
  715. m_selection.clear();
  716. did_update_selection();
  717. set_cursor(0, 0);
  718. update();
  719. }
  720. String GTextEditor::selected_text() const
  721. {
  722. if (!has_selection())
  723. return { };
  724. auto selection = normalized_selection();
  725. StringBuilder builder;
  726. for (int i = selection.start().line(); i <= selection.end().line(); ++i) {
  727. auto& line = *m_lines[i];
  728. int selection_start_column_on_line = selection.start().line() == i ? selection.start().column() : 0;
  729. int selection_end_column_on_line = selection.end().line() == i ? selection.end().column() : line.length();
  730. builder.append(line.characters() + selection_start_column_on_line, selection_end_column_on_line - selection_start_column_on_line);
  731. if (i != selection.end().line())
  732. builder.append('\n');
  733. }
  734. return builder.to_string();
  735. }
  736. void GTextEditor::delete_selection()
  737. {
  738. if (!has_selection())
  739. return;
  740. auto selection = normalized_selection();
  741. // First delete all the lines in between the first and last one.
  742. for (int i = selection.start().line() + 1; i < selection.end().line();) {
  743. m_lines.remove(i);
  744. selection.end().set_line(selection.end().line() - 1);
  745. }
  746. if (selection.start().line() == selection.end().line()) {
  747. // Delete within same line.
  748. auto& line = *m_lines[selection.start().line()];
  749. bool whole_line_is_selected = selection.start().column() == 0 && selection.end().column() == line.length();
  750. if (whole_line_is_selected) {
  751. line.clear();
  752. } else {
  753. auto before_selection = String(line.characters(), line.length()).substring(0, selection.start().column());
  754. auto after_selection = String(line.characters(), line.length()).substring(selection.end().column(), line.length() - selection.end().column());
  755. StringBuilder builder(before_selection.length() + after_selection.length());
  756. builder.append(before_selection);
  757. builder.append(after_selection);
  758. line.set_text(builder.to_string());
  759. }
  760. } else {
  761. // Delete across a newline, merging lines.
  762. ASSERT(selection.start().line() == selection.end().line() - 1);
  763. auto& first_line = *m_lines[selection.start().line()];
  764. auto& second_line = *m_lines[selection.end().line()];
  765. auto before_selection = String(first_line.characters(), first_line.length()).substring(0, selection.start().column());
  766. auto after_selection = String(second_line.characters(), second_line.length()).substring(selection.end().column(), second_line.length() - selection.end().column());
  767. StringBuilder builder(before_selection.length() + after_selection.length());
  768. builder.append(before_selection);
  769. builder.append(after_selection);
  770. first_line.set_text(builder.to_string());
  771. m_lines.remove(selection.end().line());
  772. }
  773. if (m_lines.is_empty())
  774. m_lines.append(make<Line>());
  775. m_selection.clear();
  776. did_update_selection();
  777. set_cursor(selection.start());
  778. update();
  779. did_change();
  780. }
  781. void GTextEditor::insert_at_cursor_or_replace_selection(const String& text)
  782. {
  783. if (has_selection())
  784. delete_selection();
  785. insert_at_cursor(text);
  786. }
  787. void GTextEditor::cut()
  788. {
  789. auto selected_text = this->selected_text();
  790. printf("Cut: \"%s\"\n", selected_text.characters());
  791. GClipboard::the().set_data(selected_text);
  792. delete_selection();
  793. }
  794. void GTextEditor::copy()
  795. {
  796. auto selected_text = this->selected_text();
  797. printf("Copy: \"%s\"\n", selected_text.characters());
  798. GClipboard::the().set_data(selected_text);
  799. }
  800. void GTextEditor::paste()
  801. {
  802. auto paste_text = GClipboard::the().data();
  803. printf("Paste: \"%s\"\n", paste_text.characters());
  804. insert_at_cursor_or_replace_selection(paste_text);
  805. }
  806. void GTextEditor::enter_event(CEvent&)
  807. {
  808. ASSERT(window());
  809. window()->set_override_cursor(GStandardCursor::IBeam);
  810. }
  811. void GTextEditor::leave_event(CEvent&)
  812. {
  813. ASSERT(window());
  814. window()->set_override_cursor(GStandardCursor::None);
  815. }
  816. void GTextEditor::did_change()
  817. {
  818. update_content_size();
  819. if (!m_have_pending_change_notification) {
  820. m_have_pending_change_notification = true;
  821. deferred_invoke([this] (auto&) {
  822. if (on_change)
  823. on_change();
  824. m_have_pending_change_notification = false;
  825. });
  826. }
  827. }
  828. void GTextEditor::did_update_selection()
  829. {
  830. m_cut_action->set_enabled(has_selection());
  831. m_copy_action->set_enabled(has_selection());
  832. if (on_selection_change)
  833. on_selection_change();
  834. }
  835. void GTextEditor::context_menu_event(GContextMenuEvent& event)
  836. {
  837. if (!m_context_menu) {
  838. m_context_menu = make<GMenu>("GTextEditor context menu");
  839. m_context_menu->add_action(undo_action());
  840. m_context_menu->add_action(redo_action());
  841. m_context_menu->add_separator();
  842. m_context_menu->add_action(cut_action());
  843. m_context_menu->add_action(copy_action());
  844. m_context_menu->add_action(paste_action());
  845. m_context_menu->add_action(delete_action());
  846. }
  847. m_context_menu->popup(event.screen_position());
  848. }
  849. void GTextEditor::set_text_alignment(TextAlignment alignment)
  850. {
  851. if (m_text_alignment == alignment)
  852. return;
  853. m_text_alignment = alignment;
  854. update();
  855. }
  856. void GTextEditor::resize_event(GResizeEvent& event)
  857. {
  858. GScrollableWidget::resize_event(event);
  859. update_content_size();
  860. }