GTextEditor.cpp 56 KB

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