GTextEditor.cpp 33 KB

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