GTextEditor.cpp 59 KB

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