GTextEditor.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959
  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. painter.translate(frame_thickness(), frame_thickness());
  182. Rect ruler_rect { 0, 0, ruler_width(), height() - height_occupied_by_horizontal_scrollbar()};
  183. if (m_ruler_visible) {
  184. painter.fill_rect(ruler_rect, Color::LightGray);
  185. painter.draw_line(ruler_rect.top_right(), ruler_rect.bottom_right(), Color::DarkGray);
  186. }
  187. painter.translate(-horizontal_scrollbar().value(), -vertical_scrollbar().value());
  188. if (m_ruler_visible)
  189. painter.translate(ruler_width(), 0);
  190. int exposed_width = max(content_width(), frame_inner_rect().width());
  191. int first_visible_line = text_position_at(event.rect().top_left()).line();
  192. int last_visible_line = text_position_at(event.rect().bottom_right()).line();
  193. auto selection = normalized_selection();
  194. bool has_selection = selection.is_valid();
  195. if (m_ruler_visible) {
  196. for (int i = first_visible_line; i <= last_visible_line; ++i) {
  197. bool is_current_line = i == m_cursor.line();
  198. auto ruler_line_rect = ruler_content_rect(i);
  199. painter.draw_text(
  200. ruler_line_rect.shrunken(2, 0),
  201. String::format("%u", i),
  202. is_current_line ? Font::default_bold_font() : font(),
  203. TextAlignment::CenterRight,
  204. is_current_line ? Color::DarkGray : Color::MidGray
  205. );
  206. }
  207. }
  208. 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() });
  209. for (int i = first_visible_line; i <= last_visible_line; ++i) {
  210. auto& line = *m_lines[i];
  211. auto line_rect = line_content_rect(i);
  212. // FIXME: Make sure we always fill the entire line.
  213. //line_rect.set_width(exposed_width);
  214. if (is_multi_line() && i == m_cursor.line())
  215. painter.fill_rect(line_rect, Color(230, 230, 230));
  216. painter.draw_text(line_rect, line.characters(), line.length(), m_text_alignment, Color::Black);
  217. bool line_has_selection = has_selection && i >= selection.start().line() && i <= selection.end().line();
  218. if (line_has_selection) {
  219. int selection_start_column_on_line = selection.start().line() == i ? selection.start().column() : 0;
  220. int selection_end_column_on_line = selection.end().line() == i ? selection.end().column() : line.length();
  221. int selection_left = content_x_for_position({ i, selection_start_column_on_line });
  222. int selection_right = content_x_for_position({ i, selection_end_column_on_line });;
  223. Rect selection_rect { selection_left, line_rect.y(), selection_right - selection_left, line_rect.height() };
  224. painter.fill_rect(selection_rect, Color::from_rgb(0x955233));
  225. 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);
  226. }
  227. }
  228. if (is_focused() && m_cursor_state)
  229. painter.fill_rect(cursor_content_rect(), Color::Red);
  230. }
  231. void GTextEditor::toggle_selection_if_needed_for_event(const GKeyEvent& event)
  232. {
  233. if (event.shift() && !m_selection.is_valid()) {
  234. m_selection.set(m_cursor, { });
  235. did_update_selection();
  236. update();
  237. return;
  238. }
  239. if (!event.shift() && m_selection.is_valid()) {
  240. m_selection.clear();
  241. did_update_selection();
  242. update();
  243. return;
  244. }
  245. }
  246. void GTextEditor::keydown_event(GKeyEvent& event)
  247. {
  248. if (event.key() == KeyCode::Key_Escape) {
  249. if (on_escape_pressed)
  250. on_escape_pressed();
  251. return;
  252. }
  253. if (event.key() == KeyCode::Key_Up) {
  254. if (m_cursor.line() > 0) {
  255. int new_line = m_cursor.line() - 1;
  256. int new_column = min(m_cursor.column(), m_lines[new_line]->length());
  257. toggle_selection_if_needed_for_event(event);
  258. set_cursor(new_line, new_column);
  259. if (m_selection.start().is_valid()) {
  260. m_selection.set_end(m_cursor);
  261. did_update_selection();
  262. }
  263. }
  264. return;
  265. }
  266. if (event.key() == KeyCode::Key_Down) {
  267. if (m_cursor.line() < (m_lines.size() - 1)) {
  268. int new_line = m_cursor.line() + 1;
  269. int new_column = min(m_cursor.column(), m_lines[new_line]->length());
  270. toggle_selection_if_needed_for_event(event);
  271. set_cursor(new_line, new_column);
  272. if (m_selection.start().is_valid()) {
  273. m_selection.set_end(m_cursor);
  274. did_update_selection();
  275. }
  276. }
  277. return;
  278. }
  279. if (event.key() == KeyCode::Key_PageUp) {
  280. if (m_cursor.line() > 0) {
  281. int new_line = max(0, m_cursor.line() - visible_content_rect().height() / line_height());
  282. int new_column = min(m_cursor.column(), m_lines[new_line]->length());
  283. toggle_selection_if_needed_for_event(event);
  284. set_cursor(new_line, new_column);
  285. if (m_selection.start().is_valid()) {
  286. m_selection.set_end(m_cursor);
  287. did_update_selection();
  288. }
  289. }
  290. return;
  291. }
  292. if (event.key() == KeyCode::Key_PageDown) {
  293. if (m_cursor.line() < (m_lines.size() - 1)) {
  294. int new_line = min(line_count() - 1, m_cursor.line() + visible_content_rect().height() / line_height());
  295. int new_column = min(m_cursor.column(), m_lines[new_line]->length());
  296. toggle_selection_if_needed_for_event(event);
  297. set_cursor(new_line, new_column);
  298. if (m_selection.start().is_valid()) {
  299. m_selection.set_end(m_cursor);
  300. did_update_selection();
  301. }
  302. }
  303. return;
  304. }
  305. if (event.key() == KeyCode::Key_Left) {
  306. if (m_cursor.column() > 0) {
  307. int new_column = m_cursor.column() - 1;
  308. toggle_selection_if_needed_for_event(event);
  309. set_cursor(m_cursor.line(), new_column);
  310. if (m_selection.start().is_valid()) {
  311. m_selection.set_end(m_cursor);
  312. did_update_selection();
  313. }
  314. } else if (m_cursor.line() > 0) {
  315. int new_line = m_cursor.line() - 1;
  316. int new_column = m_lines[new_line]->length();
  317. toggle_selection_if_needed_for_event(event);
  318. set_cursor(new_line, new_column);
  319. if (m_selection.start().is_valid()) {
  320. m_selection.set_end(m_cursor);
  321. did_update_selection();
  322. }
  323. }
  324. return;
  325. }
  326. if (event.key() == KeyCode::Key_Right) {
  327. if (m_cursor.column() < current_line().length()) {
  328. int new_column = m_cursor.column() + 1;
  329. toggle_selection_if_needed_for_event(event);
  330. set_cursor(m_cursor.line(), new_column);
  331. if (m_selection.start().is_valid()) {
  332. m_selection.set_end(m_cursor);
  333. did_update_selection();
  334. }
  335. } else if (m_cursor.line() != line_count() - 1) {
  336. int new_line = m_cursor.line() + 1;
  337. int new_column = 0;
  338. toggle_selection_if_needed_for_event(event);
  339. set_cursor(new_line, new_column);
  340. if (m_selection.start().is_valid()) {
  341. m_selection.set_end(m_cursor);
  342. did_update_selection();
  343. }
  344. }
  345. return;
  346. }
  347. if (!event.ctrl() && event.key() == KeyCode::Key_Home) {
  348. toggle_selection_if_needed_for_event(event);
  349. set_cursor(m_cursor.line(), 0);
  350. if (m_selection.start().is_valid()) {
  351. m_selection.set_end(m_cursor);
  352. did_update_selection();
  353. }
  354. return;
  355. }
  356. if (!event.ctrl() && event.key() == KeyCode::Key_End) {
  357. toggle_selection_if_needed_for_event(event);
  358. set_cursor(m_cursor.line(), current_line().length());
  359. if (m_selection.start().is_valid()) {
  360. m_selection.set_end(m_cursor);
  361. did_update_selection();
  362. }
  363. return;
  364. }
  365. if (event.ctrl() && event.key() == KeyCode::Key_Home) {
  366. toggle_selection_if_needed_for_event(event);
  367. set_cursor(0, 0);
  368. if (m_selection.start().is_valid()) {
  369. m_selection.set_end(m_cursor);
  370. did_update_selection();
  371. }
  372. return;
  373. }
  374. if (event.ctrl() && event.key() == KeyCode::Key_End) {
  375. toggle_selection_if_needed_for_event(event);
  376. set_cursor(line_count() - 1, m_lines[line_count() - 1]->length());
  377. if (m_selection.start().is_valid()) {
  378. m_selection.set_end(m_cursor);
  379. did_update_selection();
  380. }
  381. return;
  382. }
  383. if (event.modifiers() == Mod_Ctrl && event.key() == KeyCode::Key_A) {
  384. GTextPosition start_of_document { 0, 0 };
  385. GTextPosition end_of_document { line_count() - 1, m_lines[line_count() - 1]->length() };
  386. m_selection.set(start_of_document, end_of_document);
  387. did_update_selection();
  388. set_cursor(end_of_document);
  389. update();
  390. return;
  391. }
  392. if (event.key() == KeyCode::Key_Backspace) {
  393. if (has_selection()) {
  394. delete_selection();
  395. did_update_selection();
  396. return;
  397. }
  398. if (m_cursor.column() > 0) {
  399. // Backspace within line
  400. current_line().remove(m_cursor.column() - 1);
  401. update_content_size();
  402. set_cursor(m_cursor.line(), m_cursor.column() - 1);
  403. return;
  404. }
  405. if (m_cursor.column() == 0 && m_cursor.line() != 0) {
  406. // Backspace at column 0; merge with previous line
  407. auto& previous_line = *m_lines[m_cursor.line() - 1];
  408. int previous_length = previous_line.length();
  409. previous_line.append(current_line().characters(), current_line().length());
  410. m_lines.remove(m_cursor.line());
  411. update_content_size();
  412. update();
  413. set_cursor(m_cursor.line() - 1, previous_length);
  414. return;
  415. }
  416. return;
  417. }
  418. if (event.modifiers() == Mod_Shift && event.key() == KeyCode::Key_Delete) {
  419. delete_current_line();
  420. return;
  421. }
  422. if (event.key() == KeyCode::Key_Delete) {
  423. do_delete();
  424. return;
  425. }
  426. if (!event.ctrl() && !event.alt() && !event.text().is_empty())
  427. insert_at_cursor_or_replace_selection(event.text());
  428. return GWidget::keydown_event(event);
  429. }
  430. void GTextEditor::delete_current_line()
  431. {
  432. if (has_selection())
  433. return delete_selection();
  434. m_lines.remove(m_cursor.line());
  435. if (m_lines.is_empty())
  436. m_lines.append(make<Line>());
  437. update_content_size();
  438. update();
  439. }
  440. void GTextEditor::do_delete()
  441. {
  442. if (has_selection())
  443. return delete_selection();
  444. if (m_cursor.column() < current_line().length()) {
  445. // Delete within line
  446. current_line().remove(m_cursor.column());
  447. update_cursor();
  448. did_change();
  449. return;
  450. }
  451. if (m_cursor.column() == current_line().length() && m_cursor.line() != line_count() - 1) {
  452. // Delete at end of line; merge with next line
  453. auto& next_line = *m_lines[m_cursor.line() + 1];
  454. int previous_length = current_line().length();
  455. current_line().append(next_line.characters(), next_line.length());
  456. m_lines.remove(m_cursor.line() + 1);
  457. update();
  458. set_cursor(m_cursor.line(), previous_length);
  459. did_change();
  460. return;
  461. }
  462. }
  463. void GTextEditor::insert_at_cursor(const String& text)
  464. {
  465. // FIXME: This should obviously not be implemented this way.
  466. for (int i = 0; i < text.length(); ++i) {
  467. insert_at_cursor(text[i]);
  468. }
  469. }
  470. void GTextEditor::insert_at_cursor(char ch)
  471. {
  472. bool at_head = m_cursor.column() == 0;
  473. bool at_tail = m_cursor.column() == current_line().length();
  474. if (ch == '\n') {
  475. if (is_single_line()) {
  476. if (on_return_pressed)
  477. on_return_pressed();
  478. return;
  479. }
  480. if (at_tail || at_head) {
  481. m_lines.insert(m_cursor.line() + (at_tail ? 1 : 0), make<Line>());
  482. update();
  483. set_cursor(m_cursor.line() + 1, 0);
  484. did_change();
  485. return;
  486. }
  487. auto new_line = make<Line>();
  488. new_line->append(current_line().characters() + m_cursor.column(), current_line().length() - m_cursor.column());
  489. current_line().truncate(m_cursor.column());
  490. m_lines.insert(m_cursor.line() + 1, move(new_line));
  491. update();
  492. set_cursor(m_cursor.line() + 1, 0);
  493. did_change();
  494. return;
  495. }
  496. if (ch == '\t') {
  497. int next_soft_tab_stop = ((m_cursor.column() + m_soft_tab_width) / m_soft_tab_width) * m_soft_tab_width;
  498. int spaces_to_insert = next_soft_tab_stop - m_cursor.column();
  499. for (int i = 0; i < spaces_to_insert; ++i) {
  500. current_line().insert(m_cursor.column(), ' ');
  501. }
  502. set_cursor(m_cursor.line(), next_soft_tab_stop);
  503. update_cursor();
  504. did_change();
  505. return;
  506. }
  507. current_line().insert(m_cursor.column(), ch);
  508. set_cursor(m_cursor.line(), m_cursor.column() + 1);
  509. update_cursor();
  510. did_change();
  511. }
  512. int GTextEditor::content_x_for_position(const GTextPosition& position) const
  513. {
  514. auto& line = *m_lines[position.line()];
  515. switch (m_text_alignment) {
  516. case TextAlignment::CenterLeft:
  517. return m_horizontal_content_padding + position.column() * glyph_width();
  518. case TextAlignment::CenterRight:
  519. return content_width() - m_horizontal_content_padding - (line.length() * glyph_width()) + (position.column() * glyph_width());
  520. default:
  521. ASSERT_NOT_REACHED();
  522. }
  523. }
  524. Rect GTextEditor::cursor_content_rect() const
  525. {
  526. if (!m_cursor.is_valid())
  527. return { };
  528. ASSERT(!m_lines.is_empty());
  529. ASSERT(m_cursor.column() <= (current_line().length() + 1));
  530. int cursor_x = content_x_for_position(m_cursor);
  531. if (is_single_line()) {
  532. Rect cursor_rect { cursor_x, 0, 1, font().glyph_height() + 2 };
  533. cursor_rect.center_vertically_within({ { }, frame_inner_rect().size() });
  534. return cursor_rect;
  535. }
  536. return { cursor_x, m_cursor.line() * line_height(), 1, line_height() };
  537. }
  538. Rect GTextEditor::line_widget_rect(int line_index) const
  539. {
  540. auto rect = line_content_rect(line_index);
  541. rect.set_x(frame_thickness());
  542. rect.set_width(frame_inner_rect().width());
  543. rect.move_by(0, -(vertical_scrollbar().value()));
  544. rect.move_by(0, frame_thickness());
  545. rect.intersect(frame_inner_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({ { }, frame_inner_rect().size() });
  558. return line_rect;
  559. }
  560. return {
  561. content_x_for_position({ line_index, 0 }),
  562. line_index * line_height(),
  563. line.length() * glyph_width(),
  564. line_height()
  565. };
  566. }
  567. void GTextEditor::update_cursor()
  568. {
  569. update(line_widget_rect(m_cursor.line()));
  570. }
  571. void GTextEditor::set_cursor(int line, int column)
  572. {
  573. set_cursor({ line, column });
  574. }
  575. void GTextEditor::set_cursor(const GTextPosition& position)
  576. {
  577. ASSERT(!m_lines.is_empty());
  578. ASSERT(position.line() < m_lines.size());
  579. ASSERT(position.column() <= m_lines[position.line()]->length());
  580. if (m_cursor != position) {
  581. auto old_cursor_line_rect = line_widget_rect(m_cursor.line());
  582. m_cursor = position;
  583. m_cursor_state = true;
  584. scroll_cursor_into_view();
  585. update(old_cursor_line_rect);
  586. update_cursor();
  587. }
  588. if (on_cursor_change)
  589. on_cursor_change();
  590. }
  591. void GTextEditor::focusin_event(CEvent&)
  592. {
  593. update_cursor();
  594. start_timer(500);
  595. }
  596. void GTextEditor::focusout_event(CEvent&)
  597. {
  598. stop_timer();
  599. }
  600. void GTextEditor::timer_event(CTimerEvent&)
  601. {
  602. m_cursor_state = !m_cursor_state;
  603. if (is_focused())
  604. update_cursor();
  605. }
  606. GTextEditor::Line::Line()
  607. {
  608. clear();
  609. }
  610. void GTextEditor::Line::clear()
  611. {
  612. m_text.clear();
  613. m_text.append(0);
  614. }
  615. void GTextEditor::Line::set_text(const String& text)
  616. {
  617. if (text.length() == length() && !memcmp(text.characters(), characters(), length()))
  618. return;
  619. if (text.is_empty()) {
  620. clear();
  621. return;
  622. }
  623. m_text.resize(text.length() + 1);
  624. memcpy(m_text.data(), text.characters(), text.length() + 1);
  625. }
  626. int GTextEditor::Line::width(const Font& font) const
  627. {
  628. return font.glyph_width('x') * length();
  629. }
  630. void GTextEditor::Line::append(const char* characters, int length)
  631. {
  632. int old_length = m_text.size() - 1;
  633. m_text.resize(m_text.size() + length);
  634. memcpy(m_text.data() + old_length, characters, length);
  635. m_text.last() = 0;
  636. }
  637. void GTextEditor::Line::append(char ch)
  638. {
  639. insert(length(), ch);
  640. }
  641. void GTextEditor::Line::prepend(char ch)
  642. {
  643. insert(0, ch);
  644. }
  645. void GTextEditor::Line::insert(int index, char ch)
  646. {
  647. if (index == length()) {
  648. m_text.last() = ch;
  649. m_text.append(0);
  650. } else {
  651. m_text.insert(index, move(ch));
  652. }
  653. }
  654. void GTextEditor::Line::remove(int index)
  655. {
  656. if (index == length()) {
  657. m_text.take_last();
  658. m_text.last() = 0;
  659. } else {
  660. m_text.remove(index);
  661. }
  662. }
  663. void GTextEditor::Line::truncate(int length)
  664. {
  665. m_text.resize(length + 1);
  666. m_text.last() = 0;
  667. }
  668. bool GTextEditor::write_to_file(const String& path)
  669. {
  670. int fd = open(path.characters(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
  671. if (fd < 0) {
  672. perror("open");
  673. return false;
  674. }
  675. for (int i = 0; i < m_lines.size(); ++i) {
  676. auto& line = *m_lines[i];
  677. if (line.length()) {
  678. ssize_t nwritten = write(fd, line.characters(), line.length());
  679. if (nwritten < 0) {
  680. perror("write");
  681. close(fd);
  682. return false;
  683. }
  684. }
  685. if (i != m_lines.size() - 1) {
  686. char ch = '\n';
  687. ssize_t nwritten = write(fd, &ch, 1);
  688. if (nwritten != 1) {
  689. perror("write");
  690. close(fd);
  691. return false;
  692. }
  693. }
  694. }
  695. close(fd);
  696. return true;
  697. }
  698. String GTextEditor::text() const
  699. {
  700. StringBuilder builder;
  701. for (int i = 0; i < line_count(); ++i) {
  702. auto& line = *m_lines[i];
  703. builder.append(line.characters(), line.length());
  704. if (i != line_count() - 1)
  705. builder.append('\n');
  706. }
  707. return builder.to_string();
  708. }
  709. void GTextEditor::clear()
  710. {
  711. m_lines.clear();
  712. m_lines.append(make<Line>());
  713. m_selection.clear();
  714. did_update_selection();
  715. set_cursor(0, 0);
  716. update();
  717. }
  718. String GTextEditor::selected_text() const
  719. {
  720. if (!has_selection())
  721. return { };
  722. auto selection = normalized_selection();
  723. StringBuilder builder;
  724. for (int i = selection.start().line(); i <= selection.end().line(); ++i) {
  725. auto& line = *m_lines[i];
  726. int selection_start_column_on_line = selection.start().line() == i ? selection.start().column() : 0;
  727. int selection_end_column_on_line = selection.end().line() == i ? selection.end().column() : line.length();
  728. builder.append(line.characters() + selection_start_column_on_line, selection_end_column_on_line - selection_start_column_on_line);
  729. if (i != selection.end().line())
  730. builder.append('\n');
  731. }
  732. return builder.to_string();
  733. }
  734. void GTextEditor::delete_selection()
  735. {
  736. if (!has_selection())
  737. return;
  738. auto selection = normalized_selection();
  739. // First delete all the lines in between the first and last one.
  740. for (int i = selection.start().line() + 1; i < selection.end().line();) {
  741. m_lines.remove(i);
  742. selection.end().set_line(selection.end().line() - 1);
  743. }
  744. if (selection.start().line() == selection.end().line()) {
  745. // Delete within same line.
  746. auto& line = *m_lines[selection.start().line()];
  747. bool whole_line_is_selected = selection.start().column() == 0 && selection.end().column() == line.length();
  748. if (whole_line_is_selected) {
  749. line.clear();
  750. } else {
  751. auto before_selection = String(line.characters(), line.length()).substring(0, selection.start().column());
  752. auto after_selection = String(line.characters(), line.length()).substring(selection.end().column(), line.length() - selection.end().column());
  753. StringBuilder builder(before_selection.length() + after_selection.length());
  754. builder.append(before_selection);
  755. builder.append(after_selection);
  756. line.set_text(builder.to_string());
  757. }
  758. } else {
  759. // Delete across a newline, merging lines.
  760. ASSERT(selection.start().line() == selection.end().line() - 1);
  761. auto& first_line = *m_lines[selection.start().line()];
  762. auto& second_line = *m_lines[selection.end().line()];
  763. auto before_selection = String(first_line.characters(), first_line.length()).substring(0, selection.start().column());
  764. auto after_selection = String(second_line.characters(), second_line.length()).substring(selection.end().column(), second_line.length() - selection.end().column());
  765. StringBuilder builder(before_selection.length() + after_selection.length());
  766. builder.append(before_selection);
  767. builder.append(after_selection);
  768. first_line.set_text(builder.to_string());
  769. m_lines.remove(selection.end().line());
  770. }
  771. if (m_lines.is_empty())
  772. m_lines.append(make<Line>());
  773. m_selection.clear();
  774. did_update_selection();
  775. set_cursor(selection.start());
  776. update();
  777. did_change();
  778. }
  779. void GTextEditor::insert_at_cursor_or_replace_selection(const String& text)
  780. {
  781. if (has_selection())
  782. delete_selection();
  783. insert_at_cursor(text);
  784. }
  785. void GTextEditor::cut()
  786. {
  787. auto selected_text = this->selected_text();
  788. printf("Cut: \"%s\"\n", selected_text.characters());
  789. GClipboard::the().set_data(selected_text);
  790. delete_selection();
  791. }
  792. void GTextEditor::copy()
  793. {
  794. auto selected_text = this->selected_text();
  795. printf("Copy: \"%s\"\n", selected_text.characters());
  796. GClipboard::the().set_data(selected_text);
  797. }
  798. void GTextEditor::paste()
  799. {
  800. auto paste_text = GClipboard::the().data();
  801. printf("Paste: \"%s\"\n", paste_text.characters());
  802. insert_at_cursor_or_replace_selection(paste_text);
  803. }
  804. void GTextEditor::enter_event(CEvent&)
  805. {
  806. ASSERT(window());
  807. window()->set_override_cursor(GStandardCursor::IBeam);
  808. }
  809. void GTextEditor::leave_event(CEvent&)
  810. {
  811. ASSERT(window());
  812. window()->set_override_cursor(GStandardCursor::None);
  813. }
  814. void GTextEditor::did_change()
  815. {
  816. update_content_size();
  817. if (!m_have_pending_change_notification) {
  818. m_have_pending_change_notification = true;
  819. deferred_invoke([this] (auto&) {
  820. if (on_change)
  821. on_change();
  822. m_have_pending_change_notification = false;
  823. });
  824. }
  825. }
  826. void GTextEditor::did_update_selection()
  827. {
  828. m_cut_action->set_enabled(has_selection());
  829. m_copy_action->set_enabled(has_selection());
  830. if (on_selection_change)
  831. on_selection_change();
  832. }
  833. void GTextEditor::context_menu_event(GContextMenuEvent& event)
  834. {
  835. if (!m_context_menu) {
  836. m_context_menu = make<GMenu>("GTextEditor context menu");
  837. m_context_menu->add_action(undo_action());
  838. m_context_menu->add_action(redo_action());
  839. m_context_menu->add_separator();
  840. m_context_menu->add_action(cut_action());
  841. m_context_menu->add_action(copy_action());
  842. m_context_menu->add_action(paste_action());
  843. m_context_menu->add_action(delete_action());
  844. }
  845. m_context_menu->popup(event.screen_position());
  846. }
  847. void GTextEditor::set_text_alignment(TextAlignment alignment)
  848. {
  849. if (m_text_alignment == alignment)
  850. return;
  851. m_text_alignment = alignment;
  852. update();
  853. }
  854. void GTextEditor::resize_event(GResizeEvent& event)
  855. {
  856. GScrollableWidget::resize_event(event);
  857. update_content_size();
  858. }