GTextEditor.cpp 33 KB

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