GTextEditor.cpp 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616
  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::keydown_event(GKeyEvent& event)
  432. {
  433. if (is_single_line() && event.key() == KeyCode::Key_Tab)
  434. return GWidget::keydown_event(event);
  435. if (is_single_line() && event.key() == KeyCode::Key_Return) {
  436. if (on_return_pressed)
  437. on_return_pressed();
  438. return;
  439. }
  440. if (event.key() == KeyCode::Key_Escape) {
  441. if (on_escape_pressed)
  442. on_escape_pressed();
  443. return;
  444. }
  445. if (event.key() == KeyCode::Key_Up) {
  446. if (m_cursor.line() > 0) {
  447. int new_line = m_cursor.line() - 1;
  448. int new_column = min(m_cursor.column(), lines()[new_line].length());
  449. toggle_selection_if_needed_for_event(event);
  450. set_cursor(new_line, new_column);
  451. if (event.shift() && m_selection.start().is_valid()) {
  452. m_selection.set_end(m_cursor);
  453. did_update_selection();
  454. }
  455. }
  456. return;
  457. }
  458. if (event.key() == KeyCode::Key_Down) {
  459. if (m_cursor.line() < (lines().size() - 1)) {
  460. int new_line = m_cursor.line() + 1;
  461. int new_column = min(m_cursor.column(), lines()[new_line].length());
  462. toggle_selection_if_needed_for_event(event);
  463. set_cursor(new_line, new_column);
  464. if (event.shift() && m_selection.start().is_valid()) {
  465. m_selection.set_end(m_cursor);
  466. did_update_selection();
  467. }
  468. }
  469. return;
  470. }
  471. if (event.key() == KeyCode::Key_PageUp) {
  472. if (m_cursor.line() > 0) {
  473. int new_line = max(0, m_cursor.line() - visible_content_rect().height() / line_height());
  474. int new_column = min(m_cursor.column(), lines()[new_line].length());
  475. toggle_selection_if_needed_for_event(event);
  476. set_cursor(new_line, new_column);
  477. if (event.shift() && m_selection.start().is_valid()) {
  478. m_selection.set_end(m_cursor);
  479. did_update_selection();
  480. }
  481. }
  482. return;
  483. }
  484. if (event.key() == KeyCode::Key_PageDown) {
  485. if (m_cursor.line() < (lines().size() - 1)) {
  486. int new_line = min(line_count() - 1, m_cursor.line() + visible_content_rect().height() / line_height());
  487. int new_column = min(m_cursor.column(), lines()[new_line].length());
  488. toggle_selection_if_needed_for_event(event);
  489. set_cursor(new_line, new_column);
  490. if (event.shift() && m_selection.start().is_valid()) {
  491. m_selection.set_end(m_cursor);
  492. did_update_selection();
  493. }
  494. }
  495. return;
  496. }
  497. if (event.key() == KeyCode::Key_Left) {
  498. if (m_cursor.column() > 0) {
  499. int new_column = m_cursor.column() - 1;
  500. toggle_selection_if_needed_for_event(event);
  501. set_cursor(m_cursor.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. } else if (m_cursor.line() > 0) {
  507. int new_line = m_cursor.line() - 1;
  508. int new_column = lines()[new_line].length();
  509. toggle_selection_if_needed_for_event(event);
  510. set_cursor(new_line, new_column);
  511. if (event.shift() && m_selection.start().is_valid()) {
  512. m_selection.set_end(m_cursor);
  513. did_update_selection();
  514. }
  515. }
  516. return;
  517. }
  518. if (event.key() == KeyCode::Key_Right) {
  519. int new_line = m_cursor.line();
  520. int new_column = m_cursor.column();
  521. if (m_cursor.column() < current_line().length()) {
  522. new_line = m_cursor.line();
  523. new_column = m_cursor.column() + 1;
  524. } else if (m_cursor.line() != line_count() - 1) {
  525. new_line = m_cursor.line() + 1;
  526. new_column = 0;
  527. }
  528. toggle_selection_if_needed_for_event(event);
  529. set_cursor(new_line, new_column);
  530. if (event.shift() && m_selection.start().is_valid()) {
  531. m_selection.set_end(m_cursor);
  532. did_update_selection();
  533. }
  534. return;
  535. }
  536. if (!event.ctrl() && event.key() == KeyCode::Key_Home) {
  537. int first_nonspace_column = current_line().first_non_whitespace_column();
  538. toggle_selection_if_needed_for_event(event);
  539. if (m_cursor.column() == first_nonspace_column)
  540. set_cursor(m_cursor.line(), 0);
  541. else
  542. set_cursor(m_cursor.line(), first_nonspace_column);
  543. if (event.shift() && m_selection.start().is_valid()) {
  544. m_selection.set_end(m_cursor);
  545. did_update_selection();
  546. }
  547. return;
  548. }
  549. if (!event.ctrl() && event.key() == KeyCode::Key_End) {
  550. toggle_selection_if_needed_for_event(event);
  551. set_cursor(m_cursor.line(), current_line().length());
  552. if (event.shift() && m_selection.start().is_valid()) {
  553. m_selection.set_end(m_cursor);
  554. did_update_selection();
  555. }
  556. return;
  557. }
  558. if (event.ctrl() && event.key() == KeyCode::Key_Home) {
  559. toggle_selection_if_needed_for_event(event);
  560. set_cursor(0, 0);
  561. if (event.shift() && m_selection.start().is_valid()) {
  562. m_selection.set_end(m_cursor);
  563. did_update_selection();
  564. }
  565. return;
  566. }
  567. if (event.ctrl() && event.key() == KeyCode::Key_End) {
  568. toggle_selection_if_needed_for_event(event);
  569. set_cursor(line_count() - 1, lines()[line_count() - 1].length());
  570. if (event.shift() && m_selection.start().is_valid()) {
  571. m_selection.set_end(m_cursor);
  572. did_update_selection();
  573. }
  574. return;
  575. }
  576. if (event.modifiers() == Mod_Ctrl && event.key() == KeyCode::Key_A) {
  577. select_all();
  578. return;
  579. }
  580. if (event.key() == KeyCode::Key_Backspace) {
  581. if (is_readonly())
  582. return;
  583. if (has_selection()) {
  584. delete_selection();
  585. did_update_selection();
  586. return;
  587. }
  588. if (m_cursor.column() > 0) {
  589. int erase_count = 1;
  590. if (current_line().first_non_whitespace_column() >= m_cursor.column()) {
  591. int new_column;
  592. if (m_cursor.column() % m_soft_tab_width == 0)
  593. new_column = m_cursor.column() - m_soft_tab_width;
  594. else
  595. new_column = (m_cursor.column() / m_soft_tab_width) * m_soft_tab_width;
  596. erase_count = m_cursor.column() - new_column;
  597. }
  598. // Backspace within line
  599. for (int i = 0; i < erase_count; ++i) {
  600. int row = m_cursor.line();
  601. int column = m_cursor.column() - 1 - i;
  602. add_to_undo_stack(make<RemoveCharacterCommand>(*this, document().line(row).characters()[column], GTextPosition(row, column)));
  603. current_line().remove(document(), m_cursor.column() - 1 - i);
  604. }
  605. update_content_size();
  606. set_cursor(m_cursor.line(), m_cursor.column() - erase_count);
  607. did_change();
  608. return;
  609. }
  610. if (m_cursor.column() == 0 && m_cursor.line() != 0) {
  611. // Backspace at column 0; merge with previous line
  612. auto& previous_line = lines()[m_cursor.line() - 1];
  613. int previous_length = previous_line.length();
  614. int row = m_cursor.line();
  615. int column = previous_length;
  616. add_to_undo_stack(make<RemoveLineCommand>(*this, String(lines()[m_cursor.line()].view()), GTextPosition(row, column), true));
  617. previous_line.append(document(), current_line().characters(), current_line().length());
  618. document().remove_line(m_cursor.line());
  619. update_content_size();
  620. update();
  621. set_cursor(m_cursor.line() - 1, previous_length);
  622. did_change();
  623. return;
  624. }
  625. return;
  626. }
  627. if (event.modifiers() == Mod_Shift && event.key() == KeyCode::Key_Delete) {
  628. if (is_readonly())
  629. return;
  630. delete_current_line();
  631. return;
  632. }
  633. if (event.key() == KeyCode::Key_Delete) {
  634. if (is_readonly())
  635. return;
  636. do_delete();
  637. return;
  638. }
  639. if (!is_readonly() && !event.ctrl() && !event.alt() && !event.text().is_empty())
  640. insert_at_cursor_or_replace_selection(event.text());
  641. }
  642. void GTextEditor::delete_current_line()
  643. {
  644. if (has_selection())
  645. return delete_selection();
  646. document().remove_line(m_cursor.line());
  647. if (lines().is_empty())
  648. document().append_line(make<GTextDocumentLine>(document()));
  649. m_cursor.set_column(0);
  650. update_content_size();
  651. update();
  652. }
  653. void GTextEditor::do_delete()
  654. {
  655. if (is_readonly())
  656. return;
  657. if (has_selection())
  658. return delete_selection();
  659. if (m_cursor.column() < current_line().length()) {
  660. // Delete within line
  661. current_line().remove(document(), m_cursor.column());
  662. did_change();
  663. update_cursor();
  664. return;
  665. }
  666. if (m_cursor.column() == current_line().length() && m_cursor.line() != line_count() - 1) {
  667. // Delete at end of line; merge with next line
  668. auto& next_line = lines()[m_cursor.line() + 1];
  669. int previous_length = current_line().length();
  670. current_line().append(document(), next_line.characters(), next_line.length());
  671. document().remove_line(m_cursor.line() + 1);
  672. update();
  673. did_change();
  674. set_cursor(m_cursor.line(), previous_length);
  675. return;
  676. }
  677. }
  678. void GTextEditor::insert_at_cursor(const StringView& text)
  679. {
  680. // FIXME: This should obviously not be implemented this way.
  681. for (int i = 0; i < text.length(); ++i) {
  682. insert_at_cursor(text[i]);
  683. }
  684. }
  685. void GTextEditor::insert_at_cursor(char ch)
  686. {
  687. bool at_head = m_cursor.column() == 0;
  688. bool at_tail = m_cursor.column() == current_line().length();
  689. if (ch == '\n') {
  690. if (at_tail || at_head) {
  691. String new_line_contents;
  692. if (m_automatic_indentation_enabled && at_tail) {
  693. int leading_spaces = 0;
  694. auto& old_line = lines()[m_cursor.line()];
  695. for (int i = 0; i < old_line.length(); ++i) {
  696. if (old_line.characters()[i] == ' ')
  697. ++leading_spaces;
  698. else
  699. break;
  700. }
  701. if (leading_spaces)
  702. new_line_contents = String::repeated(' ', leading_spaces);
  703. }
  704. int row = m_cursor.line();
  705. int column = m_cursor.column() + 1;
  706. Vector<char> line_content;
  707. for (int i = m_cursor.column(); i < document().lines()[row].length(); i++)
  708. line_content.append(document().lines()[row].characters()[i]);
  709. add_to_undo_stack(make<CreateLineCommand>(*this, line_content, GTextPosition(row, column)));
  710. document().insert_line(m_cursor.line() + (at_tail ? 1 : 0), make<GTextDocumentLine>(document(), new_line_contents));
  711. update();
  712. did_change();
  713. set_cursor(m_cursor.line() + 1, lines()[m_cursor.line() + 1].length());
  714. return;
  715. }
  716. auto new_line = make<GTextDocumentLine>(document());
  717. new_line->append(document(), current_line().characters() + m_cursor.column(), current_line().length() - m_cursor.column());
  718. int row = m_cursor.line();
  719. int column = m_cursor.column() + 1;
  720. Vector<char> line_content;
  721. for (int i = 0; i < new_line->length(); i++)
  722. line_content.append(new_line->characters()[i]);
  723. add_to_undo_stack(make<CreateLineCommand>(*this, line_content, GTextPosition(row, column)));
  724. current_line().truncate(document(), m_cursor.column());
  725. document().insert_line(m_cursor.line() + 1, move(new_line));
  726. update();
  727. did_change();
  728. set_cursor(m_cursor.line() + 1, 0);
  729. return;
  730. }
  731. if (ch == '\t') {
  732. int next_soft_tab_stop = ((m_cursor.column() + m_soft_tab_width) / m_soft_tab_width) * m_soft_tab_width;
  733. int spaces_to_insert = next_soft_tab_stop - m_cursor.column();
  734. for (int i = 0; i < spaces_to_insert; ++i) {
  735. current_line().insert(document(), m_cursor.column(), ' ');
  736. }
  737. did_change();
  738. set_cursor(m_cursor.line(), next_soft_tab_stop);
  739. return;
  740. }
  741. current_line().insert(document(), m_cursor.column(), ch);
  742. did_change();
  743. set_cursor(m_cursor.line(), m_cursor.column() + 1);
  744. add_to_undo_stack(make<InsertCharacterCommand>(*this, ch, m_cursor));
  745. }
  746. int GTextEditor::content_x_for_position(const GTextPosition& position) const
  747. {
  748. auto& line = lines()[position.line()];
  749. int x_offset = -1;
  750. switch (m_text_alignment) {
  751. case TextAlignment::CenterLeft:
  752. for_each_visual_line(position.line(), [&](const Rect&, const StringView& view, int start_of_visual_line) {
  753. if (position.column() >= start_of_visual_line && ((position.column() - start_of_visual_line) <= view.length())) {
  754. x_offset = (position.column() - start_of_visual_line) * glyph_width();
  755. return IterationDecision::Break;
  756. }
  757. return IterationDecision::Continue;
  758. });
  759. return m_horizontal_content_padding + x_offset;
  760. case TextAlignment::CenterRight:
  761. // FIXME
  762. ASSERT(!is_line_wrapping_enabled());
  763. return content_width() - m_horizontal_content_padding - (line.length() * glyph_width()) + (position.column() * glyph_width());
  764. default:
  765. ASSERT_NOT_REACHED();
  766. }
  767. }
  768. Rect GTextEditor::content_rect_for_position(const GTextPosition& position) const
  769. {
  770. if (!position.is_valid())
  771. return {};
  772. ASSERT(!lines().is_empty());
  773. ASSERT(position.column() <= (current_line().length() + 1));
  774. int x = content_x_for_position(position);
  775. if (is_single_line()) {
  776. Rect rect { x, 0, 1, font().glyph_height() + 2 };
  777. rect.center_vertically_within({ {}, frame_inner_rect().size() });
  778. return rect;
  779. }
  780. Rect rect;
  781. for_each_visual_line(position.line(), [&](const Rect& visual_line_rect, const StringView& view, int start_of_visual_line) {
  782. if (position.column() >= start_of_visual_line && ((position.column() - start_of_visual_line) <= view.length())) {
  783. // NOTE: We have to subtract the horizontal padding here since it's part of the visual line rect
  784. // *and* included in what we get from content_x_for_position().
  785. rect = {
  786. visual_line_rect.x() + x - (m_horizontal_content_padding),
  787. visual_line_rect.y(),
  788. 1,
  789. line_height()
  790. };
  791. return IterationDecision::Break;
  792. }
  793. return IterationDecision::Continue;
  794. });
  795. return rect;
  796. }
  797. Rect GTextEditor::cursor_content_rect() const
  798. {
  799. return content_rect_for_position(m_cursor);
  800. }
  801. Rect GTextEditor::line_widget_rect(int line_index) const
  802. {
  803. auto rect = line_content_rect(line_index);
  804. rect.set_x(frame_thickness());
  805. rect.set_width(frame_inner_rect().width());
  806. rect.move_by(0, -(vertical_scrollbar().value()));
  807. rect.move_by(0, frame_thickness());
  808. rect.intersect(frame_inner_rect());
  809. return rect;
  810. }
  811. void GTextEditor::scroll_position_into_view(const GTextPosition& position)
  812. {
  813. auto rect = content_rect_for_position(position);
  814. if (position.column() == 0)
  815. rect.set_x(content_x_for_position({ position.line(), 0 }) - 2);
  816. else if (position.column() == lines()[position.line()].length())
  817. rect.set_x(content_x_for_position({ position.line(), lines()[position.line()].length() }) + 2);
  818. scroll_into_view(rect, true, true);
  819. }
  820. void GTextEditor::scroll_cursor_into_view()
  821. {
  822. scroll_position_into_view(m_cursor);
  823. }
  824. Rect GTextEditor::line_content_rect(int line_index) const
  825. {
  826. auto& line = lines()[line_index];
  827. if (is_single_line()) {
  828. Rect line_rect = { content_x_for_position({ line_index, 0 }), 0, line.length() * glyph_width(), font().glyph_height() + 2 };
  829. line_rect.center_vertically_within({ {}, frame_inner_rect().size() });
  830. return line_rect;
  831. }
  832. if (is_line_wrapping_enabled())
  833. return m_line_visual_data[line_index].visual_rect;
  834. return {
  835. content_x_for_position({ line_index, 0 }),
  836. line_index * line_height(),
  837. line.length() * glyph_width(),
  838. line_height()
  839. };
  840. }
  841. void GTextEditor::update_cursor()
  842. {
  843. update(line_widget_rect(m_cursor.line()));
  844. }
  845. void GTextEditor::update_undo_timer()
  846. {
  847. if (m_undo_stack.is_empty())
  848. return;
  849. auto& undo_vector = m_undo_stack[0].m_undo_vector;
  850. if (undo_vector.size() == m_last_updated_undo_vector_size && !undo_vector.is_empty()) {
  851. auto undo_commands_container = make<UndoCommandsContainer>();
  852. m_undo_stack.prepend(move(undo_commands_container));
  853. // Note: Remove dbg() if we're 100% sure there are no bugs left.
  854. dbg() << "Undo stack increased to " << m_undo_stack.size();
  855. // Shift the index to the left since we're adding an empty container.
  856. if (m_undo_stack_index > 0)
  857. m_undo_stack_index++;
  858. }
  859. m_last_updated_undo_vector_size = undo_vector.size();
  860. }
  861. void GTextEditor::set_cursor(int line, int column)
  862. {
  863. set_cursor({ line, column });
  864. }
  865. void GTextEditor::set_cursor(const GTextPosition& a_position)
  866. {
  867. ASSERT(!lines().is_empty());
  868. GTextPosition position = a_position;
  869. if (position.line() >= lines().size())
  870. position.set_line(lines().size() - 1);
  871. if (position.column() > lines()[position.line()].length())
  872. position.set_column(lines()[position.line()].length());
  873. if (m_cursor != position) {
  874. // NOTE: If the old cursor is no longer valid, repaint everything just in case.
  875. auto old_cursor_line_rect = m_cursor.line() < lines().size()
  876. ? line_widget_rect(m_cursor.line())
  877. : rect();
  878. m_cursor = position;
  879. m_cursor_state = true;
  880. scroll_cursor_into_view();
  881. update(old_cursor_line_rect);
  882. update_cursor();
  883. }
  884. if (on_cursor_change)
  885. on_cursor_change();
  886. }
  887. void GTextEditor::focusin_event(CEvent&)
  888. {
  889. update_cursor();
  890. start_timer(500);
  891. }
  892. void GTextEditor::focusout_event(CEvent&)
  893. {
  894. stop_timer();
  895. }
  896. void GTextEditor::timer_event(CTimerEvent&)
  897. {
  898. m_cursor_state = !m_cursor_state;
  899. if (is_focused())
  900. update_cursor();
  901. }
  902. bool GTextEditor::write_to_file(const StringView& path)
  903. {
  904. int fd = open_with_path_length(path.characters_without_null_termination(), path.length(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
  905. if (fd < 0) {
  906. perror("open");
  907. return false;
  908. }
  909. // Compute the final file size and ftruncate() to make writing fast.
  910. // FIXME: Remove this once the kernel is smart enough to do this instead.
  911. off_t file_size = 0;
  912. for (int i = 0; i < lines().size(); ++i)
  913. file_size += lines()[i].length();
  914. file_size += lines().size() - 1;
  915. int rc = ftruncate(fd, file_size);
  916. if (rc < 0) {
  917. perror("ftruncate");
  918. return false;
  919. }
  920. for (int i = 0; i < lines().size(); ++i) {
  921. auto& line = lines()[i];
  922. if (line.length()) {
  923. ssize_t nwritten = write(fd, line.characters(), line.length());
  924. if (nwritten < 0) {
  925. perror("write");
  926. close(fd);
  927. return false;
  928. }
  929. }
  930. if (i != lines().size() - 1) {
  931. char ch = '\n';
  932. ssize_t nwritten = write(fd, &ch, 1);
  933. if (nwritten != 1) {
  934. perror("write");
  935. close(fd);
  936. return false;
  937. }
  938. }
  939. }
  940. close(fd);
  941. return true;
  942. }
  943. String GTextEditor::text() const
  944. {
  945. StringBuilder builder;
  946. for (int i = 0; i < line_count(); ++i) {
  947. auto& line = lines()[i];
  948. builder.append(line.characters(), line.length());
  949. if (i != line_count() - 1)
  950. builder.append('\n');
  951. }
  952. return builder.to_string();
  953. }
  954. void GTextEditor::clear()
  955. {
  956. document().remove_all_lines();
  957. document().append_line(make<GTextDocumentLine>(document()));
  958. m_selection.clear();
  959. did_update_selection();
  960. set_cursor(0, 0);
  961. update();
  962. }
  963. String GTextEditor::selected_text() const
  964. {
  965. if (!has_selection())
  966. return {};
  967. return document().text_in_range(m_selection);
  968. }
  969. void GTextEditor::delete_selection()
  970. {
  971. if (!has_selection())
  972. return;
  973. auto selection = normalized_selection();
  974. // First delete all the lines in between the first and last one.
  975. for (int i = selection.start().line() + 1; i < selection.end().line();) {
  976. int row = i;
  977. int column = lines()[i].length();
  978. add_to_undo_stack(make<RemoveLineCommand>(*this, String(lines()[i].view()), GTextPosition(row, column), false));
  979. document().remove_line(i);
  980. selection.end().set_line(selection.end().line() - 1);
  981. }
  982. if (selection.start().line() == selection.end().line()) {
  983. // Delete within same line.
  984. auto& line = lines()[selection.start().line()];
  985. bool whole_line_is_selected = selection.start().column() == 0 && selection.end().column() == line.length();
  986. for (int i = selection.end().column() - 1; i >= selection.start().column(); i--) {
  987. int row = selection.start().line();
  988. int column = i;
  989. add_to_undo_stack(make<RemoveCharacterCommand>(*this, document().line(row).characters()[column], GTextPosition(row, column)));
  990. }
  991. if (whole_line_is_selected) {
  992. line.clear(document());
  993. } else {
  994. auto before_selection = String(line.characters(), line.length()).substring(0, selection.start().column());
  995. auto after_selection = String(line.characters(), line.length()).substring(selection.end().column(), line.length() - selection.end().column());
  996. StringBuilder builder(before_selection.length() + after_selection.length());
  997. builder.append(before_selection);
  998. builder.append(after_selection);
  999. line.set_text(document(), builder.to_string());
  1000. }
  1001. } else {
  1002. // Delete across a newline, merging lines.
  1003. ASSERT(selection.start().line() == selection.end().line() - 1);
  1004. auto& first_line = lines()[selection.start().line()];
  1005. auto& second_line = lines()[selection.end().line()];
  1006. auto before_selection = String(first_line.characters(), first_line.length()).substring(0, selection.start().column());
  1007. auto after_selection = String(second_line.characters(), second_line.length()).substring(selection.end().column(), second_line.length() - selection.end().column());
  1008. StringBuilder builder(before_selection.length() + after_selection.length());
  1009. builder.append(before_selection);
  1010. builder.append(after_selection);
  1011. for (int i = first_line.length() - 1; i > selection.start().column() - 1; i--) {
  1012. int row = selection.start().line();
  1013. int column = i;
  1014. add_to_undo_stack(make<RemoveCharacterCommand>(*this, document().line(row).characters()[column], GTextPosition(row, column)));
  1015. }
  1016. add_to_undo_stack(make<RemoveLineCommand>(*this, String(second_line.view()), selection.end(), false));
  1017. first_line.set_text(document(), builder.to_string());
  1018. document().remove_line(selection.end().line());
  1019. for (int i = (first_line.length()) - after_selection.length(); i < first_line.length(); i++)
  1020. add_to_undo_stack(make<InsertCharacterCommand>(*this, first_line.characters()[i], GTextPosition(selection.start().line(), i + 1)));
  1021. }
  1022. if (lines().is_empty()) {
  1023. document().append_line(make<GTextDocumentLine>(document()));
  1024. }
  1025. m_selection.clear();
  1026. did_update_selection();
  1027. did_change();
  1028. set_cursor(selection.start());
  1029. update();
  1030. }
  1031. void GTextEditor::insert_at_cursor_or_replace_selection(const StringView& text)
  1032. {
  1033. ASSERT(!is_readonly());
  1034. if (has_selection())
  1035. delete_selection();
  1036. insert_at_cursor(text);
  1037. }
  1038. void GTextEditor::cut()
  1039. {
  1040. if (is_readonly())
  1041. return;
  1042. auto selected_text = this->selected_text();
  1043. printf("Cut: \"%s\"\n", selected_text.characters());
  1044. GClipboard::the().set_data(selected_text);
  1045. delete_selection();
  1046. }
  1047. void GTextEditor::copy()
  1048. {
  1049. auto selected_text = this->selected_text();
  1050. printf("Copy: \"%s\"\n", selected_text.characters());
  1051. GClipboard::the().set_data(selected_text);
  1052. }
  1053. void GTextEditor::paste()
  1054. {
  1055. if (is_readonly())
  1056. return;
  1057. auto paste_text = GClipboard::the().data();
  1058. printf("Paste: \"%s\"\n", paste_text.characters());
  1059. insert_at_cursor_or_replace_selection(paste_text);
  1060. }
  1061. void GTextEditor::enter_event(CEvent&)
  1062. {
  1063. ASSERT(window());
  1064. window()->set_override_cursor(GStandardCursor::IBeam);
  1065. }
  1066. void GTextEditor::leave_event(CEvent&)
  1067. {
  1068. ASSERT(window());
  1069. window()->set_override_cursor(GStandardCursor::None);
  1070. }
  1071. void GTextEditor::did_change()
  1072. {
  1073. ASSERT(!is_readonly());
  1074. update_content_size();
  1075. recompute_all_visual_lines();
  1076. if (!m_has_pending_change_notification) {
  1077. m_has_pending_change_notification = true;
  1078. deferred_invoke([this](auto&) {
  1079. if (!m_has_pending_change_notification)
  1080. return;
  1081. if (on_change)
  1082. on_change();
  1083. m_has_pending_change_notification = false;
  1084. });
  1085. }
  1086. }
  1087. void GTextEditor::set_readonly(bool readonly)
  1088. {
  1089. if (m_readonly == readonly)
  1090. return;
  1091. m_readonly = readonly;
  1092. m_cut_action->set_enabled(!is_readonly() && has_selection());
  1093. m_delete_action->set_enabled(!is_readonly());
  1094. m_paste_action->set_enabled(!is_readonly());
  1095. }
  1096. void GTextEditor::did_update_selection()
  1097. {
  1098. m_cut_action->set_enabled(!is_readonly() && has_selection());
  1099. m_copy_action->set_enabled(has_selection());
  1100. if (on_selection_change)
  1101. on_selection_change();
  1102. if (is_line_wrapping_enabled()) {
  1103. // FIXME: Try to repaint less.
  1104. update();
  1105. }
  1106. }
  1107. void GTextEditor::context_menu_event(GContextMenuEvent& event)
  1108. {
  1109. if (!m_context_menu) {
  1110. m_context_menu = make<GMenu>();
  1111. m_context_menu->add_action(undo_action());
  1112. m_context_menu->add_action(redo_action());
  1113. m_context_menu->add_separator();
  1114. m_context_menu->add_action(cut_action());
  1115. m_context_menu->add_action(copy_action());
  1116. m_context_menu->add_action(paste_action());
  1117. m_context_menu->add_action(delete_action());
  1118. if (!m_custom_context_menu_actions.is_empty()) {
  1119. m_context_menu->add_separator();
  1120. for (auto& action : m_custom_context_menu_actions) {
  1121. m_context_menu->add_action(action);
  1122. }
  1123. }
  1124. }
  1125. m_context_menu->popup(event.screen_position());
  1126. }
  1127. void GTextEditor::set_text_alignment(TextAlignment alignment)
  1128. {
  1129. if (m_text_alignment == alignment)
  1130. return;
  1131. m_text_alignment = alignment;
  1132. update();
  1133. }
  1134. void GTextEditor::resize_event(GResizeEvent& event)
  1135. {
  1136. GScrollableWidget::resize_event(event);
  1137. update_content_size();
  1138. recompute_all_visual_lines();
  1139. }
  1140. void GTextEditor::set_selection(const GTextRange& selection)
  1141. {
  1142. if (m_selection == selection)
  1143. return;
  1144. m_selection = selection;
  1145. set_cursor(m_selection.end());
  1146. scroll_position_into_view(normalized_selection().start());
  1147. update();
  1148. }
  1149. void GTextEditor::recompute_all_visual_lines()
  1150. {
  1151. int y_offset = 0;
  1152. for (int line_index = 0; line_index < line_count(); ++line_index) {
  1153. recompute_visual_lines(line_index);
  1154. m_line_visual_data[line_index].visual_rect.set_y(y_offset);
  1155. y_offset += m_line_visual_data[line_index].visual_rect.height();
  1156. }
  1157. update_content_size();
  1158. }
  1159. void GTextEditor::ensure_cursor_is_valid()
  1160. {
  1161. if (cursor().column() > lines()[cursor().line()].length())
  1162. set_cursor(cursor().line(), cursor().column() - (lines()[cursor().line()].length() - cursor().column()));
  1163. }
  1164. void GTextEditor::add_to_undo_stack(NonnullOwnPtr<UndoCommand> undo_command)
  1165. {
  1166. if (m_undo_stack.is_empty()) {
  1167. auto undo_commands_container = make<UndoCommandsContainer>();
  1168. m_undo_stack.prepend(move(undo_commands_container));
  1169. }
  1170. // Clear the elements of the stack before the m_undo_stack_index (Excluding our new element)
  1171. for (int i = 1; i < m_undo_stack_index; i++)
  1172. m_undo_stack.remove(1);
  1173. if (m_undo_stack_index > 0 && !m_undo_stack.is_empty())
  1174. m_undo_stack[0].m_undo_vector.clear();
  1175. m_undo_stack_index = 0;
  1176. m_undo_stack[0].m_undo_vector.prepend(move(undo_command));
  1177. }
  1178. int GTextEditor::visual_line_containing(int line_index, int column) const
  1179. {
  1180. int visual_line_index = 0;
  1181. for_each_visual_line(line_index, [&](const Rect&, const StringView& view, int start_of_visual_line) {
  1182. if (column >= start_of_visual_line && ((column - start_of_visual_line) < view.length()))
  1183. return IterationDecision::Break;
  1184. ++visual_line_index;
  1185. return IterationDecision::Continue;
  1186. });
  1187. return visual_line_index;
  1188. }
  1189. void GTextEditor::recompute_visual_lines(int line_index)
  1190. {
  1191. auto& line = document().line(line_index);
  1192. auto& visual_data = m_line_visual_data[line_index];
  1193. visual_data.visual_line_breaks.clear_with_capacity();
  1194. int available_width = visible_text_rect_in_inner_coordinates().width();
  1195. if (is_line_wrapping_enabled()) {
  1196. int line_width_so_far = 0;
  1197. for (int i = 0; i < line.length(); ++i) {
  1198. auto ch = line.characters()[i];
  1199. auto glyph_width = font().glyph_width(ch);
  1200. if ((line_width_so_far + glyph_width) > available_width) {
  1201. visual_data.visual_line_breaks.append(i);
  1202. line_width_so_far = glyph_width;
  1203. continue;
  1204. }
  1205. line_width_so_far += glyph_width;
  1206. }
  1207. }
  1208. visual_data.visual_line_breaks.append(line.length());
  1209. if (is_line_wrapping_enabled())
  1210. visual_data.visual_rect = { m_horizontal_content_padding, 0, available_width, visual_data.visual_line_breaks.size() * line_height() };
  1211. else
  1212. visual_data.visual_rect = { m_horizontal_content_padding, 0, font().width(line.view()), line_height() };
  1213. }
  1214. template<typename Callback>
  1215. void GTextEditor::for_each_visual_line(int line_index, Callback callback) const
  1216. {
  1217. auto editor_visible_text_rect = visible_text_rect_in_inner_coordinates();
  1218. int start_of_line = 0;
  1219. int visual_line_index = 0;
  1220. auto& line = document().line(line_index);
  1221. auto& visual_data = m_line_visual_data[line_index];
  1222. for (auto visual_line_break : visual_data.visual_line_breaks) {
  1223. auto visual_line_view = StringView(line.characters() + start_of_line, visual_line_break - start_of_line);
  1224. Rect visual_line_rect {
  1225. visual_data.visual_rect.x(),
  1226. visual_data.visual_rect.y() + (visual_line_index * line_height()),
  1227. font().width(visual_line_view),
  1228. line_height()
  1229. };
  1230. if (is_right_text_alignment(text_alignment()))
  1231. visual_line_rect.set_right_without_resize(editor_visible_text_rect.right());
  1232. if (!is_multi_line())
  1233. visual_line_rect.center_vertically_within(editor_visible_text_rect);
  1234. if (callback(visual_line_rect, visual_line_view, start_of_line) == IterationDecision::Break)
  1235. break;
  1236. start_of_line = visual_line_break;
  1237. ++visual_line_index;
  1238. }
  1239. }
  1240. void GTextEditor::set_line_wrapping_enabled(bool enabled)
  1241. {
  1242. if (m_line_wrapping_enabled == enabled)
  1243. return;
  1244. m_line_wrapping_enabled = enabled;
  1245. horizontal_scrollbar().set_visible(!m_line_wrapping_enabled);
  1246. update_content_size();
  1247. recompute_all_visual_lines();
  1248. update();
  1249. }
  1250. void GTextEditor::add_custom_context_menu_action(GAction& action)
  1251. {
  1252. m_custom_context_menu_actions.append(action);
  1253. }
  1254. void GTextEditor::did_change_font()
  1255. {
  1256. vertical_scrollbar().set_step(line_height());
  1257. GWidget::did_change_font();
  1258. }
  1259. void GTextEditor::document_did_append_line()
  1260. {
  1261. m_line_visual_data.append(make<LineVisualData>());
  1262. recompute_all_visual_lines();
  1263. update();
  1264. }
  1265. void GTextEditor::document_did_remove_line(int line_index)
  1266. {
  1267. m_line_visual_data.remove(line_index);
  1268. recompute_all_visual_lines();
  1269. update();
  1270. }
  1271. void GTextEditor::document_did_remove_all_lines()
  1272. {
  1273. m_line_visual_data.clear();
  1274. recompute_all_visual_lines();
  1275. update();
  1276. }
  1277. void GTextEditor::document_did_insert_line(int line_index)
  1278. {
  1279. m_line_visual_data.insert(line_index, make<LineVisualData>());
  1280. recompute_all_visual_lines();
  1281. update();
  1282. }
  1283. void GTextEditor::document_did_change()
  1284. {
  1285. recompute_all_visual_lines();
  1286. update();
  1287. }
  1288. void GTextEditor::set_document(GTextDocument& document)
  1289. {
  1290. if (m_document.ptr() == &document)
  1291. return;
  1292. if (m_document)
  1293. m_document->unregister_client(*this);
  1294. m_document = document;
  1295. m_line_visual_data.clear();
  1296. for (int i = 0; i < m_document->line_count(); ++i) {
  1297. m_line_visual_data.append(make<LineVisualData>());
  1298. }
  1299. m_cursor = { 0, 0 };
  1300. recompute_all_visual_lines();
  1301. update();
  1302. m_document->register_client(*this);
  1303. }
  1304. GTextEditor::UndoCommand::UndoCommand(GTextEditor& text_editor)
  1305. : m_text_editor(text_editor)
  1306. {
  1307. }
  1308. GTextEditor::UndoCommand::~UndoCommand()
  1309. {
  1310. }
  1311. void GTextEditor::UndoCommand::undo() {}
  1312. void GTextEditor::UndoCommand::redo() {}
  1313. GTextEditor::InsertCharacterCommand::InsertCharacterCommand(GTextEditor& text_editor, char ch, GTextPosition text_position)
  1314. : UndoCommand(text_editor)
  1315. , m_character(ch)
  1316. , m_text_position(text_position)
  1317. {
  1318. }
  1319. GTextEditor::RemoveCharacterCommand::RemoveCharacterCommand(GTextEditor& text_editor, char ch, GTextPosition text_position)
  1320. : UndoCommand(text_editor)
  1321. , m_character(ch)
  1322. , m_text_position(text_position)
  1323. {
  1324. }
  1325. GTextEditor::RemoveLineCommand::RemoveLineCommand(GTextEditor& text_editor, String line_content, GTextPosition text_position, bool has_merged_content)
  1326. : UndoCommand(text_editor)
  1327. , m_line_content(line_content)
  1328. , m_text_position(text_position)
  1329. , m_has_merged_content(has_merged_content)
  1330. {
  1331. }
  1332. GTextEditor::CreateLineCommand::CreateLineCommand(GTextEditor& text_editor, Vector<char> line_content, GTextPosition text_position)
  1333. : UndoCommand(text_editor)
  1334. , m_line_content(line_content)
  1335. , m_text_position(text_position)
  1336. {
  1337. }
  1338. void GTextEditor::InsertCharacterCommand::undo()
  1339. {
  1340. m_text_editor.lines()[m_text_position.line()].remove(m_text_editor.document(), (m_text_position.column() - 1));
  1341. m_text_editor.ensure_cursor_is_valid();
  1342. }
  1343. void GTextEditor::InsertCharacterCommand::redo()
  1344. {
  1345. m_text_editor.lines()[m_text_position.line()].insert(m_text_editor.document(), m_text_position.column() - 1, m_character);
  1346. }
  1347. void GTextEditor::RemoveCharacterCommand::undo()
  1348. {
  1349. m_text_editor.lines()[m_text_position.line()].insert(m_text_editor.document(), m_text_position.column(), m_character);
  1350. }
  1351. void GTextEditor::RemoveCharacterCommand::redo()
  1352. {
  1353. m_text_editor.lines()[m_text_position.line()].remove(m_text_editor.document(), (m_text_position.column()));
  1354. m_text_editor.ensure_cursor_is_valid();
  1355. }
  1356. void GTextEditor::RemoveLineCommand::undo()
  1357. {
  1358. // Insert back the line
  1359. m_text_editor.document().insert_line(m_text_position.line(), make<GTextDocumentLine>(m_text_editor.document(), m_line_content));
  1360. // Remove the merged line contents
  1361. if (m_has_merged_content) {
  1362. for (int i = m_line_content.length() - 1; i >= 0; i--)
  1363. m_text_editor.document().lines()[m_text_position.line() - 1].remove(m_text_editor.document(), (m_text_position.column()) + i);
  1364. }
  1365. }
  1366. void GTextEditor::RemoveLineCommand::redo()
  1367. {
  1368. // Remove the created line
  1369. m_text_editor.document().remove_line(m_text_position.line());
  1370. // Add back the line contents
  1371. if (m_has_merged_content) {
  1372. for (int i = 0; i < m_line_content.length(); i++)
  1373. m_text_editor.document().lines()[m_text_position.line() - 1].insert(m_text_editor.document(), (m_text_position.column()) + i, m_line_content[i]);
  1374. }
  1375. }
  1376. void GTextEditor::CreateLineCommand::undo()
  1377. {
  1378. // Insert back the created line portion
  1379. for (int i = 0; i < m_line_content.size(); i++)
  1380. m_text_editor.document().lines()[m_text_position.line()].insert(m_text_editor.document(), (m_text_position.column() - 1) + i, m_line_content[i]);
  1381. // Move the cursor up a row back before the split.
  1382. m_text_editor.set_cursor(m_text_position.line(), m_text_editor.document().lines()[m_text_position.line()].length());
  1383. // Remove the created line
  1384. m_text_editor.document().remove_line(m_text_position.line() + 1);
  1385. }
  1386. void GTextEditor::CreateLineCommand::redo()
  1387. {
  1388. // Remove the characters that we're inserted back
  1389. for (int i = m_line_content.size() - 1; i >= 0; i--)
  1390. m_text_editor.document().lines()[m_text_position.line()].remove(m_text_editor.document(), (m_text_position.column()) + i);
  1391. m_text_editor.ensure_cursor_is_valid();
  1392. // Then we want to add BACK the created line
  1393. m_text_editor.document().insert_line(m_text_position.line() + 1, make<GTextDocumentLine>(m_text_editor.document(), ""));
  1394. for (int i = 0; i < m_line_content.size(); i++)
  1395. m_text_editor.document().lines()[m_text_position.line() + 1].insert(m_text_editor.document(), i, m_line_content[i]);
  1396. }
  1397. void GTextEditor::flush_pending_change_notification_if_needed()
  1398. {
  1399. if (!m_has_pending_change_notification)
  1400. return;
  1401. if (on_change)
  1402. on_change();
  1403. m_has_pending_change_notification = false;
  1404. }