GTextEditor.cpp 33 KB

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