GTextEditor.cpp 56 KB

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