GTextEditor.cpp 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693
  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. //#define DEBUG_GTEXTEDITOR
  16. GTextEditor::GTextEditor(GWidget* parent)
  17. : GTextEditor(Type::MultiLine, parent)
  18. {
  19. }
  20. GTextEditor::GTextEditor(Type type, GWidget* parent)
  21. : GScrollableWidget(parent)
  22. , m_type(type)
  23. {
  24. set_document(GTextDocument::create());
  25. set_frame_shape(FrameShape::Container);
  26. set_frame_shadow(FrameShadow::Sunken);
  27. set_frame_thickness(2);
  28. set_scrollbars_enabled(is_multi_line());
  29. set_font(GFontDatabase::the().get_by_name("Csilla Thin"));
  30. // FIXME: Recompute vertical scrollbar step size on font change.
  31. vertical_scrollbar().set_step(line_height());
  32. m_cursor = { 0, 0 };
  33. create_actions();
  34. // TODO: Instead of a repating timer, this we should call a delayed 2 sec timer when the user types.
  35. m_undo_timer = CTimer::construct(
  36. 2000, [&] {
  37. update_undo_timer();
  38. },
  39. this);
  40. }
  41. GTextEditor::~GTextEditor()
  42. {
  43. if (m_document)
  44. m_document->unregister_client(*this);
  45. }
  46. void GTextEditor::create_actions()
  47. {
  48. m_undo_action = GCommonActions::make_undo_action([&](auto&) { undo(); }, this);
  49. m_redo_action = GCommonActions::make_redo_action([&](auto&) { redo(); }, this);
  50. m_undo_action->set_enabled(false);
  51. m_redo_action->set_enabled(false);
  52. m_cut_action = GCommonActions::make_cut_action([&](auto&) { cut(); }, this);
  53. m_copy_action = GCommonActions::make_copy_action([&](auto&) { copy(); }, this);
  54. m_paste_action = GCommonActions::make_paste_action([&](auto&) { paste(); }, this);
  55. m_delete_action = GCommonActions::make_delete_action([&](auto&) { do_delete(); }, this);
  56. }
  57. void GTextEditor::set_text(const StringView& text)
  58. {
  59. if (is_single_line() && text.length() == line(0).length() && !memcmp(text.characters_without_null_termination(), line(0).characters(), text.length()))
  60. return;
  61. m_selection.clear();
  62. document().set_text(text);
  63. update_content_size();
  64. recompute_all_visual_lines();
  65. if (is_single_line())
  66. set_cursor(0, line(0).length());
  67. else
  68. set_cursor(0, 0);
  69. did_update_selection();
  70. update();
  71. }
  72. void GTextEditor::update_content_size()
  73. {
  74. int content_width = 0;
  75. int content_height = 0;
  76. for (auto& line : m_line_visual_data) {
  77. content_width = max(line.visual_rect.width(), content_width);
  78. content_height += line.visual_rect.height();
  79. }
  80. content_width += m_horizontal_content_padding * 2;
  81. if (is_right_text_alignment(m_text_alignment))
  82. content_width = max(frame_inner_rect().width(), content_width);
  83. set_content_size({ content_width, content_height });
  84. set_size_occupied_by_fixed_elements({ ruler_width(), 0 });
  85. }
  86. GTextPosition GTextEditor::text_position_at(const Point& a_position) const
  87. {
  88. auto position = a_position;
  89. position.move_by(horizontal_scrollbar().value(), vertical_scrollbar().value());
  90. position.move_by(-(m_horizontal_content_padding + ruler_width()), 0);
  91. position.move_by(-frame_thickness(), -frame_thickness());
  92. int line_index = -1;
  93. if (is_line_wrapping_enabled()) {
  94. for (int i = 0; i < lines().size(); ++i) {
  95. auto& rect = m_line_visual_data[i].visual_rect;
  96. if (position.y() >= rect.top() && position.y() <= rect.bottom()) {
  97. line_index = i;
  98. break;
  99. }
  100. if (position.y() > rect.bottom())
  101. line_index = lines().size() - 1;
  102. }
  103. } else {
  104. line_index = position.y() / line_height();
  105. }
  106. line_index = max(0, min(line_index, line_count() - 1));
  107. int column_index;
  108. switch (m_text_alignment) {
  109. case TextAlignment::CenterLeft:
  110. column_index = (position.x() + glyph_width() / 2) / glyph_width();
  111. if (is_line_wrapping_enabled()) {
  112. for_each_visual_line(line_index, [&](const Rect& rect, const StringView&, int start_of_line) {
  113. if (rect.contains_vertically(position.y())) {
  114. column_index += start_of_line;
  115. return IterationDecision::Break;
  116. }
  117. return IterationDecision::Continue;
  118. });
  119. }
  120. break;
  121. case TextAlignment::CenterRight:
  122. // FIXME: Support right-aligned line wrapping, I guess.
  123. ASSERT(!is_line_wrapping_enabled());
  124. column_index = (position.x() - content_x_for_position({ line_index, 0 }) + glyph_width() / 2) / glyph_width();
  125. break;
  126. default:
  127. ASSERT_NOT_REACHED();
  128. }
  129. column_index = max(0, min(column_index, lines()[line_index].length()));
  130. return { line_index, column_index };
  131. }
  132. void GTextEditor::doubleclick_event(GMouseEvent& event)
  133. {
  134. if (event.button() != GMouseButton::Left)
  135. return;
  136. // NOTE: This ensures that spans are updated before we look at them.
  137. flush_pending_change_notification_if_needed();
  138. m_triple_click_timer.start();
  139. m_in_drag_select = false;
  140. auto start = text_position_at(event.position());
  141. auto end = start;
  142. auto& line = lines()[start.line()];
  143. if (!document().has_spans()) {
  144. while (start.column() > 0) {
  145. if (isspace(line.characters()[start.column() - 1]))
  146. break;
  147. start.set_column(start.column() - 1);
  148. }
  149. while (end.column() < line.length()) {
  150. if (isspace(line.characters()[end.column()]))
  151. break;
  152. end.set_column(end.column() + 1);
  153. }
  154. } else {
  155. for (auto& span : document().spans()) {
  156. if (!span.range.contains(start))
  157. continue;
  158. start = span.range.start();
  159. end = span.range.end();
  160. end.set_column(end.column() + 1);
  161. break;
  162. }
  163. }
  164. m_selection.set(start, end);
  165. set_cursor(end);
  166. update();
  167. did_update_selection();
  168. }
  169. void GTextEditor::mousedown_event(GMouseEvent& event)
  170. {
  171. if (event.button() != GMouseButton::Left) {
  172. return;
  173. }
  174. if (m_triple_click_timer.is_valid() && m_triple_click_timer.elapsed() < 250) {
  175. m_triple_click_timer = CElapsedTimer();
  176. GTextPosition start;
  177. GTextPosition end;
  178. if (is_multi_line()) {
  179. // select *current* line
  180. start = GTextPosition(m_cursor.line(), 0);
  181. end = GTextPosition(m_cursor.line(), lines()[m_cursor.line()].length());
  182. } else {
  183. // select *whole* line
  184. start = GTextPosition(0, 0);
  185. end = GTextPosition(line_count() - 1, lines()[line_count() - 1].length());
  186. }
  187. m_selection.set(start, end);
  188. set_cursor(end);
  189. return;
  190. }
  191. if (event.modifiers() & Mod_Shift) {
  192. if (!has_selection())
  193. m_selection.set(m_cursor, {});
  194. } else {
  195. m_selection.clear();
  196. }
  197. m_in_drag_select = true;
  198. set_cursor(text_position_at(event.position()));
  199. if (!(event.modifiers() & Mod_Shift)) {
  200. if (!has_selection())
  201. m_selection.set(m_cursor, {});
  202. }
  203. if (m_selection.start().is_valid() && m_selection.start() != m_cursor)
  204. m_selection.set_end(m_cursor);
  205. // FIXME: Only update the relevant rects.
  206. update();
  207. did_update_selection();
  208. }
  209. void GTextEditor::mouseup_event(GMouseEvent& event)
  210. {
  211. if (event.button() == GMouseButton::Left) {
  212. if (m_in_drag_select) {
  213. m_in_drag_select = false;
  214. }
  215. return;
  216. }
  217. }
  218. void GTextEditor::mousemove_event(GMouseEvent& event)
  219. {
  220. if (m_in_drag_select) {
  221. set_cursor(text_position_at(event.position()));
  222. m_selection.set_end(m_cursor);
  223. did_update_selection();
  224. update();
  225. return;
  226. }
  227. }
  228. int GTextEditor::ruler_width() const
  229. {
  230. if (!m_ruler_visible)
  231. return 0;
  232. // FIXME: Resize based on needed space.
  233. return 5 * font().glyph_width('x') + 4;
  234. }
  235. Rect GTextEditor::ruler_content_rect(int line_index) const
  236. {
  237. if (!m_ruler_visible)
  238. return {};
  239. return {
  240. 0 - ruler_width() + horizontal_scrollbar().value(),
  241. line_content_rect(line_index).y(),
  242. ruler_width(),
  243. line_content_rect(line_index).height()
  244. };
  245. }
  246. Rect GTextEditor::ruler_rect_in_inner_coordinates() const
  247. {
  248. return { 0, 0, ruler_width(), height() - height_occupied_by_horizontal_scrollbar() };
  249. }
  250. Rect GTextEditor::visible_text_rect_in_inner_coordinates() const
  251. {
  252. return {
  253. m_horizontal_content_padding + (m_ruler_visible ? (ruler_rect_in_inner_coordinates().right() + 1) : 0),
  254. 0,
  255. frame_inner_rect().width() - (m_horizontal_content_padding * 2) - width_occupied_by_vertical_scrollbar() - ruler_width(),
  256. frame_inner_rect().height() - height_occupied_by_horizontal_scrollbar()
  257. };
  258. }
  259. void GTextEditor::paint_event(GPaintEvent& event)
  260. {
  261. // NOTE: This ensures that spans are updated before we look at them.
  262. flush_pending_change_notification_if_needed();
  263. GFrame::paint_event(event);
  264. GPainter painter(*this);
  265. painter.add_clip_rect(widget_inner_rect());
  266. painter.add_clip_rect(event.rect());
  267. painter.fill_rect(event.rect(), Color::White);
  268. painter.translate(frame_thickness(), frame_thickness());
  269. auto ruler_rect = ruler_rect_in_inner_coordinates();
  270. if (m_ruler_visible) {
  271. painter.fill_rect(ruler_rect, Color::WarmGray);
  272. painter.draw_line(ruler_rect.top_right(), ruler_rect.bottom_right(), Color::DarkGray);
  273. }
  274. painter.translate(-horizontal_scrollbar().value(), -vertical_scrollbar().value());
  275. if (m_ruler_visible)
  276. painter.translate(ruler_width(), 0);
  277. int first_visible_line = text_position_at(event.rect().top_left()).line();
  278. int last_visible_line = text_position_at(event.rect().bottom_right()).line();
  279. auto selection = normalized_selection();
  280. bool has_selection = selection.is_valid();
  281. if (m_ruler_visible) {
  282. for (int i = first_visible_line; i <= last_visible_line; ++i) {
  283. bool is_current_line = i == m_cursor.line();
  284. auto ruler_line_rect = ruler_content_rect(i);
  285. painter.draw_text(
  286. ruler_line_rect.shrunken(2, 0).translated(0, m_line_spacing / 2),
  287. String::number(i + 1),
  288. is_current_line ? Font::default_bold_font() : font(),
  289. TextAlignment::TopRight,
  290. is_current_line ? Color::DarkGray : Color::MidGray);
  291. }
  292. }
  293. Rect text_clip_rect {
  294. (m_ruler_visible ? (ruler_rect_in_inner_coordinates().right() + frame_thickness() + 1) : frame_thickness()),
  295. frame_thickness(),
  296. width() - width_occupied_by_vertical_scrollbar() - ruler_width(),
  297. height() - height_occupied_by_horizontal_scrollbar()
  298. };
  299. painter.add_clip_rect(text_clip_rect);
  300. for (int line_index = first_visible_line; line_index <= last_visible_line; ++line_index) {
  301. auto& line = lines()[line_index];
  302. bool physical_line_has_selection = has_selection && line_index >= selection.start().line() && line_index <= selection.end().line();
  303. int first_visual_line_with_selection = -1;
  304. int last_visual_line_with_selection = -1;
  305. if (physical_line_has_selection) {
  306. if (selection.start().line() < line_index)
  307. first_visual_line_with_selection = 0;
  308. else
  309. first_visual_line_with_selection = visual_line_containing(line_index, selection.start().column());
  310. if (selection.end().line() > line_index)
  311. last_visual_line_with_selection = m_line_visual_data[line_index].visual_line_breaks.size();
  312. else
  313. last_visual_line_with_selection = visual_line_containing(line_index, selection.end().column());
  314. }
  315. int selection_start_column_within_line = selection.start().line() == line_index ? selection.start().column() : 0;
  316. int selection_end_column_within_line = selection.end().line() == line_index ? selection.end().column() : line.length();
  317. int visual_line_index = 0;
  318. for_each_visual_line(line_index, [&](const Rect& visual_line_rect, const StringView& visual_line_text, int start_of_visual_line) {
  319. if (is_multi_line() && line_index == m_cursor.line())
  320. painter.fill_rect(visual_line_rect, Color(230, 230, 230));
  321. #ifdef DEBUG_GTEXTEDITOR
  322. painter.draw_rect(visual_line_rect, Color::Cyan);
  323. #endif
  324. if (!document().has_spans()) {
  325. // Fast-path for plain text
  326. painter.draw_text(visual_line_rect, visual_line_text, m_text_alignment, Color::Black);
  327. } else {
  328. int advance = font().glyph_width(' ') + font().glyph_spacing();
  329. Rect character_rect = { visual_line_rect.location(), { font().glyph_width(' '), line_height() } };
  330. for (int i = 0; i < visual_line_text.length(); ++i) {
  331. const Font* font = &this->font();
  332. Color color;
  333. GTextPosition physical_position(line_index, start_of_visual_line + i);
  334. // FIXME: This is *horribly* inefficient.
  335. for (auto& span : document().spans()) {
  336. if (!span.range.contains(physical_position))
  337. continue;
  338. color = span.color;
  339. if (span.font)
  340. font = span.font;
  341. break;
  342. }
  343. painter.draw_text(character_rect, visual_line_text.substring_view(i, 1), *font, m_text_alignment, color);
  344. character_rect.move_by(advance, 0);
  345. }
  346. }
  347. bool physical_line_has_selection = has_selection && line_index >= selection.start().line() && line_index <= selection.end().line();
  348. if (physical_line_has_selection) {
  349. bool current_visual_line_has_selection = (line_index != selection.start().line() && line_index != selection.end().line())
  350. || (visual_line_index >= first_visual_line_with_selection && visual_line_index <= last_visual_line_with_selection);
  351. if (current_visual_line_has_selection) {
  352. bool selection_begins_on_current_visual_line = visual_line_index == first_visual_line_with_selection;
  353. bool selection_ends_on_current_visual_line = visual_line_index == last_visual_line_with_selection;
  354. int selection_left = selection_begins_on_current_visual_line
  355. ? content_x_for_position({ line_index, selection_start_column_within_line })
  356. : m_horizontal_content_padding;
  357. int selection_right = selection_ends_on_current_visual_line
  358. ? content_x_for_position({ line_index, selection_end_column_within_line })
  359. : visual_line_rect.right() + 1;
  360. Rect selection_rect {
  361. selection_left,
  362. visual_line_rect.y(),
  363. selection_right - selection_left,
  364. visual_line_rect.height()
  365. };
  366. painter.fill_rect(selection_rect, Color::from_rgb(0x955233));
  367. int start_of_selection_within_visual_line = max(0, selection_start_column_within_line - start_of_visual_line);
  368. int end_of_selection_within_visual_line = selection_end_column_within_line - start_of_visual_line;
  369. StringView visual_selected_text {
  370. visual_line_text.characters_without_null_termination() + start_of_selection_within_visual_line,
  371. end_of_selection_within_visual_line - start_of_selection_within_visual_line
  372. };
  373. painter.draw_text(selection_rect, visual_selected_text, TextAlignment::CenterLeft, Color::White);
  374. }
  375. }
  376. ++visual_line_index;
  377. return IterationDecision::Continue;
  378. });
  379. }
  380. if (is_focused() && m_cursor_state)
  381. painter.fill_rect(cursor_content_rect(), Color::Red);
  382. }
  383. void GTextEditor::toggle_selection_if_needed_for_event(const GKeyEvent& event)
  384. {
  385. if (event.shift() && !m_selection.is_valid()) {
  386. m_selection.set(m_cursor, {});
  387. did_update_selection();
  388. update();
  389. return;
  390. }
  391. if (!event.shift() && m_selection.is_valid()) {
  392. m_selection.clear();
  393. did_update_selection();
  394. update();
  395. return;
  396. }
  397. }
  398. void GTextEditor::select_all()
  399. {
  400. GTextPosition start_of_document { 0, 0 };
  401. GTextPosition end_of_document { line_count() - 1, lines()[line_count() - 1].length() };
  402. m_selection.set(start_of_document, end_of_document);
  403. did_update_selection();
  404. set_cursor(end_of_document);
  405. update();
  406. }
  407. void GTextEditor::undo()
  408. {
  409. if (!can_undo())
  410. return;
  411. auto& undo_container = m_undo_stack[m_undo_stack_index];
  412. auto& undo_vector = undo_container.m_undo_vector;
  413. //If we try to undo a empty vector, delete it and skip over.
  414. if (undo_vector.is_empty()) {
  415. m_undo_stack.remove(m_undo_stack_index);
  416. undo();
  417. return;
  418. }
  419. for (int i = 0; i < undo_vector.size(); i++) {
  420. auto& undo_command = undo_vector[i];
  421. undo_command.undo();
  422. }
  423. m_undo_stack_index++;
  424. did_change();
  425. }
  426. void GTextEditor::redo()
  427. {
  428. if (!can_redo())
  429. return;
  430. auto& undo_container = m_undo_stack[m_undo_stack_index - 1];
  431. auto& redo_vector = undo_container.m_undo_vector;
  432. for (int i = redo_vector.size() - 1; i >= 0; i--) {
  433. auto& undo_command = redo_vector[i];
  434. undo_command.redo();
  435. }
  436. m_undo_stack_index--;
  437. did_change();
  438. }
  439. void GTextEditor::get_selection_line_boundaries(int& first_line, int& last_line)
  440. {
  441. auto selection = normalized_selection();
  442. if (!selection.is_valid()) {
  443. first_line = m_cursor.line();
  444. last_line = m_cursor.line();
  445. return;
  446. }
  447. first_line = selection.start().line();
  448. last_line = selection.end().line();
  449. if (first_line != last_line && selection.end().column() == 0)
  450. last_line -= 1;
  451. }
  452. void GTextEditor::move_selected_lines_up()
  453. {
  454. int first_line;
  455. int last_line;
  456. get_selection_line_boundaries(first_line, last_line);
  457. if (first_line == 0)
  458. return;
  459. auto& lines = document().lines();
  460. lines.insert(last_line, lines.take(first_line - 1));
  461. m_cursor = { first_line - 1, 0 };
  462. if (has_selection()) {
  463. m_selection.set_start({ first_line - 1, 0 });
  464. m_selection.set_end({ last_line - 1, line(last_line - 1).length() });
  465. }
  466. did_change();
  467. update();
  468. }
  469. void GTextEditor::move_selected_lines_down()
  470. {
  471. int first_line;
  472. int last_line;
  473. get_selection_line_boundaries(first_line, last_line);
  474. auto& lines = document().lines();
  475. if (last_line >= (lines.size() - 1))
  476. return;
  477. lines.insert(first_line, lines.take(last_line + 1));
  478. m_cursor = { first_line + 1, 0 };
  479. if (has_selection()) {
  480. m_selection.set_start({ first_line + 1, 0 });
  481. m_selection.set_end({ last_line + 1, line(last_line + 1).length() });
  482. }
  483. did_change();
  484. update();
  485. }
  486. void GTextEditor::keydown_event(GKeyEvent& event)
  487. {
  488. if (is_single_line() && event.key() == KeyCode::Key_Tab)
  489. return GWidget::keydown_event(event);
  490. if (is_single_line() && event.key() == KeyCode::Key_Return) {
  491. if (on_return_pressed)
  492. on_return_pressed();
  493. return;
  494. }
  495. if (event.key() == KeyCode::Key_Escape) {
  496. if (on_escape_pressed)
  497. on_escape_pressed();
  498. return;
  499. }
  500. if (event.key() == KeyCode::Key_Up) {
  501. if (m_cursor.line() > 0) {
  502. if (event.ctrl() && event.shift()) {
  503. move_selected_lines_up();
  504. return;
  505. }
  506. int new_line = m_cursor.line() - 1;
  507. int new_column = min(m_cursor.column(), lines()[new_line].length());
  508. toggle_selection_if_needed_for_event(event);
  509. set_cursor(new_line, new_column);
  510. if (event.shift() && m_selection.start().is_valid()) {
  511. m_selection.set_end(m_cursor);
  512. did_update_selection();
  513. }
  514. }
  515. return;
  516. }
  517. if (event.key() == KeyCode::Key_Down) {
  518. if (m_cursor.line() < (lines().size() - 1)) {
  519. if (event.ctrl() && event.shift()) {
  520. move_selected_lines_down();
  521. return;
  522. }
  523. int new_line = m_cursor.line() + 1;
  524. int new_column = min(m_cursor.column(), lines()[new_line].length());
  525. toggle_selection_if_needed_for_event(event);
  526. set_cursor(new_line, new_column);
  527. if (event.shift() && m_selection.start().is_valid()) {
  528. m_selection.set_end(m_cursor);
  529. did_update_selection();
  530. }
  531. }
  532. return;
  533. }
  534. if (event.key() == KeyCode::Key_PageUp) {
  535. if (m_cursor.line() > 0) {
  536. int new_line = max(0, m_cursor.line() - visible_content_rect().height() / line_height());
  537. int new_column = min(m_cursor.column(), lines()[new_line].length());
  538. toggle_selection_if_needed_for_event(event);
  539. set_cursor(new_line, new_column);
  540. if (event.shift() && m_selection.start().is_valid()) {
  541. m_selection.set_end(m_cursor);
  542. did_update_selection();
  543. }
  544. }
  545. return;
  546. }
  547. if (event.key() == KeyCode::Key_PageDown) {
  548. if (m_cursor.line() < (lines().size() - 1)) {
  549. int new_line = min(line_count() - 1, m_cursor.line() + visible_content_rect().height() / line_height());
  550. int new_column = min(m_cursor.column(), lines()[new_line].length());
  551. toggle_selection_if_needed_for_event(event);
  552. set_cursor(new_line, new_column);
  553. if (event.shift() && m_selection.start().is_valid()) {
  554. m_selection.set_end(m_cursor);
  555. did_update_selection();
  556. }
  557. }
  558. return;
  559. }
  560. if (event.key() == KeyCode::Key_Left) {
  561. if (m_cursor.column() > 0) {
  562. int new_column = m_cursor.column() - 1;
  563. toggle_selection_if_needed_for_event(event);
  564. set_cursor(m_cursor.line(), new_column);
  565. if (event.shift() && m_selection.start().is_valid()) {
  566. m_selection.set_end(m_cursor);
  567. did_update_selection();
  568. }
  569. } else if (m_cursor.line() > 0) {
  570. int new_line = m_cursor.line() - 1;
  571. int new_column = lines()[new_line].length();
  572. toggle_selection_if_needed_for_event(event);
  573. set_cursor(new_line, new_column);
  574. if (event.shift() && m_selection.start().is_valid()) {
  575. m_selection.set_end(m_cursor);
  576. did_update_selection();
  577. }
  578. }
  579. return;
  580. }
  581. if (event.key() == KeyCode::Key_Right) {
  582. int new_line = m_cursor.line();
  583. int new_column = m_cursor.column();
  584. if (m_cursor.column() < current_line().length()) {
  585. new_line = m_cursor.line();
  586. new_column = m_cursor.column() + 1;
  587. } else if (m_cursor.line() != line_count() - 1) {
  588. new_line = m_cursor.line() + 1;
  589. new_column = 0;
  590. }
  591. toggle_selection_if_needed_for_event(event);
  592. set_cursor(new_line, new_column);
  593. if (event.shift() && m_selection.start().is_valid()) {
  594. m_selection.set_end(m_cursor);
  595. did_update_selection();
  596. }
  597. return;
  598. }
  599. if (!event.ctrl() && event.key() == KeyCode::Key_Home) {
  600. int first_nonspace_column = current_line().first_non_whitespace_column();
  601. toggle_selection_if_needed_for_event(event);
  602. if (m_cursor.column() == first_nonspace_column)
  603. set_cursor(m_cursor.line(), 0);
  604. else
  605. set_cursor(m_cursor.line(), first_nonspace_column);
  606. if (event.shift() && m_selection.start().is_valid()) {
  607. m_selection.set_end(m_cursor);
  608. did_update_selection();
  609. }
  610. return;
  611. }
  612. if (!event.ctrl() && event.key() == KeyCode::Key_End) {
  613. toggle_selection_if_needed_for_event(event);
  614. set_cursor(m_cursor.line(), current_line().length());
  615. if (event.shift() && m_selection.start().is_valid()) {
  616. m_selection.set_end(m_cursor);
  617. did_update_selection();
  618. }
  619. return;
  620. }
  621. if (event.ctrl() && event.key() == KeyCode::Key_Home) {
  622. toggle_selection_if_needed_for_event(event);
  623. set_cursor(0, 0);
  624. if (event.shift() && m_selection.start().is_valid()) {
  625. m_selection.set_end(m_cursor);
  626. did_update_selection();
  627. }
  628. return;
  629. }
  630. if (event.ctrl() && event.key() == KeyCode::Key_End) {
  631. toggle_selection_if_needed_for_event(event);
  632. set_cursor(line_count() - 1, lines()[line_count() - 1].length());
  633. if (event.shift() && m_selection.start().is_valid()) {
  634. m_selection.set_end(m_cursor);
  635. did_update_selection();
  636. }
  637. return;
  638. }
  639. if (event.modifiers() == Mod_Ctrl && event.key() == KeyCode::Key_A) {
  640. select_all();
  641. return;
  642. }
  643. if (event.key() == KeyCode::Key_Backspace) {
  644. if (is_readonly())
  645. return;
  646. if (has_selection()) {
  647. delete_selection();
  648. did_update_selection();
  649. return;
  650. }
  651. if (m_cursor.column() > 0) {
  652. int erase_count = 1;
  653. if (current_line().first_non_whitespace_column() >= m_cursor.column()) {
  654. int new_column;
  655. if (m_cursor.column() % m_soft_tab_width == 0)
  656. new_column = m_cursor.column() - m_soft_tab_width;
  657. else
  658. new_column = (m_cursor.column() / m_soft_tab_width) * m_soft_tab_width;
  659. erase_count = m_cursor.column() - new_column;
  660. }
  661. // Backspace within line
  662. for (int i = 0; i < erase_count; ++i) {
  663. int row = m_cursor.line();
  664. int column = m_cursor.column() - 1 - i;
  665. add_to_undo_stack(make<RemoveCharacterCommand>(*this, document().line(row).characters()[column], GTextPosition(row, column)));
  666. current_line().remove(document(), m_cursor.column() - 1 - i);
  667. }
  668. update_content_size();
  669. set_cursor(m_cursor.line(), m_cursor.column() - erase_count);
  670. did_change();
  671. return;
  672. }
  673. if (m_cursor.column() == 0 && m_cursor.line() != 0) {
  674. // Backspace at column 0; merge with previous line
  675. auto& previous_line = lines()[m_cursor.line() - 1];
  676. int previous_length = previous_line.length();
  677. int row = m_cursor.line();
  678. int column = previous_length;
  679. add_to_undo_stack(make<RemoveLineCommand>(*this, String(lines()[m_cursor.line()].view()), GTextPosition(row, column), true));
  680. previous_line.append(document(), current_line().characters(), current_line().length());
  681. document().remove_line(m_cursor.line());
  682. update_content_size();
  683. update();
  684. set_cursor(m_cursor.line() - 1, previous_length);
  685. did_change();
  686. return;
  687. }
  688. return;
  689. }
  690. if (event.modifiers() == Mod_Shift && event.key() == KeyCode::Key_Delete) {
  691. if (is_readonly())
  692. return;
  693. delete_current_line();
  694. return;
  695. }
  696. if (event.key() == KeyCode::Key_Delete) {
  697. if (is_readonly())
  698. return;
  699. do_delete();
  700. return;
  701. }
  702. if (!is_readonly() && !event.ctrl() && !event.alt() && !event.text().is_empty())
  703. insert_at_cursor_or_replace_selection(event.text());
  704. }
  705. void GTextEditor::delete_current_line()
  706. {
  707. if (has_selection())
  708. return delete_selection();
  709. document().remove_line(m_cursor.line());
  710. if (lines().is_empty())
  711. document().append_line(make<GTextDocumentLine>(document()));
  712. m_cursor.set_column(0);
  713. update_content_size();
  714. update();
  715. }
  716. void GTextEditor::do_delete()
  717. {
  718. if (is_readonly())
  719. return;
  720. if (has_selection())
  721. return delete_selection();
  722. if (m_cursor.column() < current_line().length()) {
  723. // Delete within line
  724. current_line().remove(document(), m_cursor.column());
  725. did_change();
  726. update_cursor();
  727. return;
  728. }
  729. if (m_cursor.column() == current_line().length() && m_cursor.line() != line_count() - 1) {
  730. // Delete at end of line; merge with next line
  731. auto& next_line = lines()[m_cursor.line() + 1];
  732. int previous_length = current_line().length();
  733. current_line().append(document(), next_line.characters(), next_line.length());
  734. document().remove_line(m_cursor.line() + 1);
  735. update();
  736. did_change();
  737. set_cursor(m_cursor.line(), previous_length);
  738. return;
  739. }
  740. }
  741. void GTextEditor::insert_at_cursor(const StringView& text)
  742. {
  743. // FIXME: This should obviously not be implemented this way.
  744. for (int i = 0; i < text.length(); ++i) {
  745. insert_at_cursor(text[i]);
  746. }
  747. }
  748. void GTextEditor::insert_at_cursor(char ch)
  749. {
  750. bool at_head = m_cursor.column() == 0;
  751. bool at_tail = m_cursor.column() == current_line().length();
  752. if (ch == '\n') {
  753. if (at_tail || at_head) {
  754. String new_line_contents;
  755. if (m_automatic_indentation_enabled && at_tail) {
  756. int leading_spaces = 0;
  757. auto& old_line = lines()[m_cursor.line()];
  758. for (int i = 0; i < old_line.length(); ++i) {
  759. if (old_line.characters()[i] == ' ')
  760. ++leading_spaces;
  761. else
  762. break;
  763. }
  764. if (leading_spaces)
  765. new_line_contents = String::repeated(' ', leading_spaces);
  766. }
  767. int row = m_cursor.line();
  768. int column = m_cursor.column() + 1;
  769. Vector<char> line_content;
  770. for (int i = m_cursor.column(); i < document().lines()[row].length(); i++)
  771. line_content.append(document().lines()[row].characters()[i]);
  772. add_to_undo_stack(make<CreateLineCommand>(*this, line_content, GTextPosition(row, column)));
  773. document().insert_line(m_cursor.line() + (at_tail ? 1 : 0), make<GTextDocumentLine>(document(), new_line_contents));
  774. update();
  775. did_change();
  776. set_cursor(m_cursor.line() + 1, lines()[m_cursor.line() + 1].length());
  777. return;
  778. }
  779. auto new_line = make<GTextDocumentLine>(document());
  780. new_line->append(document(), current_line().characters() + m_cursor.column(), current_line().length() - m_cursor.column());
  781. int row = m_cursor.line();
  782. int column = m_cursor.column() + 1;
  783. Vector<char> line_content;
  784. for (int i = 0; i < new_line->length(); i++)
  785. line_content.append(new_line->characters()[i]);
  786. add_to_undo_stack(make<CreateLineCommand>(*this, line_content, GTextPosition(row, column)));
  787. current_line().truncate(document(), m_cursor.column());
  788. document().insert_line(m_cursor.line() + 1, move(new_line));
  789. update();
  790. did_change();
  791. set_cursor(m_cursor.line() + 1, 0);
  792. return;
  793. }
  794. if (ch == '\t') {
  795. int next_soft_tab_stop = ((m_cursor.column() + m_soft_tab_width) / m_soft_tab_width) * m_soft_tab_width;
  796. int spaces_to_insert = next_soft_tab_stop - m_cursor.column();
  797. for (int i = 0; i < spaces_to_insert; ++i) {
  798. current_line().insert(document(), m_cursor.column(), ' ');
  799. }
  800. did_change();
  801. set_cursor(m_cursor.line(), next_soft_tab_stop);
  802. return;
  803. }
  804. current_line().insert(document(), m_cursor.column(), ch);
  805. did_change();
  806. set_cursor(m_cursor.line(), m_cursor.column() + 1);
  807. add_to_undo_stack(make<InsertCharacterCommand>(*this, ch, m_cursor));
  808. }
  809. int GTextEditor::content_x_for_position(const GTextPosition& position) const
  810. {
  811. auto& line = lines()[position.line()];
  812. int x_offset = -1;
  813. switch (m_text_alignment) {
  814. case TextAlignment::CenterLeft:
  815. for_each_visual_line(position.line(), [&](const Rect&, const StringView& view, int start_of_visual_line) {
  816. if (position.column() >= start_of_visual_line && ((position.column() - start_of_visual_line) <= view.length())) {
  817. x_offset = (position.column() - start_of_visual_line) * glyph_width();
  818. return IterationDecision::Break;
  819. }
  820. return IterationDecision::Continue;
  821. });
  822. return m_horizontal_content_padding + x_offset;
  823. case TextAlignment::CenterRight:
  824. // FIXME
  825. ASSERT(!is_line_wrapping_enabled());
  826. return content_width() - m_horizontal_content_padding - (line.length() * glyph_width()) + (position.column() * glyph_width());
  827. default:
  828. ASSERT_NOT_REACHED();
  829. }
  830. }
  831. Rect GTextEditor::content_rect_for_position(const GTextPosition& position) const
  832. {
  833. if (!position.is_valid())
  834. return {};
  835. ASSERT(!lines().is_empty());
  836. ASSERT(position.column() <= (current_line().length() + 1));
  837. int x = content_x_for_position(position);
  838. if (is_single_line()) {
  839. Rect rect { x, 0, 1, font().glyph_height() + 2 };
  840. rect.center_vertically_within({ {}, frame_inner_rect().size() });
  841. return rect;
  842. }
  843. Rect rect;
  844. for_each_visual_line(position.line(), [&](const Rect& visual_line_rect, const StringView& view, int start_of_visual_line) {
  845. if (position.column() >= start_of_visual_line && ((position.column() - start_of_visual_line) <= view.length())) {
  846. // NOTE: We have to subtract the horizontal padding here since it's part of the visual line rect
  847. // *and* included in what we get from content_x_for_position().
  848. rect = {
  849. visual_line_rect.x() + x - (m_horizontal_content_padding),
  850. visual_line_rect.y(),
  851. 1,
  852. line_height()
  853. };
  854. return IterationDecision::Break;
  855. }
  856. return IterationDecision::Continue;
  857. });
  858. return rect;
  859. }
  860. Rect GTextEditor::cursor_content_rect() const
  861. {
  862. return content_rect_for_position(m_cursor);
  863. }
  864. Rect GTextEditor::line_widget_rect(int line_index) const
  865. {
  866. auto rect = line_content_rect(line_index);
  867. rect.set_x(frame_thickness());
  868. rect.set_width(frame_inner_rect().width());
  869. rect.move_by(0, -(vertical_scrollbar().value()));
  870. rect.move_by(0, frame_thickness());
  871. rect.intersect(frame_inner_rect());
  872. return rect;
  873. }
  874. void GTextEditor::scroll_position_into_view(const GTextPosition& position)
  875. {
  876. auto rect = content_rect_for_position(position);
  877. if (position.column() == 0)
  878. rect.set_x(content_x_for_position({ position.line(), 0 }) - 2);
  879. else if (position.column() == lines()[position.line()].length())
  880. rect.set_x(content_x_for_position({ position.line(), lines()[position.line()].length() }) + 2);
  881. scroll_into_view(rect, true, true);
  882. }
  883. void GTextEditor::scroll_cursor_into_view()
  884. {
  885. scroll_position_into_view(m_cursor);
  886. }
  887. Rect GTextEditor::line_content_rect(int line_index) const
  888. {
  889. auto& line = lines()[line_index];
  890. if (is_single_line()) {
  891. Rect line_rect = { content_x_for_position({ line_index, 0 }), 0, line.length() * glyph_width(), font().glyph_height() + 2 };
  892. line_rect.center_vertically_within({ {}, frame_inner_rect().size() });
  893. return line_rect;
  894. }
  895. if (is_line_wrapping_enabled())
  896. return m_line_visual_data[line_index].visual_rect;
  897. return {
  898. content_x_for_position({ line_index, 0 }),
  899. line_index * line_height(),
  900. line.length() * glyph_width(),
  901. line_height()
  902. };
  903. }
  904. void GTextEditor::update_cursor()
  905. {
  906. update(line_widget_rect(m_cursor.line()));
  907. }
  908. void GTextEditor::update_undo_timer()
  909. {
  910. if (m_undo_stack.is_empty())
  911. return;
  912. auto& undo_vector = m_undo_stack[0].m_undo_vector;
  913. if (undo_vector.size() == m_last_updated_undo_vector_size && !undo_vector.is_empty()) {
  914. auto undo_commands_container = make<UndoCommandsContainer>();
  915. m_undo_stack.prepend(move(undo_commands_container));
  916. // Note: Remove dbg() if we're 100% sure there are no bugs left.
  917. dbg() << "Undo stack increased to " << m_undo_stack.size();
  918. // Shift the index to the left since we're adding an empty container.
  919. if (m_undo_stack_index > 0)
  920. m_undo_stack_index++;
  921. }
  922. m_last_updated_undo_vector_size = undo_vector.size();
  923. }
  924. void GTextEditor::set_cursor(int line, int column)
  925. {
  926. set_cursor({ line, column });
  927. }
  928. void GTextEditor::set_cursor(const GTextPosition& a_position)
  929. {
  930. ASSERT(!lines().is_empty());
  931. GTextPosition position = a_position;
  932. if (position.line() >= lines().size())
  933. position.set_line(lines().size() - 1);
  934. if (position.column() > lines()[position.line()].length())
  935. position.set_column(lines()[position.line()].length());
  936. if (m_cursor != position) {
  937. // NOTE: If the old cursor is no longer valid, repaint everything just in case.
  938. auto old_cursor_line_rect = m_cursor.line() < lines().size()
  939. ? line_widget_rect(m_cursor.line())
  940. : rect();
  941. m_cursor = position;
  942. m_cursor_state = true;
  943. scroll_cursor_into_view();
  944. update(old_cursor_line_rect);
  945. update_cursor();
  946. }
  947. if (on_cursor_change)
  948. on_cursor_change();
  949. }
  950. void GTextEditor::focusin_event(CEvent&)
  951. {
  952. update_cursor();
  953. start_timer(500);
  954. }
  955. void GTextEditor::focusout_event(CEvent&)
  956. {
  957. stop_timer();
  958. }
  959. void GTextEditor::timer_event(CTimerEvent&)
  960. {
  961. m_cursor_state = !m_cursor_state;
  962. if (is_focused())
  963. update_cursor();
  964. }
  965. bool GTextEditor::write_to_file(const StringView& path)
  966. {
  967. int fd = open_with_path_length(path.characters_without_null_termination(), path.length(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
  968. if (fd < 0) {
  969. perror("open");
  970. return false;
  971. }
  972. // Compute the final file size and ftruncate() to make writing fast.
  973. // FIXME: Remove this once the kernel is smart enough to do this instead.
  974. off_t file_size = 0;
  975. for (int i = 0; i < lines().size(); ++i)
  976. file_size += lines()[i].length();
  977. file_size += lines().size() - 1;
  978. int rc = ftruncate(fd, file_size);
  979. if (rc < 0) {
  980. perror("ftruncate");
  981. return false;
  982. }
  983. for (int i = 0; i < lines().size(); ++i) {
  984. auto& line = lines()[i];
  985. if (line.length()) {
  986. ssize_t nwritten = write(fd, line.characters(), line.length());
  987. if (nwritten < 0) {
  988. perror("write");
  989. close(fd);
  990. return false;
  991. }
  992. }
  993. if (i != lines().size() - 1) {
  994. char ch = '\n';
  995. ssize_t nwritten = write(fd, &ch, 1);
  996. if (nwritten != 1) {
  997. perror("write");
  998. close(fd);
  999. return false;
  1000. }
  1001. }
  1002. }
  1003. close(fd);
  1004. return true;
  1005. }
  1006. String GTextEditor::text() const
  1007. {
  1008. StringBuilder builder;
  1009. for (int i = 0; i < line_count(); ++i) {
  1010. auto& line = lines()[i];
  1011. builder.append(line.characters(), line.length());
  1012. if (i != line_count() - 1)
  1013. builder.append('\n');
  1014. }
  1015. return builder.to_string();
  1016. }
  1017. void GTextEditor::clear()
  1018. {
  1019. document().remove_all_lines();
  1020. document().append_line(make<GTextDocumentLine>(document()));
  1021. m_selection.clear();
  1022. did_update_selection();
  1023. set_cursor(0, 0);
  1024. update();
  1025. }
  1026. String GTextEditor::selected_text() const
  1027. {
  1028. if (!has_selection())
  1029. return {};
  1030. return document().text_in_range(m_selection);
  1031. }
  1032. void GTextEditor::delete_selection()
  1033. {
  1034. if (!has_selection())
  1035. return;
  1036. auto selection = normalized_selection();
  1037. // First delete all the lines in between the first and last one.
  1038. for (int i = selection.start().line() + 1; i < selection.end().line();) {
  1039. int row = i;
  1040. int column = lines()[i].length();
  1041. add_to_undo_stack(make<RemoveLineCommand>(*this, String(lines()[i].view()), GTextPosition(row, column), false));
  1042. document().remove_line(i);
  1043. selection.end().set_line(selection.end().line() - 1);
  1044. }
  1045. if (selection.start().line() == selection.end().line()) {
  1046. // Delete within same line.
  1047. auto& line = lines()[selection.start().line()];
  1048. bool whole_line_is_selected = selection.start().column() == 0 && selection.end().column() == line.length();
  1049. for (int i = selection.end().column() - 1; i >= selection.start().column(); i--) {
  1050. int row = selection.start().line();
  1051. int column = i;
  1052. add_to_undo_stack(make<RemoveCharacterCommand>(*this, document().line(row).characters()[column], GTextPosition(row, column)));
  1053. }
  1054. if (whole_line_is_selected) {
  1055. line.clear(document());
  1056. } else {
  1057. auto before_selection = String(line.characters(), line.length()).substring(0, selection.start().column());
  1058. auto after_selection = String(line.characters(), line.length()).substring(selection.end().column(), line.length() - selection.end().column());
  1059. StringBuilder builder(before_selection.length() + after_selection.length());
  1060. builder.append(before_selection);
  1061. builder.append(after_selection);
  1062. line.set_text(document(), builder.to_string());
  1063. }
  1064. } else {
  1065. // Delete across a newline, merging lines.
  1066. ASSERT(selection.start().line() == selection.end().line() - 1);
  1067. auto& first_line = lines()[selection.start().line()];
  1068. auto& second_line = lines()[selection.end().line()];
  1069. auto before_selection = String(first_line.characters(), first_line.length()).substring(0, selection.start().column());
  1070. auto after_selection = String(second_line.characters(), second_line.length()).substring(selection.end().column(), second_line.length() - selection.end().column());
  1071. StringBuilder builder(before_selection.length() + after_selection.length());
  1072. builder.append(before_selection);
  1073. builder.append(after_selection);
  1074. for (int i = first_line.length() - 1; i > selection.start().column() - 1; i--) {
  1075. int row = selection.start().line();
  1076. int column = i;
  1077. add_to_undo_stack(make<RemoveCharacterCommand>(*this, document().line(row).characters()[column], GTextPosition(row, column)));
  1078. }
  1079. add_to_undo_stack(make<RemoveLineCommand>(*this, String(second_line.view()), selection.end(), false));
  1080. first_line.set_text(document(), builder.to_string());
  1081. document().remove_line(selection.end().line());
  1082. for (int i = (first_line.length()) - after_selection.length(); i < first_line.length(); i++)
  1083. add_to_undo_stack(make<InsertCharacterCommand>(*this, first_line.characters()[i], GTextPosition(selection.start().line(), i + 1)));
  1084. }
  1085. if (lines().is_empty()) {
  1086. document().append_line(make<GTextDocumentLine>(document()));
  1087. }
  1088. m_selection.clear();
  1089. did_update_selection();
  1090. did_change();
  1091. set_cursor(selection.start());
  1092. update();
  1093. }
  1094. void GTextEditor::insert_at_cursor_or_replace_selection(const StringView& text)
  1095. {
  1096. ASSERT(!is_readonly());
  1097. if (has_selection())
  1098. delete_selection();
  1099. insert_at_cursor(text);
  1100. }
  1101. void GTextEditor::cut()
  1102. {
  1103. if (is_readonly())
  1104. return;
  1105. auto selected_text = this->selected_text();
  1106. printf("Cut: \"%s\"\n", selected_text.characters());
  1107. GClipboard::the().set_data(selected_text);
  1108. delete_selection();
  1109. }
  1110. void GTextEditor::copy()
  1111. {
  1112. auto selected_text = this->selected_text();
  1113. printf("Copy: \"%s\"\n", selected_text.characters());
  1114. GClipboard::the().set_data(selected_text);
  1115. }
  1116. void GTextEditor::paste()
  1117. {
  1118. if (is_readonly())
  1119. return;
  1120. auto paste_text = GClipboard::the().data();
  1121. printf("Paste: \"%s\"\n", paste_text.characters());
  1122. insert_at_cursor_or_replace_selection(paste_text);
  1123. }
  1124. void GTextEditor::enter_event(CEvent&)
  1125. {
  1126. ASSERT(window());
  1127. window()->set_override_cursor(GStandardCursor::IBeam);
  1128. }
  1129. void GTextEditor::leave_event(CEvent&)
  1130. {
  1131. ASSERT(window());
  1132. window()->set_override_cursor(GStandardCursor::None);
  1133. }
  1134. void GTextEditor::did_change()
  1135. {
  1136. ASSERT(!is_readonly());
  1137. update_content_size();
  1138. recompute_all_visual_lines();
  1139. m_undo_action->set_enabled(can_undo());
  1140. m_redo_action->set_enabled(can_redo());
  1141. if (!m_has_pending_change_notification) {
  1142. m_has_pending_change_notification = true;
  1143. deferred_invoke([this](auto&) {
  1144. if (!m_has_pending_change_notification)
  1145. return;
  1146. if (on_change)
  1147. on_change();
  1148. m_has_pending_change_notification = false;
  1149. });
  1150. }
  1151. }
  1152. void GTextEditor::set_readonly(bool readonly)
  1153. {
  1154. if (m_readonly == readonly)
  1155. return;
  1156. m_readonly = readonly;
  1157. m_cut_action->set_enabled(!is_readonly() && has_selection());
  1158. m_delete_action->set_enabled(!is_readonly());
  1159. m_paste_action->set_enabled(!is_readonly());
  1160. }
  1161. void GTextEditor::did_update_selection()
  1162. {
  1163. m_cut_action->set_enabled(!is_readonly() && has_selection());
  1164. m_copy_action->set_enabled(has_selection());
  1165. if (on_selection_change)
  1166. on_selection_change();
  1167. if (is_line_wrapping_enabled()) {
  1168. // FIXME: Try to repaint less.
  1169. update();
  1170. }
  1171. }
  1172. void GTextEditor::context_menu_event(GContextMenuEvent& event)
  1173. {
  1174. if (!m_context_menu) {
  1175. m_context_menu = make<GMenu>();
  1176. m_context_menu->add_action(undo_action());
  1177. m_context_menu->add_action(redo_action());
  1178. m_context_menu->add_separator();
  1179. m_context_menu->add_action(cut_action());
  1180. m_context_menu->add_action(copy_action());
  1181. m_context_menu->add_action(paste_action());
  1182. m_context_menu->add_action(delete_action());
  1183. if (!m_custom_context_menu_actions.is_empty()) {
  1184. m_context_menu->add_separator();
  1185. for (auto& action : m_custom_context_menu_actions) {
  1186. m_context_menu->add_action(action);
  1187. }
  1188. }
  1189. }
  1190. m_context_menu->popup(event.screen_position());
  1191. }
  1192. void GTextEditor::set_text_alignment(TextAlignment alignment)
  1193. {
  1194. if (m_text_alignment == alignment)
  1195. return;
  1196. m_text_alignment = alignment;
  1197. update();
  1198. }
  1199. void GTextEditor::resize_event(GResizeEvent& event)
  1200. {
  1201. GScrollableWidget::resize_event(event);
  1202. update_content_size();
  1203. recompute_all_visual_lines();
  1204. }
  1205. void GTextEditor::set_selection(const GTextRange& selection)
  1206. {
  1207. if (m_selection == selection)
  1208. return;
  1209. m_selection = selection;
  1210. set_cursor(m_selection.end());
  1211. scroll_position_into_view(normalized_selection().start());
  1212. update();
  1213. }
  1214. void GTextEditor::recompute_all_visual_lines()
  1215. {
  1216. int y_offset = 0;
  1217. for (int line_index = 0; line_index < line_count(); ++line_index) {
  1218. recompute_visual_lines(line_index);
  1219. m_line_visual_data[line_index].visual_rect.set_y(y_offset);
  1220. y_offset += m_line_visual_data[line_index].visual_rect.height();
  1221. }
  1222. update_content_size();
  1223. }
  1224. void GTextEditor::ensure_cursor_is_valid()
  1225. {
  1226. if (cursor().column() > lines()[cursor().line()].length())
  1227. set_cursor(cursor().line(), cursor().column() - (lines()[cursor().line()].length() - cursor().column()));
  1228. }
  1229. void GTextEditor::add_to_undo_stack(NonnullOwnPtr<UndoCommand> undo_command)
  1230. {
  1231. if (m_undo_stack.is_empty()) {
  1232. auto undo_commands_container = make<UndoCommandsContainer>();
  1233. m_undo_stack.prepend(move(undo_commands_container));
  1234. }
  1235. // Clear the elements of the stack before the m_undo_stack_index (Excluding our new element)
  1236. for (int i = 1; i < m_undo_stack_index; i++)
  1237. m_undo_stack.remove(1);
  1238. if (m_undo_stack_index > 0 && !m_undo_stack.is_empty())
  1239. m_undo_stack[0].m_undo_vector.clear();
  1240. m_undo_stack_index = 0;
  1241. m_undo_stack[0].m_undo_vector.prepend(move(undo_command));
  1242. }
  1243. int GTextEditor::visual_line_containing(int line_index, int column) const
  1244. {
  1245. int visual_line_index = 0;
  1246. for_each_visual_line(line_index, [&](const Rect&, const StringView& view, int start_of_visual_line) {
  1247. if (column >= start_of_visual_line && ((column - start_of_visual_line) < view.length()))
  1248. return IterationDecision::Break;
  1249. ++visual_line_index;
  1250. return IterationDecision::Continue;
  1251. });
  1252. return visual_line_index;
  1253. }
  1254. void GTextEditor::recompute_visual_lines(int line_index)
  1255. {
  1256. auto& line = document().line(line_index);
  1257. auto& visual_data = m_line_visual_data[line_index];
  1258. visual_data.visual_line_breaks.clear_with_capacity();
  1259. int available_width = visible_text_rect_in_inner_coordinates().width();
  1260. if (is_line_wrapping_enabled()) {
  1261. int line_width_so_far = 0;
  1262. for (int i = 0; i < line.length(); ++i) {
  1263. auto ch = line.characters()[i];
  1264. auto glyph_width = font().glyph_width(ch);
  1265. if ((line_width_so_far + glyph_width) > available_width) {
  1266. visual_data.visual_line_breaks.append(i);
  1267. line_width_so_far = glyph_width;
  1268. continue;
  1269. }
  1270. line_width_so_far += glyph_width;
  1271. }
  1272. }
  1273. visual_data.visual_line_breaks.append(line.length());
  1274. if (is_line_wrapping_enabled())
  1275. visual_data.visual_rect = { m_horizontal_content_padding, 0, available_width, visual_data.visual_line_breaks.size() * line_height() };
  1276. else
  1277. visual_data.visual_rect = { m_horizontal_content_padding, 0, font().width(line.view()), line_height() };
  1278. }
  1279. template<typename Callback>
  1280. void GTextEditor::for_each_visual_line(int line_index, Callback callback) const
  1281. {
  1282. auto editor_visible_text_rect = visible_text_rect_in_inner_coordinates();
  1283. int start_of_line = 0;
  1284. int visual_line_index = 0;
  1285. auto& line = document().line(line_index);
  1286. auto& visual_data = m_line_visual_data[line_index];
  1287. for (auto visual_line_break : visual_data.visual_line_breaks) {
  1288. auto visual_line_view = StringView(line.characters() + start_of_line, visual_line_break - start_of_line);
  1289. Rect visual_line_rect {
  1290. visual_data.visual_rect.x(),
  1291. visual_data.visual_rect.y() + (visual_line_index * line_height()),
  1292. font().width(visual_line_view),
  1293. line_height()
  1294. };
  1295. if (is_right_text_alignment(text_alignment()))
  1296. visual_line_rect.set_right_without_resize(editor_visible_text_rect.right());
  1297. if (!is_multi_line())
  1298. visual_line_rect.center_vertically_within(editor_visible_text_rect);
  1299. if (callback(visual_line_rect, visual_line_view, start_of_line) == IterationDecision::Break)
  1300. break;
  1301. start_of_line = visual_line_break;
  1302. ++visual_line_index;
  1303. }
  1304. }
  1305. void GTextEditor::set_line_wrapping_enabled(bool enabled)
  1306. {
  1307. if (m_line_wrapping_enabled == enabled)
  1308. return;
  1309. m_line_wrapping_enabled = enabled;
  1310. horizontal_scrollbar().set_visible(!m_line_wrapping_enabled);
  1311. update_content_size();
  1312. recompute_all_visual_lines();
  1313. update();
  1314. }
  1315. void GTextEditor::add_custom_context_menu_action(GAction& action)
  1316. {
  1317. m_custom_context_menu_actions.append(action);
  1318. }
  1319. void GTextEditor::did_change_font()
  1320. {
  1321. vertical_scrollbar().set_step(line_height());
  1322. GWidget::did_change_font();
  1323. }
  1324. void GTextEditor::document_did_append_line()
  1325. {
  1326. m_line_visual_data.append(make<LineVisualData>());
  1327. recompute_all_visual_lines();
  1328. update();
  1329. }
  1330. void GTextEditor::document_did_remove_line(int line_index)
  1331. {
  1332. m_line_visual_data.remove(line_index);
  1333. recompute_all_visual_lines();
  1334. update();
  1335. }
  1336. void GTextEditor::document_did_remove_all_lines()
  1337. {
  1338. m_line_visual_data.clear();
  1339. recompute_all_visual_lines();
  1340. update();
  1341. }
  1342. void GTextEditor::document_did_insert_line(int line_index)
  1343. {
  1344. m_line_visual_data.insert(line_index, make<LineVisualData>());
  1345. recompute_all_visual_lines();
  1346. update();
  1347. }
  1348. void GTextEditor::document_did_change()
  1349. {
  1350. recompute_all_visual_lines();
  1351. update();
  1352. }
  1353. void GTextEditor::set_document(GTextDocument& document)
  1354. {
  1355. if (m_document.ptr() == &document)
  1356. return;
  1357. if (m_document)
  1358. m_document->unregister_client(*this);
  1359. m_document = document;
  1360. m_line_visual_data.clear();
  1361. for (int i = 0; i < m_document->line_count(); ++i) {
  1362. m_line_visual_data.append(make<LineVisualData>());
  1363. }
  1364. m_cursor = { 0, 0 };
  1365. recompute_all_visual_lines();
  1366. update();
  1367. m_document->register_client(*this);
  1368. }
  1369. GTextEditor::UndoCommand::UndoCommand(GTextEditor& text_editor)
  1370. : m_text_editor(text_editor)
  1371. {
  1372. }
  1373. GTextEditor::UndoCommand::~UndoCommand()
  1374. {
  1375. }
  1376. void GTextEditor::UndoCommand::undo() {}
  1377. void GTextEditor::UndoCommand::redo() {}
  1378. GTextEditor::InsertCharacterCommand::InsertCharacterCommand(GTextEditor& text_editor, char ch, GTextPosition text_position)
  1379. : UndoCommand(text_editor)
  1380. , m_character(ch)
  1381. , m_text_position(text_position)
  1382. {
  1383. }
  1384. GTextEditor::RemoveCharacterCommand::RemoveCharacterCommand(GTextEditor& text_editor, char ch, GTextPosition text_position)
  1385. : UndoCommand(text_editor)
  1386. , m_character(ch)
  1387. , m_text_position(text_position)
  1388. {
  1389. }
  1390. GTextEditor::RemoveLineCommand::RemoveLineCommand(GTextEditor& text_editor, String line_content, GTextPosition text_position, bool has_merged_content)
  1391. : UndoCommand(text_editor)
  1392. , m_line_content(line_content)
  1393. , m_text_position(text_position)
  1394. , m_has_merged_content(has_merged_content)
  1395. {
  1396. }
  1397. GTextEditor::CreateLineCommand::CreateLineCommand(GTextEditor& text_editor, Vector<char> line_content, GTextPosition text_position)
  1398. : UndoCommand(text_editor)
  1399. , m_line_content(line_content)
  1400. , m_text_position(text_position)
  1401. {
  1402. }
  1403. void GTextEditor::InsertCharacterCommand::undo()
  1404. {
  1405. m_text_editor.lines()[m_text_position.line()].remove(m_text_editor.document(), (m_text_position.column() - 1));
  1406. m_text_editor.ensure_cursor_is_valid();
  1407. }
  1408. void GTextEditor::InsertCharacterCommand::redo()
  1409. {
  1410. m_text_editor.lines()[m_text_position.line()].insert(m_text_editor.document(), m_text_position.column() - 1, m_character);
  1411. }
  1412. void GTextEditor::RemoveCharacterCommand::undo()
  1413. {
  1414. m_text_editor.lines()[m_text_position.line()].insert(m_text_editor.document(), m_text_position.column(), m_character);
  1415. }
  1416. void GTextEditor::RemoveCharacterCommand::redo()
  1417. {
  1418. m_text_editor.lines()[m_text_position.line()].remove(m_text_editor.document(), (m_text_position.column()));
  1419. m_text_editor.ensure_cursor_is_valid();
  1420. }
  1421. void GTextEditor::RemoveLineCommand::undo()
  1422. {
  1423. // Insert back the line
  1424. m_text_editor.document().insert_line(m_text_position.line(), make<GTextDocumentLine>(m_text_editor.document(), m_line_content));
  1425. // Remove the merged line contents
  1426. if (m_has_merged_content) {
  1427. for (int i = m_line_content.length() - 1; i >= 0; i--)
  1428. m_text_editor.document().lines()[m_text_position.line() - 1].remove(m_text_editor.document(), (m_text_position.column()) + i);
  1429. }
  1430. }
  1431. void GTextEditor::RemoveLineCommand::redo()
  1432. {
  1433. // Remove the created line
  1434. m_text_editor.document().remove_line(m_text_position.line());
  1435. // Add back the line contents
  1436. if (m_has_merged_content) {
  1437. for (int i = 0; i < m_line_content.length(); i++)
  1438. m_text_editor.document().lines()[m_text_position.line() - 1].insert(m_text_editor.document(), (m_text_position.column()) + i, m_line_content[i]);
  1439. }
  1440. }
  1441. void GTextEditor::CreateLineCommand::undo()
  1442. {
  1443. // Insert back the created line portion
  1444. for (int i = 0; i < m_line_content.size(); i++)
  1445. m_text_editor.document().lines()[m_text_position.line()].insert(m_text_editor.document(), (m_text_position.column() - 1) + i, m_line_content[i]);
  1446. // Move the cursor up a row back before the split.
  1447. m_text_editor.set_cursor(m_text_position.line(), m_text_editor.document().lines()[m_text_position.line()].length());
  1448. // Remove the created line
  1449. m_text_editor.document().remove_line(m_text_position.line() + 1);
  1450. }
  1451. void GTextEditor::CreateLineCommand::redo()
  1452. {
  1453. // Remove the characters that we're inserted back
  1454. for (int i = m_line_content.size() - 1; i >= 0; i--)
  1455. m_text_editor.document().lines()[m_text_position.line()].remove(m_text_editor.document(), (m_text_position.column()) + i);
  1456. m_text_editor.ensure_cursor_is_valid();
  1457. // Then we want to add BACK the created line
  1458. m_text_editor.document().insert_line(m_text_position.line() + 1, make<GTextDocumentLine>(m_text_editor.document(), ""));
  1459. for (int i = 0; i < m_line_content.size(); i++)
  1460. m_text_editor.document().lines()[m_text_position.line() + 1].insert(m_text_editor.document(), i, m_line_content[i]);
  1461. }
  1462. void GTextEditor::flush_pending_change_notification_if_needed()
  1463. {
  1464. if (!m_has_pending_change_notification)
  1465. return;
  1466. if (on_change)
  1467. on_change();
  1468. m_has_pending_change_notification = false;
  1469. }