GTextEditor.cpp 36 KB

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