GTextEditor.cpp 49 KB

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