GTextEditor.cpp 34 KB

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