GTextEditor.cpp 32 KB

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