TextEditor.cpp 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/QuickSort.h>
  27. #include <AK/StringBuilder.h>
  28. #include <Kernel/KeyCode.h>
  29. #include <LibGUI/Action.h>
  30. #include <LibGUI/Clipboard.h>
  31. #include <LibGUI/FontDatabase.h>
  32. #include <LibGUI/InputBox.h>
  33. #include <LibGUI/Menu.h>
  34. #include <LibGUI/Painter.h>
  35. #include <LibGUI/ScrollBar.h>
  36. #include <LibGUI/SyntaxHighlighter.h>
  37. #include <LibGUI/TextEditor.h>
  38. #include <LibGUI/Window.h>
  39. #include <LibGfx/Palette.h>
  40. #include <ctype.h>
  41. #include <fcntl.h>
  42. #include <stdio.h>
  43. #include <unistd.h>
  44. //#define DEBUG_GTEXTEDITOR
  45. namespace GUI {
  46. TextEditor::TextEditor(Widget* parent)
  47. : TextEditor(Type::MultiLine, parent)
  48. {
  49. }
  50. TextEditor::TextEditor(Type type, Widget* parent)
  51. : ScrollableWidget(parent)
  52. , m_type(type)
  53. {
  54. set_background_role(ColorRole::Base);
  55. set_foreground_role(ColorRole::BaseText);
  56. set_document(TextDocument::create());
  57. set_frame_shape(Gfx::FrameShape::Container);
  58. set_frame_shadow(Gfx::FrameShadow::Sunken);
  59. set_frame_thickness(2);
  60. set_scrollbars_enabled(is_multi_line());
  61. set_font(GFontDatabase::the().get_by_name("Csilla Thin"));
  62. // FIXME: Recompute vertical scrollbar step size on font change.
  63. vertical_scrollbar().set_step(line_height());
  64. m_cursor = { 0, 0 };
  65. create_actions();
  66. }
  67. TextEditor::~TextEditor()
  68. {
  69. if (m_document)
  70. m_document->unregister_client(*this);
  71. }
  72. void TextEditor::create_actions()
  73. {
  74. m_undo_action = CommonActions::make_undo_action([&](auto&) { undo(); }, this);
  75. m_redo_action = CommonActions::make_redo_action([&](auto&) { redo(); }, this);
  76. m_undo_action->set_enabled(false);
  77. m_redo_action->set_enabled(false);
  78. m_cut_action = CommonActions::make_cut_action([&](auto&) { cut(); }, this);
  79. m_copy_action = CommonActions::make_copy_action([&](auto&) { copy(); }, this);
  80. m_paste_action = CommonActions::make_paste_action([&](auto&) { paste(); }, this);
  81. m_delete_action = CommonActions::make_delete_action([&](auto&) { do_delete(); }, this);
  82. if (is_multi_line()) {
  83. m_go_to_line_action = Action::create(
  84. "Go to line...", { Mod_Ctrl, Key_L }, Gfx::Bitmap::load_from_file("/res/icons/16x16/go-forward.png"), [this](auto&) {
  85. auto input_box = InputBox::construct("Line:", "Go to line", window());
  86. auto result = input_box->exec();
  87. if (result == InputBox::ExecOK) {
  88. bool ok;
  89. auto line_number = input_box->text_value().to_uint(ok);
  90. if (ok)
  91. set_cursor(line_number - 1, 0);
  92. }
  93. },
  94. this);
  95. }
  96. }
  97. void TextEditor::set_text(const StringView& text)
  98. {
  99. if (is_single_line() && text.length() == line(0).length() && !memcmp(text.characters_without_null_termination(), line(0).characters(), text.length()))
  100. return;
  101. m_selection.clear();
  102. document().set_text(text);
  103. update_content_size();
  104. recompute_all_visual_lines();
  105. if (is_single_line())
  106. set_cursor(0, line(0).length());
  107. else
  108. set_cursor(0, 0);
  109. did_update_selection();
  110. update();
  111. }
  112. void TextEditor::update_content_size()
  113. {
  114. int content_width = 0;
  115. int content_height = 0;
  116. for (auto& line : m_line_visual_data) {
  117. content_width = max(line.visual_rect.width(), content_width);
  118. content_height += line.visual_rect.height();
  119. }
  120. content_width += m_horizontal_content_padding * 2;
  121. if (is_right_text_alignment(m_text_alignment))
  122. content_width = max(frame_inner_rect().width(), content_width);
  123. set_content_size({ content_width, content_height });
  124. set_size_occupied_by_fixed_elements({ ruler_width(), 0 });
  125. }
  126. TextPosition TextEditor::text_position_at(const Gfx::Point& a_position) const
  127. {
  128. auto position = a_position;
  129. position.move_by(horizontal_scrollbar().value(), vertical_scrollbar().value());
  130. position.move_by(-(m_horizontal_content_padding + ruler_width()), 0);
  131. position.move_by(-frame_thickness(), -frame_thickness());
  132. size_t line_index = 0;
  133. if (is_line_wrapping_enabled()) {
  134. for (size_t i = 0; i < line_count(); ++i) {
  135. auto& rect = m_line_visual_data[i].visual_rect;
  136. if (position.y() >= rect.top() && position.y() <= rect.bottom()) {
  137. line_index = i;
  138. break;
  139. }
  140. if (position.y() > rect.bottom())
  141. line_index = line_count() - 1;
  142. }
  143. } else {
  144. line_index = (size_t)(position.y() / line_height());
  145. }
  146. line_index = max((size_t)0, min(line_index, line_count() - 1));
  147. size_t column_index;
  148. switch (m_text_alignment) {
  149. case Gfx::TextAlignment::CenterLeft:
  150. column_index = (position.x() + glyph_width() / 2) / glyph_width();
  151. if (is_line_wrapping_enabled()) {
  152. for_each_visual_line(line_index, [&](const Gfx::Rect& rect, const StringView&, size_t start_of_line) {
  153. if (rect.contains_vertically(position.y())) {
  154. column_index += start_of_line;
  155. return IterationDecision::Break;
  156. }
  157. return IterationDecision::Continue;
  158. });
  159. }
  160. break;
  161. case Gfx::TextAlignment::CenterRight:
  162. // FIXME: Support right-aligned line wrapping, I guess.
  163. ASSERT(!is_line_wrapping_enabled());
  164. column_index = (position.x() - content_x_for_position({ line_index, 0 }) + glyph_width() / 2) / glyph_width();
  165. break;
  166. default:
  167. ASSERT_NOT_REACHED();
  168. }
  169. column_index = max((size_t)0, min(column_index, line(line_index).length()));
  170. return { line_index, column_index };
  171. }
  172. void TextEditor::doubleclick_event(MouseEvent& event)
  173. {
  174. if (event.button() != MouseButton::Left)
  175. return;
  176. // NOTE: This ensures that spans are updated before we look at them.
  177. flush_pending_change_notification_if_needed();
  178. m_triple_click_timer.start();
  179. m_in_drag_select = false;
  180. auto start = text_position_at(event.position());
  181. auto end = start;
  182. auto& line = this->line(start.line());
  183. if (!document().has_spans()) {
  184. while (start.column() > 0) {
  185. if (isspace(line.characters()[start.column() - 1]))
  186. break;
  187. start.set_column(start.column() - 1);
  188. }
  189. while (end.column() < line.length()) {
  190. if (isspace(line.characters()[end.column()]))
  191. break;
  192. end.set_column(end.column() + 1);
  193. }
  194. } else {
  195. for (auto& span : document().spans()) {
  196. if (!span.range.contains(start))
  197. continue;
  198. start = span.range.start();
  199. end = span.range.end();
  200. end.set_column(end.column() + 1);
  201. break;
  202. }
  203. }
  204. m_selection.set(start, end);
  205. set_cursor(end);
  206. update();
  207. did_update_selection();
  208. }
  209. void TextEditor::mousedown_event(MouseEvent& event)
  210. {
  211. if (event.button() != MouseButton::Left) {
  212. return;
  213. }
  214. if (m_triple_click_timer.is_valid() && m_triple_click_timer.elapsed() < 250) {
  215. m_triple_click_timer = Core::ElapsedTimer();
  216. TextPosition start;
  217. TextPosition end;
  218. if (is_multi_line()) {
  219. // select *current* line
  220. start = TextPosition(m_cursor.line(), 0);
  221. end = TextPosition(m_cursor.line(), line(m_cursor.line()).length());
  222. } else {
  223. // select *whole* line
  224. start = TextPosition(0, 0);
  225. end = TextPosition(line_count() - 1, line(line_count() - 1).length());
  226. }
  227. m_selection.set(start, end);
  228. set_cursor(end);
  229. return;
  230. }
  231. if (event.modifiers() & Mod_Shift) {
  232. if (!has_selection())
  233. m_selection.set(m_cursor, {});
  234. } else {
  235. m_selection.clear();
  236. }
  237. m_in_drag_select = true;
  238. set_cursor(text_position_at(event.position()));
  239. if (!(event.modifiers() & Mod_Shift)) {
  240. if (!has_selection())
  241. m_selection.set(m_cursor, {});
  242. }
  243. if (m_selection.start().is_valid() && m_selection.start() != m_cursor)
  244. m_selection.set_end(m_cursor);
  245. // FIXME: Only update the relevant rects.
  246. update();
  247. did_update_selection();
  248. }
  249. void TextEditor::mouseup_event(MouseEvent& event)
  250. {
  251. if (event.button() == MouseButton::Left) {
  252. if (m_in_drag_select) {
  253. m_in_drag_select = false;
  254. }
  255. return;
  256. }
  257. }
  258. void TextEditor::mousemove_event(MouseEvent& event)
  259. {
  260. if (m_in_drag_select) {
  261. set_cursor(text_position_at(event.position()));
  262. m_selection.set_end(m_cursor);
  263. did_update_selection();
  264. update();
  265. return;
  266. }
  267. }
  268. int TextEditor::ruler_width() const
  269. {
  270. if (!m_ruler_visible)
  271. return 0;
  272. // FIXME: Resize based on needed space.
  273. return 5 * font().glyph_width('x') + 4;
  274. }
  275. Gfx::Rect TextEditor::ruler_content_rect(size_t line_index) const
  276. {
  277. if (!m_ruler_visible)
  278. return {};
  279. return {
  280. 0 - ruler_width() + horizontal_scrollbar().value(),
  281. line_content_rect(line_index).y(),
  282. ruler_width(),
  283. line_content_rect(line_index).height()
  284. };
  285. }
  286. Gfx::Rect TextEditor::ruler_rect_in_inner_coordinates() const
  287. {
  288. return { 0, 0, ruler_width(), height() - height_occupied_by_horizontal_scrollbar() };
  289. }
  290. Gfx::Rect TextEditor::visible_text_rect_in_inner_coordinates() const
  291. {
  292. return {
  293. m_horizontal_content_padding + (m_ruler_visible ? (ruler_rect_in_inner_coordinates().right() + 1) : 0),
  294. 0,
  295. frame_inner_rect().width() - (m_horizontal_content_padding * 2) - width_occupied_by_vertical_scrollbar() - ruler_width(),
  296. frame_inner_rect().height() - height_occupied_by_horizontal_scrollbar()
  297. };
  298. }
  299. void TextEditor::paint_event(PaintEvent& event)
  300. {
  301. Color widget_background_color = palette().color(background_role());
  302. // NOTE: This ensures that spans are updated before we look at them.
  303. flush_pending_change_notification_if_needed();
  304. Frame::paint_event(event);
  305. Painter painter(*this);
  306. painter.add_clip_rect(widget_inner_rect());
  307. painter.add_clip_rect(event.rect());
  308. painter.fill_rect(event.rect(), widget_background_color);
  309. painter.translate(frame_thickness(), frame_thickness());
  310. auto ruler_rect = ruler_rect_in_inner_coordinates();
  311. if (m_ruler_visible) {
  312. painter.fill_rect(ruler_rect, widget_background_color.darkened(0.85f));
  313. painter.draw_line(ruler_rect.top_right(), ruler_rect.bottom_right(), widget_background_color.darkened(0.5f));
  314. }
  315. painter.translate(-horizontal_scrollbar().value(), -vertical_scrollbar().value());
  316. if (m_ruler_visible)
  317. painter.translate(ruler_width(), 0);
  318. size_t first_visible_line = text_position_at(event.rect().top_left()).line();
  319. size_t last_visible_line = text_position_at(event.rect().bottom_right()).line();
  320. auto selection = normalized_selection();
  321. bool has_selection = selection.is_valid();
  322. if (m_ruler_visible) {
  323. for (size_t i = first_visible_line; i <= last_visible_line; ++i) {
  324. bool is_current_line = i == m_cursor.line();
  325. auto ruler_line_rect = ruler_content_rect(i);
  326. painter.draw_text(
  327. ruler_line_rect.shrunken(2, 0).translated(0, m_line_spacing / 2),
  328. String::number(i + 1),
  329. is_current_line ? Gfx::Font::default_bold_font() : font(),
  330. Gfx::TextAlignment::TopRight,
  331. is_current_line ? widget_background_color.darkened(0.2f) : widget_background_color.darkened(0.4f));
  332. }
  333. }
  334. Gfx::Rect text_clip_rect {
  335. (m_ruler_visible ? (ruler_rect_in_inner_coordinates().right() + frame_thickness() + 1) : frame_thickness()),
  336. frame_thickness(),
  337. width() - width_occupied_by_vertical_scrollbar() - ruler_width(),
  338. height() - height_occupied_by_horizontal_scrollbar()
  339. };
  340. painter.add_clip_rect(text_clip_rect);
  341. for (size_t line_index = first_visible_line; line_index <= last_visible_line; ++line_index) {
  342. auto& line = this->line(line_index);
  343. bool physical_line_has_selection = has_selection && line_index >= selection.start().line() && line_index <= selection.end().line();
  344. size_t first_visual_line_with_selection = 0;
  345. size_t last_visual_line_with_selection = 0;
  346. if (physical_line_has_selection) {
  347. if (selection.start().line() < line_index)
  348. first_visual_line_with_selection = 0;
  349. else
  350. first_visual_line_with_selection = visual_line_containing(line_index, selection.start().column());
  351. if (selection.end().line() > line_index)
  352. last_visual_line_with_selection = m_line_visual_data[line_index].visual_line_breaks.size();
  353. else
  354. last_visual_line_with_selection = visual_line_containing(line_index, selection.end().column());
  355. }
  356. size_t selection_start_column_within_line = selection.start().line() == line_index ? selection.start().column() : 0;
  357. size_t selection_end_column_within_line = selection.end().line() == line_index ? selection.end().column() : line.length();
  358. size_t visual_line_index = 0;
  359. for_each_visual_line(line_index, [&](const Gfx::Rect& visual_line_rect, const StringView& visual_line_text, size_t start_of_visual_line) {
  360. if (is_multi_line() && line_index == m_cursor.line())
  361. painter.fill_rect(visual_line_rect, widget_background_color.darkened(0.9f));
  362. #ifdef DEBUG_GTEXTEDITOR
  363. painter.draw_rect(visual_line_rect, Color::Cyan);
  364. #endif
  365. if (!document().has_spans()) {
  366. // Fast-path for plain text
  367. painter.draw_text(visual_line_rect, visual_line_text, m_text_alignment, palette().color(foreground_role()));
  368. } else {
  369. int advance = font().glyph_width(' ') + font().glyph_spacing();
  370. Gfx::Rect character_rect = { visual_line_rect.location(), { font().glyph_width(' '), line_height() } };
  371. for (size_t i = 0; i < visual_line_text.length(); ++i) {
  372. const Gfx::Font* font = &this->font();
  373. Color color;
  374. Optional<Color> background_color;
  375. TextPosition physical_position(line_index, start_of_visual_line + i);
  376. // FIXME: This is *horribly* inefficient.
  377. for (auto& span : document().spans()) {
  378. if (!span.range.contains(physical_position))
  379. continue;
  380. color = span.color;
  381. if (span.font)
  382. font = span.font;
  383. background_color = span.background_color;
  384. break;
  385. }
  386. if (background_color.has_value())
  387. painter.fill_rect(character_rect, background_color.value());
  388. painter.draw_text(character_rect, visual_line_text.substring_view(i, 1), *font, m_text_alignment, color);
  389. character_rect.move_by(advance, 0);
  390. }
  391. }
  392. bool physical_line_has_selection = has_selection && line_index >= selection.start().line() && line_index <= selection.end().line();
  393. if (physical_line_has_selection) {
  394. bool current_visual_line_has_selection = (line_index != selection.start().line() && line_index != selection.end().line())
  395. || (visual_line_index >= first_visual_line_with_selection && visual_line_index <= last_visual_line_with_selection);
  396. if (current_visual_line_has_selection) {
  397. bool selection_begins_on_current_visual_line = visual_line_index == first_visual_line_with_selection;
  398. bool selection_ends_on_current_visual_line = visual_line_index == last_visual_line_with_selection;
  399. int selection_left = selection_begins_on_current_visual_line
  400. ? content_x_for_position({ line_index, (size_t)selection_start_column_within_line })
  401. : m_horizontal_content_padding;
  402. int selection_right = selection_ends_on_current_visual_line
  403. ? content_x_for_position({ line_index, (size_t)selection_end_column_within_line })
  404. : visual_line_rect.right() + 1;
  405. Gfx::Rect selection_rect {
  406. selection_left,
  407. visual_line_rect.y(),
  408. selection_right - selection_left,
  409. visual_line_rect.height()
  410. };
  411. painter.fill_rect(selection_rect, palette().selection());
  412. size_t start_of_selection_within_visual_line = (size_t)max(0, (int)selection_start_column_within_line - (int)start_of_visual_line);
  413. size_t end_of_selection_within_visual_line = selection_end_column_within_line - start_of_visual_line;
  414. StringView visual_selected_text {
  415. visual_line_text.characters_without_null_termination() + start_of_selection_within_visual_line,
  416. end_of_selection_within_visual_line - start_of_selection_within_visual_line
  417. };
  418. painter.draw_text(selection_rect, visual_selected_text, Gfx::TextAlignment::CenterLeft, palette().selection_text());
  419. }
  420. }
  421. ++visual_line_index;
  422. return IterationDecision::Continue;
  423. });
  424. }
  425. if (is_focused() && m_cursor_state)
  426. painter.fill_rect(cursor_content_rect(), Color::Red);
  427. }
  428. void TextEditor::toggle_selection_if_needed_for_event(const KeyEvent& event)
  429. {
  430. if (event.shift() && !m_selection.is_valid()) {
  431. m_selection.set(m_cursor, {});
  432. did_update_selection();
  433. update();
  434. return;
  435. }
  436. if (!event.shift() && m_selection.is_valid()) {
  437. m_selection.clear();
  438. did_update_selection();
  439. update();
  440. return;
  441. }
  442. }
  443. void TextEditor::select_all()
  444. {
  445. TextPosition start_of_document { 0, 0 };
  446. TextPosition end_of_document { line_count() - 1, line(line_count() - 1).length() };
  447. m_selection.set(start_of_document, end_of_document);
  448. did_update_selection();
  449. set_cursor(end_of_document);
  450. update();
  451. }
  452. void TextEditor::get_selection_line_boundaries(size_t& first_line, size_t& last_line)
  453. {
  454. auto selection = normalized_selection();
  455. if (!selection.is_valid()) {
  456. first_line = m_cursor.line();
  457. last_line = m_cursor.line();
  458. return;
  459. }
  460. first_line = selection.start().line();
  461. last_line = selection.end().line();
  462. if (first_line != last_line && selection.end().column() == 0)
  463. last_line -= 1;
  464. }
  465. void TextEditor::move_selected_lines_up()
  466. {
  467. size_t first_line;
  468. size_t last_line;
  469. get_selection_line_boundaries(first_line, last_line);
  470. if (first_line == 0)
  471. return;
  472. auto& lines = document().lines();
  473. lines.insert((int)last_line, lines.take((int)first_line - 1));
  474. m_cursor = { first_line - 1, 0 };
  475. if (has_selection()) {
  476. m_selection.set_start({ first_line - 1, 0 });
  477. m_selection.set_end({ last_line - 1, line(last_line - 1).length() });
  478. }
  479. did_change();
  480. update();
  481. }
  482. void TextEditor::move_selected_lines_down()
  483. {
  484. size_t first_line;
  485. size_t last_line;
  486. get_selection_line_boundaries(first_line, last_line);
  487. auto& lines = document().lines();
  488. if (last_line >= (size_t)(lines.size() - 1))
  489. return;
  490. lines.insert((int)first_line, lines.take((int)last_line + 1));
  491. m_cursor = { first_line + 1, 0 };
  492. if (has_selection()) {
  493. m_selection.set_start({ first_line + 1, 0 });
  494. m_selection.set_end({ last_line + 1, line(last_line + 1).length() });
  495. }
  496. did_change();
  497. update();
  498. }
  499. void TextEditor::sort_selected_lines()
  500. {
  501. if (is_readonly())
  502. return;
  503. if (!has_selection())
  504. return;
  505. size_t first_line;
  506. size_t last_line;
  507. get_selection_line_boundaries(first_line, last_line);
  508. auto& lines = document().lines();
  509. auto start = lines.begin() + (int)first_line;
  510. auto end = lines.begin() + (int)last_line + 1;
  511. quick_sort(start, end, [](auto& a, auto& b) {
  512. return strcmp(a.characters(), b.characters()) < 0;
  513. });
  514. did_change();
  515. update();
  516. }
  517. void TextEditor::keydown_event(KeyEvent& event)
  518. {
  519. if (is_single_line() && event.key() == KeyCode::Key_Tab)
  520. return Widget::keydown_event(event);
  521. if (is_single_line() && event.key() == KeyCode::Key_Return) {
  522. if (on_return_pressed)
  523. on_return_pressed();
  524. return;
  525. }
  526. if (event.key() == KeyCode::Key_Escape) {
  527. if (on_escape_pressed)
  528. on_escape_pressed();
  529. return;
  530. }
  531. if (event.key() == KeyCode::Key_Up) {
  532. if (m_cursor.line() > 0) {
  533. if (event.ctrl() && event.shift()) {
  534. move_selected_lines_up();
  535. return;
  536. }
  537. size_t new_line = m_cursor.line() - 1;
  538. size_t new_column = min(m_cursor.column(), line(new_line).length());
  539. toggle_selection_if_needed_for_event(event);
  540. set_cursor(new_line, new_column);
  541. if (event.shift() && m_selection.start().is_valid()) {
  542. m_selection.set_end(m_cursor);
  543. did_update_selection();
  544. }
  545. }
  546. return;
  547. }
  548. if (event.key() == KeyCode::Key_Down) {
  549. if (m_cursor.line() < (line_count() - 1)) {
  550. if (event.ctrl() && event.shift()) {
  551. move_selected_lines_down();
  552. return;
  553. }
  554. size_t new_line = m_cursor.line() + 1;
  555. size_t new_column = min(m_cursor.column(), line(new_line).length());
  556. toggle_selection_if_needed_for_event(event);
  557. set_cursor(new_line, new_column);
  558. if (event.shift() && m_selection.start().is_valid()) {
  559. m_selection.set_end(m_cursor);
  560. did_update_selection();
  561. }
  562. }
  563. return;
  564. }
  565. if (event.key() == KeyCode::Key_PageUp) {
  566. if (m_cursor.line() > 0) {
  567. size_t page_step = (size_t)visible_content_rect().height() / (size_t)line_height();
  568. size_t new_line = m_cursor.line() < page_step ? 0 : m_cursor.line() - page_step;
  569. size_t new_column = min(m_cursor.column(), line(new_line).length());
  570. toggle_selection_if_needed_for_event(event);
  571. set_cursor(new_line, new_column);
  572. if (event.shift() && m_selection.start().is_valid()) {
  573. m_selection.set_end(m_cursor);
  574. did_update_selection();
  575. }
  576. }
  577. return;
  578. }
  579. if (event.key() == KeyCode::Key_PageDown) {
  580. if (m_cursor.line() < (line_count() - 1)) {
  581. int new_line = min(line_count() - 1, m_cursor.line() + visible_content_rect().height() / line_height());
  582. int new_column = min(m_cursor.column(), lines()[new_line].length());
  583. toggle_selection_if_needed_for_event(event);
  584. set_cursor(new_line, new_column);
  585. if (event.shift() && m_selection.start().is_valid()) {
  586. m_selection.set_end(m_cursor);
  587. did_update_selection();
  588. }
  589. }
  590. return;
  591. }
  592. if (event.key() == KeyCode::Key_Left) {
  593. if (event.ctrl() && document().has_spans()) {
  594. // FIXME: Do something nice when the document has no spans.
  595. auto span = document().first_non_skippable_span_before(m_cursor);
  596. TextPosition new_cursor = !span.has_value()
  597. ? TextPosition(0, 0)
  598. : span.value().range.start();
  599. toggle_selection_if_needed_for_event(event);
  600. set_cursor(new_cursor);
  601. if (event.shift() && m_selection.start().is_valid()) {
  602. m_selection.set_end(m_cursor);
  603. did_update_selection();
  604. }
  605. return;
  606. }
  607. if (m_cursor.column() > 0) {
  608. int new_column = m_cursor.column() - 1;
  609. toggle_selection_if_needed_for_event(event);
  610. set_cursor(m_cursor.line(), new_column);
  611. if (event.shift() && m_selection.start().is_valid()) {
  612. m_selection.set_end(m_cursor);
  613. did_update_selection();
  614. }
  615. } else if (m_cursor.line() > 0) {
  616. int new_line = m_cursor.line() - 1;
  617. int new_column = lines()[new_line].length();
  618. toggle_selection_if_needed_for_event(event);
  619. set_cursor(new_line, new_column);
  620. if (event.shift() && m_selection.start().is_valid()) {
  621. m_selection.set_end(m_cursor);
  622. did_update_selection();
  623. }
  624. }
  625. return;
  626. }
  627. if (event.key() == KeyCode::Key_Right) {
  628. if (event.ctrl() && document().has_spans()) {
  629. // FIXME: Do something nice when the document has no spans.
  630. auto span = document().first_non_skippable_span_after(m_cursor);
  631. TextPosition new_cursor = !span.has_value()
  632. ? document().spans().last().range.end()
  633. : span.value().range.start();
  634. toggle_selection_if_needed_for_event(event);
  635. set_cursor(new_cursor);
  636. if (event.shift() && m_selection.start().is_valid()) {
  637. m_selection.set_end(m_cursor);
  638. did_update_selection();
  639. }
  640. return;
  641. }
  642. int new_line = m_cursor.line();
  643. int new_column = m_cursor.column();
  644. if (m_cursor.column() < current_line().length()) {
  645. new_line = m_cursor.line();
  646. new_column = m_cursor.column() + 1;
  647. } else if (m_cursor.line() != line_count() - 1) {
  648. new_line = m_cursor.line() + 1;
  649. new_column = 0;
  650. }
  651. toggle_selection_if_needed_for_event(event);
  652. set_cursor(new_line, new_column);
  653. if (event.shift() && m_selection.start().is_valid()) {
  654. m_selection.set_end(m_cursor);
  655. did_update_selection();
  656. }
  657. return;
  658. }
  659. if (!event.ctrl() && event.key() == KeyCode::Key_Home) {
  660. size_t first_nonspace_column = current_line().first_non_whitespace_column();
  661. toggle_selection_if_needed_for_event(event);
  662. if (m_cursor.column() == first_nonspace_column)
  663. set_cursor(m_cursor.line(), 0);
  664. else
  665. set_cursor(m_cursor.line(), first_nonspace_column);
  666. if (event.shift() && m_selection.start().is_valid()) {
  667. m_selection.set_end(m_cursor);
  668. did_update_selection();
  669. }
  670. return;
  671. }
  672. if (!event.ctrl() && event.key() == KeyCode::Key_End) {
  673. toggle_selection_if_needed_for_event(event);
  674. set_cursor(m_cursor.line(), current_line().length());
  675. if (event.shift() && m_selection.start().is_valid()) {
  676. m_selection.set_end(m_cursor);
  677. did_update_selection();
  678. }
  679. return;
  680. }
  681. if (event.ctrl() && event.key() == KeyCode::Key_Home) {
  682. toggle_selection_if_needed_for_event(event);
  683. set_cursor(0, 0);
  684. if (event.shift() && m_selection.start().is_valid()) {
  685. m_selection.set_end(m_cursor);
  686. did_update_selection();
  687. }
  688. return;
  689. }
  690. if (event.ctrl() && event.key() == KeyCode::Key_End) {
  691. toggle_selection_if_needed_for_event(event);
  692. set_cursor(line_count() - 1, lines()[line_count() - 1].length());
  693. if (event.shift() && m_selection.start().is_valid()) {
  694. m_selection.set_end(m_cursor);
  695. did_update_selection();
  696. }
  697. return;
  698. }
  699. if (event.modifiers() == Mod_Ctrl && event.key() == KeyCode::Key_A) {
  700. select_all();
  701. return;
  702. }
  703. if (event.alt() && event.shift() && event.key() == KeyCode::Key_S) {
  704. sort_selected_lines();
  705. return;
  706. }
  707. if (event.key() == KeyCode::Key_Backspace) {
  708. if (is_readonly())
  709. return;
  710. if (has_selection()) {
  711. delete_selection();
  712. did_update_selection();
  713. return;
  714. }
  715. if (m_cursor.column() > 0) {
  716. int erase_count = 1;
  717. if (current_line().first_non_whitespace_column() >= m_cursor.column()) {
  718. int new_column;
  719. if (m_cursor.column() % m_soft_tab_width == 0)
  720. new_column = m_cursor.column() - m_soft_tab_width;
  721. else
  722. new_column = (m_cursor.column() / m_soft_tab_width) * m_soft_tab_width;
  723. erase_count = m_cursor.column() - new_column;
  724. }
  725. // Backspace within line
  726. TextRange erased_range({ m_cursor.line(), m_cursor.column() - erase_count }, m_cursor);
  727. auto erased_text = document().text_in_range(erased_range);
  728. execute<RemoveTextCommand>(erased_text, erased_range);
  729. return;
  730. }
  731. if (m_cursor.column() == 0 && m_cursor.line() != 0) {
  732. // Backspace at column 0; merge with previous line
  733. size_t previous_length = line(m_cursor.line() - 1).length();
  734. TextRange erased_range({ m_cursor.line() - 1, previous_length }, m_cursor);
  735. execute<RemoveTextCommand>("\n", erased_range);
  736. return;
  737. }
  738. return;
  739. }
  740. if (event.modifiers() == Mod_Shift && event.key() == KeyCode::Key_Delete) {
  741. if (is_readonly())
  742. return;
  743. delete_current_line();
  744. return;
  745. }
  746. if (event.key() == KeyCode::Key_Delete) {
  747. if (is_readonly())
  748. return;
  749. do_delete();
  750. return;
  751. }
  752. if (!is_readonly() && !event.ctrl() && !event.alt() && !event.text().is_empty())
  753. insert_at_cursor_or_replace_selection(event.text());
  754. }
  755. void TextEditor::delete_current_line()
  756. {
  757. if (has_selection())
  758. return delete_selection();
  759. TextPosition start;
  760. TextPosition end;
  761. if (m_cursor.line() == 0 && line_count() == 1) {
  762. start = { 0, 0 };
  763. end = { 0, line(0).length() };
  764. } else if (m_cursor.line() == line_count() - 1) {
  765. start = { m_cursor.line() - 1, line(m_cursor.line()).length() };
  766. end = { m_cursor.line(), line(m_cursor.line()).length() };
  767. } else {
  768. start = { m_cursor.line(), 0 };
  769. end = { m_cursor.line() + 1, 0 };
  770. }
  771. TextRange erased_range(start, end);
  772. execute<RemoveTextCommand>(document().text_in_range(erased_range), erased_range);
  773. }
  774. void TextEditor::do_delete()
  775. {
  776. if (is_readonly())
  777. return;
  778. if (has_selection())
  779. return delete_selection();
  780. if (m_cursor.column() < current_line().length()) {
  781. // Delete within line
  782. TextRange erased_range(m_cursor, { m_cursor.line(), m_cursor.column() + 1 });
  783. execute<RemoveTextCommand>(document().text_in_range(erased_range), erased_range);
  784. return;
  785. }
  786. if (m_cursor.column() == current_line().length() && m_cursor.line() != line_count() - 1) {
  787. // Delete at end of line; merge with next line
  788. TextRange erased_range(m_cursor, { m_cursor.line() + 1, 0 });
  789. execute<RemoveTextCommand>(document().text_in_range(erased_range), erased_range);
  790. return;
  791. }
  792. }
  793. int TextEditor::content_x_for_position(const TextPosition& position) const
  794. {
  795. auto& line = this->line(position.line());
  796. int x_offset = -1;
  797. switch (m_text_alignment) {
  798. case Gfx::TextAlignment::CenterLeft:
  799. for_each_visual_line(position.line(), [&](const Gfx::Rect&, const StringView& view, size_t start_of_visual_line) {
  800. if (position.column() >= start_of_visual_line && ((position.column() - start_of_visual_line) <= view.length())) {
  801. x_offset = (position.column() - start_of_visual_line) * glyph_width();
  802. return IterationDecision::Break;
  803. }
  804. return IterationDecision::Continue;
  805. });
  806. return m_horizontal_content_padding + x_offset;
  807. case Gfx::TextAlignment::CenterRight:
  808. // FIXME
  809. ASSERT(!is_line_wrapping_enabled());
  810. return content_width() - m_horizontal_content_padding - (line.length() * glyph_width()) + (position.column() * glyph_width());
  811. default:
  812. ASSERT_NOT_REACHED();
  813. }
  814. }
  815. Gfx::Rect TextEditor::content_rect_for_position(const TextPosition& position) const
  816. {
  817. if (!position.is_valid())
  818. return {};
  819. ASSERT(!lines().is_empty());
  820. ASSERT(position.column() <= (current_line().length() + 1));
  821. int x = content_x_for_position(position);
  822. if (is_single_line()) {
  823. Gfx::Rect rect { x, 0, 1, font().glyph_height() + 2 };
  824. rect.center_vertically_within({ {}, frame_inner_rect().size() });
  825. return rect;
  826. }
  827. Gfx::Rect rect;
  828. for_each_visual_line(position.line(), [&](const Gfx::Rect& visual_line_rect, const StringView& view, size_t start_of_visual_line) {
  829. if (position.column() >= start_of_visual_line && ((position.column() - start_of_visual_line) <= view.length())) {
  830. // NOTE: We have to subtract the horizontal padding here since it's part of the visual line rect
  831. // *and* included in what we get from content_x_for_position().
  832. rect = {
  833. visual_line_rect.x() + x - (m_horizontal_content_padding),
  834. visual_line_rect.y(),
  835. 1,
  836. line_height()
  837. };
  838. return IterationDecision::Break;
  839. }
  840. return IterationDecision::Continue;
  841. });
  842. return rect;
  843. }
  844. Gfx::Rect TextEditor::cursor_content_rect() const
  845. {
  846. return content_rect_for_position(m_cursor);
  847. }
  848. Gfx::Rect TextEditor::line_widget_rect(size_t line_index) const
  849. {
  850. auto rect = line_content_rect(line_index);
  851. rect.set_x(frame_thickness());
  852. rect.set_width(frame_inner_rect().width());
  853. rect.move_by(0, -(vertical_scrollbar().value()));
  854. rect.move_by(0, frame_thickness());
  855. rect.intersect(frame_inner_rect());
  856. return rect;
  857. }
  858. void TextEditor::scroll_position_into_view(const TextPosition& position)
  859. {
  860. auto rect = content_rect_for_position(position);
  861. if (position.column() == 0)
  862. rect.set_x(content_x_for_position({ position.line(), 0 }) - 2);
  863. else if (position.column() == line(position.line()).length())
  864. rect.set_x(content_x_for_position({ position.line(), line(position.line()).length() }) + 2);
  865. scroll_into_view(rect, true, true);
  866. }
  867. void TextEditor::scroll_cursor_into_view()
  868. {
  869. scroll_position_into_view(m_cursor);
  870. }
  871. Gfx::Rect TextEditor::line_content_rect(size_t line_index) const
  872. {
  873. auto& line = this->line(line_index);
  874. if (is_single_line()) {
  875. Gfx::Rect line_rect = { content_x_for_position({ line_index, 0 }), 0, (int)line.length() * glyph_width(), font().glyph_height() + 2 };
  876. line_rect.center_vertically_within({ {}, frame_inner_rect().size() });
  877. return line_rect;
  878. }
  879. if (is_line_wrapping_enabled())
  880. return m_line_visual_data[line_index].visual_rect;
  881. return {
  882. content_x_for_position({ line_index, 0 }),
  883. (int)line_index * line_height(),
  884. (int)line.length() * glyph_width(),
  885. line_height()
  886. };
  887. }
  888. void TextEditor::update_cursor()
  889. {
  890. update(line_widget_rect(m_cursor.line()));
  891. }
  892. void TextEditor::set_cursor(size_t line, size_t column)
  893. {
  894. set_cursor({ line, column });
  895. }
  896. void TextEditor::set_cursor(const TextPosition& a_position)
  897. {
  898. ASSERT(!lines().is_empty());
  899. TextPosition position = a_position;
  900. if (position.line() >= line_count())
  901. position.set_line(line_count() - 1);
  902. if (position.column() > lines()[position.line()].length())
  903. position.set_column(lines()[position.line()].length());
  904. if (m_cursor != position) {
  905. // NOTE: If the old cursor is no longer valid, repaint everything just in case.
  906. auto old_cursor_line_rect = m_cursor.line() < line_count()
  907. ? line_widget_rect(m_cursor.line())
  908. : rect();
  909. m_cursor = position;
  910. m_cursor_state = true;
  911. scroll_cursor_into_view();
  912. update(old_cursor_line_rect);
  913. update_cursor();
  914. }
  915. cursor_did_change();
  916. if (on_cursor_change)
  917. on_cursor_change();
  918. if (m_highlighter)
  919. m_highlighter->cursor_did_change();
  920. }
  921. void TextEditor::focusin_event(Core::Event&)
  922. {
  923. update_cursor();
  924. start_timer(500);
  925. }
  926. void TextEditor::focusout_event(Core::Event&)
  927. {
  928. stop_timer();
  929. }
  930. void TextEditor::timer_event(Core::TimerEvent&)
  931. {
  932. m_cursor_state = !m_cursor_state;
  933. if (is_focused())
  934. update_cursor();
  935. }
  936. bool TextEditor::write_to_file(const StringView& path)
  937. {
  938. int fd = open_with_path_length(path.characters_without_null_termination(), path.length(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
  939. if (fd < 0) {
  940. perror("open");
  941. return false;
  942. }
  943. // Compute the final file size and ftruncate() to make writing fast.
  944. // FIXME: Remove this once the kernel is smart enough to do this instead.
  945. off_t file_size = 0;
  946. for (size_t i = 0; i < line_count(); ++i)
  947. file_size += line(i).length();
  948. file_size += line_count() - 1;
  949. int rc = ftruncate(fd, file_size);
  950. if (rc < 0) {
  951. perror("ftruncate");
  952. return false;
  953. }
  954. for (size_t i = 0; i < line_count(); ++i) {
  955. auto& line = this->line(i);
  956. if (line.length()) {
  957. ssize_t nwritten = write(fd, line.characters(), line.length());
  958. if (nwritten < 0) {
  959. perror("write");
  960. close(fd);
  961. return false;
  962. }
  963. }
  964. if (i != line_count() - 1) {
  965. char ch = '\n';
  966. ssize_t nwritten = write(fd, &ch, 1);
  967. if (nwritten != 1) {
  968. perror("write");
  969. close(fd);
  970. return false;
  971. }
  972. }
  973. }
  974. close(fd);
  975. return true;
  976. }
  977. String TextEditor::text() const
  978. {
  979. StringBuilder builder;
  980. for (size_t i = 0; i < line_count(); ++i) {
  981. auto& line = this->line(i);
  982. builder.append(line.characters(), line.length());
  983. if (i != line_count() - 1)
  984. builder.append('\n');
  985. }
  986. return builder.to_string();
  987. }
  988. void TextEditor::clear()
  989. {
  990. document().remove_all_lines();
  991. document().append_line(make<TextDocumentLine>(document()));
  992. m_selection.clear();
  993. did_update_selection();
  994. set_cursor(0, 0);
  995. update();
  996. }
  997. String TextEditor::selected_text() const
  998. {
  999. if (!has_selection())
  1000. return {};
  1001. return document().text_in_range(m_selection);
  1002. }
  1003. void TextEditor::delete_selection()
  1004. {
  1005. auto selection = normalized_selection();
  1006. execute<RemoveTextCommand>(selected_text(), selection);
  1007. m_selection.clear();
  1008. did_update_selection();
  1009. did_change();
  1010. set_cursor(selection.start());
  1011. update();
  1012. }
  1013. void TextEditor::insert_at_cursor_or_replace_selection(const StringView& text)
  1014. {
  1015. ASSERT(!is_readonly());
  1016. if (has_selection())
  1017. delete_selection();
  1018. execute<InsertTextCommand>(text, m_cursor);
  1019. }
  1020. void TextEditor::cut()
  1021. {
  1022. if (is_readonly())
  1023. return;
  1024. auto selected_text = this->selected_text();
  1025. printf("Cut: \"%s\"\n", selected_text.characters());
  1026. Clipboard::the().set_data(selected_text);
  1027. delete_selection();
  1028. }
  1029. void TextEditor::copy()
  1030. {
  1031. auto selected_text = this->selected_text();
  1032. printf("Copy: \"%s\"\n", selected_text.characters());
  1033. Clipboard::the().set_data(selected_text);
  1034. }
  1035. void TextEditor::paste()
  1036. {
  1037. if (is_readonly())
  1038. return;
  1039. auto paste_text = Clipboard::the().data();
  1040. printf("Paste: \"%s\"\n", paste_text.characters());
  1041. TemporaryChange change(m_automatic_indentation_enabled, false);
  1042. insert_at_cursor_or_replace_selection(paste_text);
  1043. }
  1044. void TextEditor::enter_event(Core::Event&)
  1045. {
  1046. ASSERT(window());
  1047. window()->set_override_cursor(StandardCursor::IBeam);
  1048. }
  1049. void TextEditor::leave_event(Core::Event&)
  1050. {
  1051. ASSERT(window());
  1052. window()->set_override_cursor(StandardCursor::None);
  1053. }
  1054. void TextEditor::did_change()
  1055. {
  1056. update_content_size();
  1057. recompute_all_visual_lines();
  1058. m_undo_action->set_enabled(can_undo());
  1059. m_redo_action->set_enabled(can_redo());
  1060. if (!m_has_pending_change_notification) {
  1061. m_has_pending_change_notification = true;
  1062. deferred_invoke([this](auto&) {
  1063. if (!m_has_pending_change_notification)
  1064. return;
  1065. if (on_change)
  1066. on_change();
  1067. if (m_highlighter)
  1068. m_highlighter->rehighlight();
  1069. m_has_pending_change_notification = false;
  1070. });
  1071. }
  1072. }
  1073. void TextEditor::set_readonly(bool readonly)
  1074. {
  1075. if (m_readonly == readonly)
  1076. return;
  1077. m_readonly = readonly;
  1078. m_cut_action->set_enabled(!is_readonly() && has_selection());
  1079. m_delete_action->set_enabled(!is_readonly());
  1080. m_paste_action->set_enabled(!is_readonly());
  1081. }
  1082. void TextEditor::did_update_selection()
  1083. {
  1084. m_cut_action->set_enabled(!is_readonly() && has_selection());
  1085. m_copy_action->set_enabled(has_selection());
  1086. if (on_selection_change)
  1087. on_selection_change();
  1088. if (is_line_wrapping_enabled()) {
  1089. // FIXME: Try to repaint less.
  1090. update();
  1091. }
  1092. }
  1093. void TextEditor::context_menu_event(ContextMenuEvent& event)
  1094. {
  1095. if (!m_context_menu) {
  1096. m_context_menu = Menu::construct();
  1097. m_context_menu->add_action(undo_action());
  1098. m_context_menu->add_action(redo_action());
  1099. m_context_menu->add_separator();
  1100. m_context_menu->add_action(cut_action());
  1101. m_context_menu->add_action(copy_action());
  1102. m_context_menu->add_action(paste_action());
  1103. m_context_menu->add_action(delete_action());
  1104. if (is_multi_line()) {
  1105. m_context_menu->add_separator();
  1106. m_context_menu->add_action(go_to_line_action());
  1107. }
  1108. if (!m_custom_context_menu_actions.is_empty()) {
  1109. m_context_menu->add_separator();
  1110. for (auto& action : m_custom_context_menu_actions) {
  1111. m_context_menu->add_action(action);
  1112. }
  1113. }
  1114. }
  1115. m_context_menu->popup(event.screen_position());
  1116. }
  1117. void TextEditor::set_text_alignment(Gfx::TextAlignment alignment)
  1118. {
  1119. if (m_text_alignment == alignment)
  1120. return;
  1121. m_text_alignment = alignment;
  1122. update();
  1123. }
  1124. void TextEditor::resize_event(ResizeEvent& event)
  1125. {
  1126. ScrollableWidget::resize_event(event);
  1127. update_content_size();
  1128. recompute_all_visual_lines();
  1129. }
  1130. void TextEditor::set_selection(const TextRange& selection)
  1131. {
  1132. if (m_selection == selection)
  1133. return;
  1134. m_selection = selection;
  1135. set_cursor(m_selection.end());
  1136. scroll_position_into_view(normalized_selection().start());
  1137. update();
  1138. }
  1139. void TextEditor::clear_selection()
  1140. {
  1141. if (!has_selection())
  1142. return;
  1143. m_selection.clear();
  1144. update();
  1145. }
  1146. void TextEditor::recompute_all_visual_lines()
  1147. {
  1148. int y_offset = 0;
  1149. for (size_t line_index = 0; line_index < line_count(); ++line_index) {
  1150. recompute_visual_lines(line_index);
  1151. m_line_visual_data[line_index].visual_rect.set_y(y_offset);
  1152. y_offset += m_line_visual_data[line_index].visual_rect.height();
  1153. }
  1154. update_content_size();
  1155. }
  1156. void TextEditor::ensure_cursor_is_valid()
  1157. {
  1158. auto new_cursor = m_cursor;
  1159. if (new_cursor.line() >= line_count())
  1160. new_cursor.set_line(line_count() - 1);
  1161. if (new_cursor.column() > line(new_cursor.line()).length())
  1162. new_cursor.set_column(line(new_cursor.line()).length());
  1163. if (m_cursor != new_cursor)
  1164. set_cursor(new_cursor);
  1165. }
  1166. size_t TextEditor::visual_line_containing(size_t line_index, size_t column) const
  1167. {
  1168. size_t visual_line_index = 0;
  1169. for_each_visual_line(line_index, [&](const Gfx::Rect&, const StringView& view, size_t 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 TextEditor::recompute_visual_lines(size_t 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 (size_t 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 TextEditor::for_each_visual_line(size_t line_index, Callback callback) const
  1204. {
  1205. auto editor_visible_text_rect = visible_text_rect_in_inner_coordinates();
  1206. size_t start_of_line = 0;
  1207. size_t 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. Gfx::Rect visual_line_rect {
  1213. visual_data.visual_rect.x(),
  1214. visual_data.visual_rect.y() + ((int)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 TextEditor::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 TextEditor::add_custom_context_menu_action(Action& action)
  1239. {
  1240. m_custom_context_menu_actions.append(action);
  1241. }
  1242. void TextEditor::did_change_font()
  1243. {
  1244. vertical_scrollbar().set_step(line_height());
  1245. recompute_all_visual_lines();
  1246. update();
  1247. Widget::did_change_font();
  1248. }
  1249. void TextEditor::document_did_append_line()
  1250. {
  1251. m_line_visual_data.append(make<LineVisualData>());
  1252. recompute_all_visual_lines();
  1253. update();
  1254. }
  1255. void TextEditor::document_did_remove_line(size_t line_index)
  1256. {
  1257. m_line_visual_data.remove(line_index);
  1258. recompute_all_visual_lines();
  1259. update();
  1260. }
  1261. void TextEditor::document_did_remove_all_lines()
  1262. {
  1263. m_line_visual_data.clear();
  1264. recompute_all_visual_lines();
  1265. update();
  1266. }
  1267. void TextEditor::document_did_insert_line(size_t line_index)
  1268. {
  1269. m_line_visual_data.insert(line_index, make<LineVisualData>());
  1270. recompute_all_visual_lines();
  1271. update();
  1272. }
  1273. void TextEditor::document_did_change()
  1274. {
  1275. did_change();
  1276. update();
  1277. }
  1278. void TextEditor::document_did_set_text()
  1279. {
  1280. m_line_visual_data.clear();
  1281. for (size_t i = 0; i < m_document->line_count(); ++i)
  1282. m_line_visual_data.append(make<LineVisualData>());
  1283. document_did_change();
  1284. }
  1285. void TextEditor::document_did_set_cursor(const TextPosition& position)
  1286. {
  1287. set_cursor(position);
  1288. }
  1289. void TextEditor::set_document(TextDocument& document)
  1290. {
  1291. if (m_document.ptr() == &document)
  1292. return;
  1293. if (m_document)
  1294. m_document->unregister_client(*this);
  1295. m_document = document;
  1296. m_line_visual_data.clear();
  1297. for (size_t i = 0; i < m_document->line_count(); ++i) {
  1298. m_line_visual_data.append(make<LineVisualData>());
  1299. }
  1300. m_cursor = { 0, 0 };
  1301. if (has_selection())
  1302. m_selection.clear();
  1303. recompute_all_visual_lines();
  1304. update();
  1305. m_document->register_client(*this);
  1306. }
  1307. void TextEditor::flush_pending_change_notification_if_needed()
  1308. {
  1309. if (!m_has_pending_change_notification)
  1310. return;
  1311. if (on_change)
  1312. on_change();
  1313. if (m_highlighter)
  1314. m_highlighter->rehighlight();
  1315. m_has_pending_change_notification = false;
  1316. }
  1317. void TextEditor::set_syntax_highlighter(OwnPtr<SyntaxHighlighter> highlighter)
  1318. {
  1319. if (m_highlighter)
  1320. m_highlighter->detach();
  1321. m_highlighter = move(highlighter);
  1322. if (m_highlighter) {
  1323. m_highlighter->attach(*this);
  1324. m_highlighter->rehighlight();
  1325. }
  1326. }
  1327. }