GTextEditor.cpp 30 KB

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