GTextEditor.cpp 38 KB

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