TextEditor.cpp 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616
  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 <LibCore/Timer.h>
  30. #include <LibGUI/Action.h>
  31. #include <LibGUI/Clipboard.h>
  32. #include <LibGUI/FontDatabase.h>
  33. #include <LibGUI/InputBox.h>
  34. #include <LibGUI/Menu.h>
  35. #include <LibGUI/Painter.h>
  36. #include <LibGUI/ScrollBar.h>
  37. #include <LibGUI/SyntaxHighlighter.h>
  38. #include <LibGUI/TextEditor.h>
  39. #include <LibGUI/Window.h>
  40. #include <LibGfx/Bitmap.h>
  41. #include <LibGfx/Font.h>
  42. #include <LibGfx/Palette.h>
  43. #include <ctype.h>
  44. #include <fcntl.h>
  45. #include <stdio.h>
  46. #include <unistd.h>
  47. //#define DEBUG_TEXTEDITOR
  48. namespace GUI {
  49. TextEditor::TextEditor(Type type)
  50. : m_type(type)
  51. {
  52. set_accepts_emoji_input(true);
  53. set_background_role(ColorRole::Base);
  54. set_foreground_role(ColorRole::BaseText);
  55. set_document(TextDocument::create());
  56. set_scrollbars_enabled(is_multi_line());
  57. if (is_multi_line())
  58. set_font(Gfx::Font::default_fixed_width_font());
  59. vertical_scrollbar().set_step(line_height());
  60. m_cursor = { 0, 0 };
  61. m_automatic_selection_scroll_timer = add<Core::Timer>(100, [this] {
  62. automatic_selection_scroll_timer_fired();
  63. });
  64. m_automatic_selection_scroll_timer->stop();
  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. m_select_all_action = Action::create(
  97. "Select all", { Mod_Ctrl, Key_A }, Gfx::Bitmap::load_from_file("/res/icons/16x16/select-all.png"), [this](auto&) { select_all(); }, this);
  98. }
  99. void TextEditor::set_text(const StringView& text)
  100. {
  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 = 0;
  148. switch (m_text_alignment) {
  149. case Gfx::TextAlignment::CenterLeft:
  150. for_each_visual_line(line_index, [&](const Gfx::Rect& rect, auto& view, size_t start_of_line) {
  151. if (is_multi_line() && !rect.contains_vertically(position.y()))
  152. return IterationDecision::Continue;
  153. column_index = start_of_line;
  154. if (position.x() <= 0) {
  155. // We're outside the text on the left side, put cursor at column 0 on this visual line.
  156. } else {
  157. int glyph_x = 0;
  158. size_t i = 0;
  159. for (; i < view.length(); ++i) {
  160. int advance = font().glyph_width(view.codepoints()[i]) + font().glyph_spacing();
  161. if ((glyph_x + (advance / 2)) >= position.x())
  162. break;
  163. glyph_x += advance;
  164. }
  165. column_index += i;
  166. }
  167. return IterationDecision::Break;
  168. });
  169. break;
  170. case Gfx::TextAlignment::CenterRight:
  171. // FIXME: Support right-aligned line wrapping, I guess.
  172. ASSERT(!is_line_wrapping_enabled());
  173. column_index = (position.x() - content_x_for_position({ line_index, 0 }) + fixed_glyph_width() / 2) / fixed_glyph_width();
  174. break;
  175. default:
  176. ASSERT_NOT_REACHED();
  177. }
  178. column_index = max((size_t)0, min(column_index, line(line_index).length()));
  179. return { line_index, column_index };
  180. }
  181. void TextEditor::doubleclick_event(MouseEvent& event)
  182. {
  183. if (event.button() != MouseButton::Left)
  184. return;
  185. // NOTE: This ensures that spans are updated before we look at them.
  186. flush_pending_change_notification_if_needed();
  187. m_triple_click_timer.start();
  188. m_in_drag_select = false;
  189. auto start = text_position_at(event.position());
  190. auto end = start;
  191. if (!document().has_spans()) {
  192. start = document().first_word_break_before(start, false);
  193. end = document().first_word_break_after(end);
  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. m_automatic_selection_scroll_timer->start();
  239. set_cursor(text_position_at(event.position()));
  240. if (!(event.modifiers() & Mod_Shift)) {
  241. if (!has_selection())
  242. m_selection.set(m_cursor, {});
  243. }
  244. if (m_selection.start().is_valid() && m_selection.start() != m_cursor)
  245. m_selection.set_end(m_cursor);
  246. // FIXME: Only update the relevant rects.
  247. update();
  248. did_update_selection();
  249. }
  250. void TextEditor::mouseup_event(MouseEvent& event)
  251. {
  252. if (event.button() == MouseButton::Left) {
  253. if (m_in_drag_select) {
  254. m_in_drag_select = false;
  255. }
  256. return;
  257. }
  258. }
  259. void TextEditor::mousemove_event(MouseEvent& event)
  260. {
  261. m_last_mousemove_position = event.position();
  262. if (m_in_drag_select && (rect().contains(event.position()) || !m_automatic_selection_scroll_timer->is_active())) {
  263. set_cursor(text_position_at(event.position()));
  264. m_selection.set_end(m_cursor);
  265. did_update_selection();
  266. update();
  267. return;
  268. }
  269. }
  270. void TextEditor::automatic_selection_scroll_timer_fired()
  271. {
  272. if (!m_in_drag_select) {
  273. m_automatic_selection_scroll_timer->stop();
  274. return;
  275. }
  276. set_cursor(text_position_at(m_last_mousemove_position));
  277. m_selection.set_end(m_cursor);
  278. did_update_selection();
  279. update();
  280. }
  281. int TextEditor::ruler_width() const
  282. {
  283. if (!m_ruler_visible)
  284. return 0;
  285. // FIXME: Resize based on needed space.
  286. return 5 * font().glyph_width('x') + 4;
  287. }
  288. Gfx::Rect TextEditor::ruler_content_rect(size_t line_index) const
  289. {
  290. if (!m_ruler_visible)
  291. return {};
  292. return {
  293. 0 - ruler_width() + horizontal_scrollbar().value(),
  294. line_content_rect(line_index).y(),
  295. ruler_width(),
  296. line_content_rect(line_index).height()
  297. };
  298. }
  299. Gfx::Rect TextEditor::ruler_rect_in_inner_coordinates() const
  300. {
  301. return { 0, 0, ruler_width(), height() - height_occupied_by_horizontal_scrollbar() };
  302. }
  303. Gfx::Rect TextEditor::visible_text_rect_in_inner_coordinates() const
  304. {
  305. return {
  306. m_horizontal_content_padding + (m_ruler_visible ? (ruler_rect_in_inner_coordinates().right() + 1) : 0),
  307. 0,
  308. frame_inner_rect().width() - (m_horizontal_content_padding * 2) - width_occupied_by_vertical_scrollbar() - ruler_width(),
  309. frame_inner_rect().height() - height_occupied_by_horizontal_scrollbar()
  310. };
  311. }
  312. void TextEditor::paint_event(PaintEvent& event)
  313. {
  314. Color widget_background_color = palette().color(is_enabled() ? background_role() : Gfx::ColorRole::Window);
  315. // NOTE: This ensures that spans are updated before we look at them.
  316. flush_pending_change_notification_if_needed();
  317. Frame::paint_event(event);
  318. Painter painter(*this);
  319. painter.add_clip_rect(widget_inner_rect());
  320. painter.add_clip_rect(event.rect());
  321. painter.fill_rect(event.rect(), widget_background_color);
  322. painter.translate(frame_thickness(), frame_thickness());
  323. auto ruler_rect = ruler_rect_in_inner_coordinates();
  324. if (m_ruler_visible) {
  325. painter.fill_rect(ruler_rect, palette().ruler());
  326. painter.draw_line(ruler_rect.top_right(), ruler_rect.bottom_right(), palette().ruler_border());
  327. }
  328. painter.translate(-horizontal_scrollbar().value(), -vertical_scrollbar().value());
  329. if (m_ruler_visible)
  330. painter.translate(ruler_width(), 0);
  331. size_t first_visible_line = text_position_at(event.rect().top_left()).line();
  332. size_t last_visible_line = text_position_at(event.rect().bottom_right()).line();
  333. auto selection = normalized_selection();
  334. bool has_selection = selection.is_valid();
  335. if (m_ruler_visible) {
  336. for (size_t i = first_visible_line; i <= last_visible_line; ++i) {
  337. bool is_current_line = i == m_cursor.line();
  338. auto ruler_line_rect = ruler_content_rect(i);
  339. painter.draw_text(
  340. ruler_line_rect.shrunken(2, 0).translated(0, m_line_spacing / 2),
  341. String::number(i + 1),
  342. is_current_line ? Gfx::Font::default_bold_font() : font(),
  343. Gfx::TextAlignment::TopRight,
  344. is_current_line ? palette().ruler_active_text() : palette().ruler_inactive_text());
  345. }
  346. }
  347. Gfx::Rect text_clip_rect {
  348. (m_ruler_visible ? (ruler_rect_in_inner_coordinates().right() + frame_thickness() + 1) : frame_thickness()),
  349. frame_thickness(),
  350. width() - width_occupied_by_vertical_scrollbar() - ruler_width(),
  351. height() - height_occupied_by_horizontal_scrollbar()
  352. };
  353. if (m_ruler_visible)
  354. text_clip_rect.move_by(-ruler_width(), 0);
  355. text_clip_rect.move_by(horizontal_scrollbar().value(), vertical_scrollbar().value());
  356. painter.add_clip_rect(text_clip_rect);
  357. for (size_t line_index = first_visible_line; line_index <= last_visible_line; ++line_index) {
  358. auto& line = this->line(line_index);
  359. bool physical_line_has_selection = has_selection && line_index >= selection.start().line() && line_index <= selection.end().line();
  360. size_t first_visual_line_with_selection = 0;
  361. size_t last_visual_line_with_selection = 0;
  362. if (physical_line_has_selection) {
  363. if (selection.start().line() < line_index)
  364. first_visual_line_with_selection = 0;
  365. else
  366. first_visual_line_with_selection = visual_line_containing(line_index, selection.start().column());
  367. if (selection.end().line() > line_index)
  368. last_visual_line_with_selection = m_line_visual_data[line_index].visual_line_breaks.size();
  369. else
  370. last_visual_line_with_selection = visual_line_containing(line_index, selection.end().column());
  371. }
  372. size_t selection_start_column_within_line = selection.start().line() == line_index ? selection.start().column() : 0;
  373. size_t selection_end_column_within_line = selection.end().line() == line_index ? selection.end().column() : line.length();
  374. size_t visual_line_index = 0;
  375. for_each_visual_line(line_index, [&](const Gfx::Rect& visual_line_rect, auto& visual_line_text, size_t start_of_visual_line) {
  376. if (is_multi_line() && line_index == m_cursor.line())
  377. painter.fill_rect(visual_line_rect, widget_background_color.darkened(0.9f));
  378. #ifdef DEBUG_TEXTEDITOR
  379. painter.draw_rect(visual_line_rect, Color::Cyan);
  380. #endif
  381. if (!document().has_spans()) {
  382. // Fast-path for plain text
  383. auto color = palette().color(is_enabled() ? foreground_role() : Gfx::ColorRole::DisabledText);
  384. painter.draw_text(visual_line_rect, visual_line_text, m_text_alignment, color);
  385. } else {
  386. Gfx::Rect character_rect = { visual_line_rect.location(), { 0, line_height() } };
  387. for (size_t i = 0; i < visual_line_text.length(); ++i) {
  388. u32 codepoint = visual_line_text.substring_view(i, 1).codepoints()[0];
  389. const Gfx::Font* font = &this->font();
  390. Color color;
  391. Optional<Color> background_color;
  392. bool underline = false;
  393. TextPosition physical_position(line_index, start_of_visual_line + i);
  394. // FIXME: This is *horribly* inefficient.
  395. for (auto& span : document().spans()) {
  396. if (!span.range.contains(physical_position))
  397. continue;
  398. color = span.color;
  399. if (span.font)
  400. font = span.font;
  401. background_color = span.background_color;
  402. underline = span.is_underlined;
  403. break;
  404. }
  405. character_rect.set_width(font->glyph_width(codepoint) + font->glyph_spacing());
  406. if (background_color.has_value())
  407. painter.fill_rect(character_rect, background_color.value());
  408. painter.draw_text(character_rect, visual_line_text.substring_view(i, 1), *font, m_text_alignment, color);
  409. if (underline) {
  410. painter.draw_line(character_rect.bottom_left().translated(0, 1), character_rect.bottom_right().translated(0, 1), color);
  411. }
  412. character_rect.move_by(character_rect.width(), 0);
  413. }
  414. }
  415. if (physical_line_has_selection) {
  416. size_t start_of_selection_within_visual_line = (size_t)max(0, (int)selection_start_column_within_line - (int)start_of_visual_line);
  417. size_t end_of_selection_within_visual_line = selection_end_column_within_line - start_of_visual_line;
  418. bool current_visual_line_has_selection = start_of_selection_within_visual_line != end_of_selection_within_visual_line
  419. && ((line_index != selection.start().line() && line_index != selection.end().line())
  420. || (visual_line_index >= first_visual_line_with_selection && visual_line_index <= last_visual_line_with_selection));
  421. if (current_visual_line_has_selection) {
  422. bool selection_begins_on_current_visual_line = visual_line_index == first_visual_line_with_selection;
  423. bool selection_ends_on_current_visual_line = visual_line_index == last_visual_line_with_selection;
  424. int selection_left = selection_begins_on_current_visual_line
  425. ? content_x_for_position({ line_index, (size_t)selection_start_column_within_line })
  426. : m_horizontal_content_padding;
  427. int selection_right = selection_ends_on_current_visual_line
  428. ? content_x_for_position({ line_index, (size_t)selection_end_column_within_line })
  429. : visual_line_rect.right() + 1;
  430. Gfx::Rect selection_rect {
  431. selection_left,
  432. visual_line_rect.y(),
  433. selection_right - selection_left,
  434. visual_line_rect.height()
  435. };
  436. Color background_color = is_focused() ? palette().selection() : palette().inactive_selection();
  437. Color text_color = is_focused() ? palette().selection_text() : palette().inactive_selection_text();
  438. painter.fill_rect(selection_rect, background_color);
  439. if (visual_line_text.codepoints()) {
  440. Utf32View visual_selected_text {
  441. visual_line_text.codepoints() + start_of_selection_within_visual_line,
  442. end_of_selection_within_visual_line - start_of_selection_within_visual_line
  443. };
  444. painter.draw_text(selection_rect, visual_selected_text, Gfx::TextAlignment::CenterLeft, text_color);
  445. }
  446. }
  447. }
  448. ++visual_line_index;
  449. return IterationDecision::Continue;
  450. });
  451. }
  452. if (is_focused() && m_cursor_state)
  453. painter.fill_rect(cursor_content_rect(), palette().text_cursor());
  454. }
  455. void TextEditor::toggle_selection_if_needed_for_event(const KeyEvent& event)
  456. {
  457. if (event.shift() && !m_selection.is_valid()) {
  458. m_selection.set(m_cursor, {});
  459. did_update_selection();
  460. update();
  461. return;
  462. }
  463. if (!event.shift() && m_selection.is_valid()) {
  464. m_selection.clear();
  465. did_update_selection();
  466. update();
  467. return;
  468. }
  469. }
  470. void TextEditor::select_all()
  471. {
  472. TextPosition start_of_document { 0, 0 };
  473. TextPosition end_of_document { line_count() - 1, line(line_count() - 1).length() };
  474. m_selection.set(end_of_document, start_of_document);
  475. did_update_selection();
  476. set_cursor(start_of_document);
  477. update();
  478. }
  479. void TextEditor::get_selection_line_boundaries(size_t& first_line, size_t& last_line)
  480. {
  481. auto selection = normalized_selection();
  482. if (!selection.is_valid()) {
  483. first_line = m_cursor.line();
  484. last_line = m_cursor.line();
  485. return;
  486. }
  487. first_line = selection.start().line();
  488. last_line = selection.end().line();
  489. if (first_line != last_line && selection.end().column() == 0)
  490. last_line -= 1;
  491. }
  492. void TextEditor::move_selected_lines_up()
  493. {
  494. size_t first_line;
  495. size_t last_line;
  496. get_selection_line_boundaries(first_line, last_line);
  497. if (first_line == 0)
  498. return;
  499. auto& lines = document().lines();
  500. lines.insert((int)last_line, lines.take((int)first_line - 1));
  501. m_cursor = { first_line - 1, 0 };
  502. if (has_selection()) {
  503. m_selection.set_start({ first_line - 1, 0 });
  504. m_selection.set_end({ last_line - 1, line(last_line - 1).length() });
  505. }
  506. did_change();
  507. update();
  508. }
  509. void TextEditor::move_selected_lines_down()
  510. {
  511. size_t first_line;
  512. size_t last_line;
  513. get_selection_line_boundaries(first_line, last_line);
  514. auto& lines = document().lines();
  515. ASSERT(lines.size() != 0);
  516. if (last_line >= lines.size() - 1)
  517. return;
  518. lines.insert((int)first_line, lines.take((int)last_line + 1));
  519. m_cursor = { first_line + 1, 0 };
  520. if (has_selection()) {
  521. m_selection.set_start({ first_line + 1, 0 });
  522. m_selection.set_end({ last_line + 1, line(last_line + 1).length() });
  523. }
  524. did_change();
  525. update();
  526. }
  527. int strcmp_utf32(const u32* s1, const u32* s2, size_t n)
  528. {
  529. while (n-- > 0) {
  530. if (*s1++ != *s2++)
  531. return s1[-1] < s2[-1] ? -1 : 1;
  532. }
  533. return 0;
  534. }
  535. void TextEditor::sort_selected_lines()
  536. {
  537. if (is_readonly())
  538. return;
  539. if (!has_selection())
  540. return;
  541. size_t first_line;
  542. size_t last_line;
  543. get_selection_line_boundaries(first_line, last_line);
  544. auto& lines = document().lines();
  545. auto start = lines.begin() + (int)first_line;
  546. auto end = lines.begin() + (int)last_line + 1;
  547. quick_sort(start, end, [](auto& a, auto& b) {
  548. return strcmp_utf32(a.codepoints(), b.codepoints(), min(a.length(), b.length())) < 0;
  549. });
  550. did_change();
  551. update();
  552. }
  553. void TextEditor::keydown_event(KeyEvent& event)
  554. {
  555. if (is_single_line() && event.key() == KeyCode::Key_Tab)
  556. return Widget::keydown_event(event);
  557. if (is_single_line() && event.key() == KeyCode::Key_Return) {
  558. if (on_return_pressed)
  559. on_return_pressed();
  560. return;
  561. }
  562. if (event.key() == KeyCode::Key_Escape) {
  563. if (on_escape_pressed)
  564. on_escape_pressed();
  565. return;
  566. }
  567. if (is_multi_line() && event.key() == KeyCode::Key_Up) {
  568. if (m_cursor.line() > 0) {
  569. if (event.ctrl() && event.shift()) {
  570. move_selected_lines_up();
  571. return;
  572. }
  573. size_t new_line = m_cursor.line() - 1;
  574. size_t new_column = min(m_cursor.column(), line(new_line).length());
  575. toggle_selection_if_needed_for_event(event);
  576. set_cursor(new_line, new_column);
  577. if (event.shift() && m_selection.start().is_valid()) {
  578. m_selection.set_end(m_cursor);
  579. did_update_selection();
  580. }
  581. }
  582. return;
  583. }
  584. if (is_multi_line() && event.key() == KeyCode::Key_Down) {
  585. if (m_cursor.line() < (line_count() - 1)) {
  586. if (event.ctrl() && event.shift()) {
  587. move_selected_lines_down();
  588. return;
  589. }
  590. size_t new_line = m_cursor.line() + 1;
  591. size_t new_column = min(m_cursor.column(), line(new_line).length());
  592. toggle_selection_if_needed_for_event(event);
  593. set_cursor(new_line, new_column);
  594. if (event.shift() && m_selection.start().is_valid()) {
  595. m_selection.set_end(m_cursor);
  596. did_update_selection();
  597. }
  598. }
  599. return;
  600. }
  601. if (is_multi_line() && event.key() == KeyCode::Key_PageUp) {
  602. if (m_cursor.line() > 0) {
  603. size_t page_step = (size_t)visible_content_rect().height() / (size_t)line_height();
  604. size_t new_line = m_cursor.line() < page_step ? 0 : m_cursor.line() - page_step;
  605. size_t new_column = min(m_cursor.column(), line(new_line).length());
  606. toggle_selection_if_needed_for_event(event);
  607. set_cursor(new_line, new_column);
  608. if (event.shift() && m_selection.start().is_valid()) {
  609. m_selection.set_end(m_cursor);
  610. did_update_selection();
  611. }
  612. }
  613. return;
  614. }
  615. if (is_multi_line() && event.key() == KeyCode::Key_PageDown) {
  616. if (m_cursor.line() < (line_count() - 1)) {
  617. int new_line = min(line_count() - 1, m_cursor.line() + visible_content_rect().height() / line_height());
  618. int new_column = min(m_cursor.column(), lines()[new_line].length());
  619. toggle_selection_if_needed_for_event(event);
  620. set_cursor(new_line, new_column);
  621. if (event.shift() && m_selection.start().is_valid()) {
  622. m_selection.set_end(m_cursor);
  623. did_update_selection();
  624. }
  625. }
  626. return;
  627. }
  628. if (event.key() == KeyCode::Key_Left) {
  629. if (event.ctrl()) {
  630. TextPosition new_cursor;
  631. if (document().has_spans()) {
  632. auto span = document().first_non_skippable_span_before(m_cursor);
  633. if (span.has_value()) {
  634. new_cursor = span.value().range.start();
  635. } else {
  636. // No remaining spans, just use word break calculation
  637. new_cursor = document().first_word_break_before(m_cursor, true);
  638. }
  639. } else {
  640. new_cursor = document().first_word_break_before(m_cursor, true);
  641. }
  642. toggle_selection_if_needed_for_event(event);
  643. set_cursor(new_cursor);
  644. if (event.shift() && m_selection.start().is_valid()) {
  645. m_selection.set_end(m_cursor);
  646. did_update_selection();
  647. }
  648. return;
  649. }
  650. if (m_cursor.column() > 0) {
  651. int new_column = m_cursor.column() - 1;
  652. toggle_selection_if_needed_for_event(event);
  653. set_cursor(m_cursor.line(), new_column);
  654. if (event.shift() && m_selection.start().is_valid()) {
  655. m_selection.set_end(m_cursor);
  656. did_update_selection();
  657. }
  658. } else if (m_cursor.line() > 0) {
  659. int new_line = m_cursor.line() - 1;
  660. int new_column = lines()[new_line].length();
  661. toggle_selection_if_needed_for_event(event);
  662. set_cursor(new_line, new_column);
  663. if (event.shift() && m_selection.start().is_valid()) {
  664. m_selection.set_end(m_cursor);
  665. did_update_selection();
  666. }
  667. }
  668. return;
  669. }
  670. if (event.key() == KeyCode::Key_Right) {
  671. if (event.ctrl()) {
  672. TextPosition new_cursor;
  673. if (document().has_spans()) {
  674. auto span = document().first_non_skippable_span_after(m_cursor);
  675. if (span.has_value()) {
  676. new_cursor = span.value().range.start();
  677. } else {
  678. // No remaining spans, just use word break calculation
  679. new_cursor = document().first_word_break_after(m_cursor);
  680. }
  681. } else {
  682. new_cursor = document().first_word_break_after(m_cursor);
  683. }
  684. toggle_selection_if_needed_for_event(event);
  685. set_cursor(new_cursor);
  686. if (event.shift() && m_selection.start().is_valid()) {
  687. m_selection.set_end(m_cursor);
  688. did_update_selection();
  689. }
  690. return;
  691. }
  692. int new_line = m_cursor.line();
  693. int new_column = m_cursor.column();
  694. if (m_cursor.column() < current_line().length()) {
  695. new_line = m_cursor.line();
  696. new_column = m_cursor.column() + 1;
  697. } else if (m_cursor.line() != line_count() - 1) {
  698. new_line = m_cursor.line() + 1;
  699. new_column = 0;
  700. }
  701. toggle_selection_if_needed_for_event(event);
  702. set_cursor(new_line, new_column);
  703. if (event.shift() && m_selection.start().is_valid()) {
  704. m_selection.set_end(m_cursor);
  705. did_update_selection();
  706. }
  707. return;
  708. }
  709. if (!event.ctrl() && event.key() == KeyCode::Key_Home) {
  710. size_t first_nonspace_column = current_line().first_non_whitespace_column();
  711. toggle_selection_if_needed_for_event(event);
  712. if (m_cursor.column() == first_nonspace_column)
  713. set_cursor(m_cursor.line(), 0);
  714. else
  715. set_cursor(m_cursor.line(), first_nonspace_column);
  716. if (event.shift() && m_selection.start().is_valid()) {
  717. m_selection.set_end(m_cursor);
  718. did_update_selection();
  719. }
  720. return;
  721. }
  722. if (!event.ctrl() && event.key() == KeyCode::Key_End) {
  723. toggle_selection_if_needed_for_event(event);
  724. set_cursor(m_cursor.line(), current_line().length());
  725. if (event.shift() && m_selection.start().is_valid()) {
  726. m_selection.set_end(m_cursor);
  727. did_update_selection();
  728. }
  729. return;
  730. }
  731. if (event.ctrl() && event.key() == KeyCode::Key_Home) {
  732. toggle_selection_if_needed_for_event(event);
  733. set_cursor(0, 0);
  734. if (event.shift() && m_selection.start().is_valid()) {
  735. m_selection.set_end(m_cursor);
  736. did_update_selection();
  737. }
  738. return;
  739. }
  740. if (event.ctrl() && event.key() == KeyCode::Key_End) {
  741. toggle_selection_if_needed_for_event(event);
  742. set_cursor(line_count() - 1, lines()[line_count() - 1].length());
  743. if (event.shift() && m_selection.start().is_valid()) {
  744. m_selection.set_end(m_cursor);
  745. did_update_selection();
  746. }
  747. return;
  748. }
  749. if (event.alt() && event.shift() && event.key() == KeyCode::Key_S) {
  750. sort_selected_lines();
  751. return;
  752. }
  753. if (event.key() == KeyCode::Key_Backspace) {
  754. if (is_readonly())
  755. return;
  756. if (has_selection()) {
  757. delete_selection();
  758. did_update_selection();
  759. return;
  760. }
  761. if (m_cursor.column() > 0) {
  762. int erase_count = 1;
  763. if (current_line().first_non_whitespace_column() >= m_cursor.column()) {
  764. int new_column;
  765. if (m_cursor.column() % m_soft_tab_width == 0)
  766. new_column = m_cursor.column() - m_soft_tab_width;
  767. else
  768. new_column = (m_cursor.column() / m_soft_tab_width) * m_soft_tab_width;
  769. erase_count = m_cursor.column() - new_column;
  770. }
  771. // Backspace within line
  772. TextRange erased_range({ m_cursor.line(), m_cursor.column() - erase_count }, m_cursor);
  773. auto erased_text = document().text_in_range(erased_range);
  774. execute<RemoveTextCommand>(erased_text, erased_range);
  775. return;
  776. }
  777. if (m_cursor.column() == 0 && m_cursor.line() != 0) {
  778. // Backspace at column 0; merge with previous line
  779. size_t previous_length = line(m_cursor.line() - 1).length();
  780. TextRange erased_range({ m_cursor.line() - 1, previous_length }, m_cursor);
  781. execute<RemoveTextCommand>("\n", erased_range);
  782. return;
  783. }
  784. return;
  785. }
  786. if (event.modifiers() == Mod_Shift && event.key() == KeyCode::Key_Delete) {
  787. if (is_readonly())
  788. return;
  789. delete_current_line();
  790. return;
  791. }
  792. if (event.key() == KeyCode::Key_Delete) {
  793. if (is_readonly())
  794. return;
  795. do_delete();
  796. return;
  797. }
  798. if (!is_readonly() && !event.ctrl() && !event.alt() && !event.text().is_empty()) {
  799. insert_at_cursor_or_replace_selection(event.text());
  800. return;
  801. }
  802. event.ignore();
  803. }
  804. void TextEditor::delete_current_line()
  805. {
  806. if (has_selection())
  807. return delete_selection();
  808. TextPosition start;
  809. TextPosition end;
  810. if (m_cursor.line() == 0 && line_count() == 1) {
  811. start = { 0, 0 };
  812. end = { 0, line(0).length() };
  813. } else if (m_cursor.line() == line_count() - 1) {
  814. start = { m_cursor.line() - 1, line(m_cursor.line()).length() };
  815. end = { m_cursor.line(), line(m_cursor.line()).length() };
  816. } else {
  817. start = { m_cursor.line(), 0 };
  818. end = { m_cursor.line() + 1, 0 };
  819. }
  820. TextRange erased_range(start, end);
  821. execute<RemoveTextCommand>(document().text_in_range(erased_range), erased_range);
  822. }
  823. void TextEditor::do_delete()
  824. {
  825. if (is_readonly())
  826. return;
  827. if (has_selection())
  828. return delete_selection();
  829. if (m_cursor.column() < current_line().length()) {
  830. // Delete within line
  831. TextRange erased_range(m_cursor, { m_cursor.line(), m_cursor.column() + 1 });
  832. execute<RemoveTextCommand>(document().text_in_range(erased_range), erased_range);
  833. return;
  834. }
  835. if (m_cursor.column() == current_line().length() && m_cursor.line() != line_count() - 1) {
  836. // Delete at end of line; merge with next line
  837. TextRange erased_range(m_cursor, { m_cursor.line() + 1, 0 });
  838. execute<RemoveTextCommand>(document().text_in_range(erased_range), erased_range);
  839. return;
  840. }
  841. }
  842. int TextEditor::content_x_for_position(const TextPosition& position) const
  843. {
  844. auto& line = this->line(position.line());
  845. int x_offset = 0;
  846. switch (m_text_alignment) {
  847. case Gfx::TextAlignment::CenterLeft:
  848. for_each_visual_line(position.line(), [&](const Gfx::Rect&, auto& visual_line_view, size_t start_of_visual_line) {
  849. size_t offset_in_visual_line = position.column() - start_of_visual_line;
  850. if (position.column() >= start_of_visual_line && (offset_in_visual_line <= visual_line_view.length())) {
  851. if (offset_in_visual_line == 0) {
  852. x_offset = 0;
  853. } else {
  854. x_offset = font().width(visual_line_view.substring_view(0, offset_in_visual_line));
  855. x_offset += font().glyph_spacing();
  856. }
  857. return IterationDecision::Break;
  858. }
  859. return IterationDecision::Continue;
  860. });
  861. return m_horizontal_content_padding + x_offset;
  862. case Gfx::TextAlignment::CenterRight:
  863. // FIXME
  864. ASSERT(!is_line_wrapping_enabled());
  865. return content_width() - m_horizontal_content_padding - (line.length() * fixed_glyph_width()) + (position.column() * fixed_glyph_width());
  866. default:
  867. ASSERT_NOT_REACHED();
  868. }
  869. }
  870. Gfx::Rect TextEditor::content_rect_for_position(const TextPosition& position) const
  871. {
  872. if (!position.is_valid())
  873. return {};
  874. ASSERT(!lines().is_empty());
  875. ASSERT(position.column() <= (current_line().length() + 1));
  876. int x = content_x_for_position(position);
  877. if (is_single_line()) {
  878. Gfx::Rect rect { x, 0, 1, font().glyph_height() + 2 };
  879. rect.center_vertically_within({ {}, frame_inner_rect().size() });
  880. return rect;
  881. }
  882. Gfx::Rect rect;
  883. for_each_visual_line(position.line(), [&](const Gfx::Rect& visual_line_rect, auto& view, size_t start_of_visual_line) {
  884. if (position.column() >= start_of_visual_line && ((position.column() - start_of_visual_line) <= view.length())) {
  885. // NOTE: We have to subtract the horizontal padding here since it's part of the visual line rect
  886. // *and* included in what we get from content_x_for_position().
  887. rect = {
  888. visual_line_rect.x() + x - (m_horizontal_content_padding),
  889. visual_line_rect.y(),
  890. 1,
  891. line_height()
  892. };
  893. return IterationDecision::Break;
  894. }
  895. return IterationDecision::Continue;
  896. });
  897. return rect;
  898. }
  899. Gfx::Rect TextEditor::cursor_content_rect() const
  900. {
  901. return content_rect_for_position(m_cursor);
  902. }
  903. Gfx::Rect TextEditor::line_widget_rect(size_t line_index) const
  904. {
  905. auto rect = line_content_rect(line_index);
  906. rect.set_x(frame_thickness());
  907. rect.set_width(frame_inner_rect().width());
  908. rect.move_by(0, -(vertical_scrollbar().value()));
  909. rect.move_by(0, frame_thickness());
  910. rect.intersect(frame_inner_rect());
  911. return rect;
  912. }
  913. void TextEditor::scroll_position_into_view(const TextPosition& position)
  914. {
  915. auto rect = content_rect_for_position(position);
  916. if (position.column() == 0)
  917. rect.set_x(content_x_for_position({ position.line(), 0 }) - 2);
  918. else if (position.column() == line(position.line()).length())
  919. rect.set_x(content_x_for_position({ position.line(), line(position.line()).length() }) + 2);
  920. scroll_into_view(rect, true, true);
  921. }
  922. void TextEditor::scroll_cursor_into_view()
  923. {
  924. if (!m_reflow_deferred)
  925. scroll_position_into_view(m_cursor);
  926. }
  927. Gfx::Rect TextEditor::line_content_rect(size_t line_index) const
  928. {
  929. auto& line = this->line(line_index);
  930. if (is_single_line()) {
  931. Gfx::Rect line_rect = { content_x_for_position({ line_index, 0 }), 0, font().width(line.view()), font().glyph_height() + 4 };
  932. line_rect.center_vertically_within({ {}, frame_inner_rect().size() });
  933. return line_rect;
  934. }
  935. if (is_line_wrapping_enabled())
  936. return m_line_visual_data[line_index].visual_rect;
  937. return {
  938. content_x_for_position({ line_index, 0 }),
  939. (int)line_index * line_height(),
  940. font().width(line.view()),
  941. line_height()
  942. };
  943. }
  944. void TextEditor::update_cursor()
  945. {
  946. update(line_widget_rect(m_cursor.line()));
  947. }
  948. void TextEditor::set_cursor(size_t line, size_t column)
  949. {
  950. set_cursor({ line, column });
  951. }
  952. void TextEditor::set_cursor(const TextPosition& a_position)
  953. {
  954. ASSERT(!lines().is_empty());
  955. TextPosition position = a_position;
  956. if (position.line() >= line_count())
  957. position.set_line(line_count() - 1);
  958. if (position.column() > lines()[position.line()].length())
  959. position.set_column(lines()[position.line()].length());
  960. if (m_cursor != position) {
  961. // NOTE: If the old cursor is no longer valid, repaint everything just in case.
  962. auto old_cursor_line_rect = m_cursor.line() < line_count()
  963. ? line_widget_rect(m_cursor.line())
  964. : rect();
  965. m_cursor = position;
  966. m_cursor_state = true;
  967. scroll_cursor_into_view();
  968. update(old_cursor_line_rect);
  969. update_cursor();
  970. }
  971. cursor_did_change();
  972. if (on_cursor_change)
  973. on_cursor_change();
  974. if (m_highlighter)
  975. m_highlighter->cursor_did_change();
  976. }
  977. void TextEditor::focusin_event(Core::Event&)
  978. {
  979. m_cursor_state = true;
  980. update_cursor();
  981. start_timer(500);
  982. }
  983. void TextEditor::focusout_event(Core::Event&)
  984. {
  985. stop_timer();
  986. }
  987. void TextEditor::timer_event(Core::TimerEvent&)
  988. {
  989. m_cursor_state = !m_cursor_state;
  990. if (is_focused())
  991. update_cursor();
  992. }
  993. bool TextEditor::write_to_file(const StringView& path)
  994. {
  995. int fd = open_with_path_length(path.characters_without_null_termination(), path.length(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
  996. if (fd < 0) {
  997. perror("open");
  998. return false;
  999. }
  1000. // Compute the final file size and ftruncate() to make writing fast.
  1001. // FIXME: Remove this once the kernel is smart enough to do this instead.
  1002. off_t file_size = 0;
  1003. for (size_t i = 0; i < line_count(); ++i)
  1004. file_size += line(i).length();
  1005. file_size += line_count() - 1;
  1006. int rc = ftruncate(fd, file_size);
  1007. if (rc < 0) {
  1008. perror("ftruncate");
  1009. return false;
  1010. }
  1011. for (size_t i = 0; i < line_count(); ++i) {
  1012. auto& line = this->line(i);
  1013. if (line.length()) {
  1014. auto line_as_utf8 = line.to_utf8();
  1015. ssize_t nwritten = write(fd, line_as_utf8.characters(), line_as_utf8.length());
  1016. if (nwritten < 0) {
  1017. perror("write");
  1018. close(fd);
  1019. return false;
  1020. }
  1021. }
  1022. if (i != line_count() - 1) {
  1023. char ch = '\n';
  1024. ssize_t nwritten = write(fd, &ch, 1);
  1025. if (nwritten != 1) {
  1026. perror("write");
  1027. close(fd);
  1028. return false;
  1029. }
  1030. }
  1031. }
  1032. close(fd);
  1033. return true;
  1034. }
  1035. String TextEditor::text() const
  1036. {
  1037. StringBuilder builder;
  1038. for (size_t i = 0; i < line_count(); ++i) {
  1039. auto& line = this->line(i);
  1040. builder.append(line.view());
  1041. if (i != line_count() - 1)
  1042. builder.append('\n');
  1043. }
  1044. return builder.to_string();
  1045. }
  1046. void TextEditor::clear()
  1047. {
  1048. document().remove_all_lines();
  1049. document().append_line(make<TextDocumentLine>(document()));
  1050. m_selection.clear();
  1051. did_update_selection();
  1052. set_cursor(0, 0);
  1053. update();
  1054. }
  1055. String TextEditor::selected_text() const
  1056. {
  1057. if (!has_selection())
  1058. return {};
  1059. return document().text_in_range(m_selection);
  1060. }
  1061. void TextEditor::delete_selection()
  1062. {
  1063. auto selection = normalized_selection();
  1064. execute<RemoveTextCommand>(selected_text(), selection);
  1065. m_selection.clear();
  1066. did_update_selection();
  1067. did_change();
  1068. set_cursor(selection.start());
  1069. update();
  1070. }
  1071. void TextEditor::insert_at_cursor_or_replace_selection(const StringView& text)
  1072. {
  1073. ReflowDeferrer defer(*this);
  1074. ASSERT(!is_readonly());
  1075. if (has_selection())
  1076. delete_selection();
  1077. execute<InsertTextCommand>(text, m_cursor);
  1078. }
  1079. void TextEditor::cut()
  1080. {
  1081. if (is_readonly())
  1082. return;
  1083. auto selected_text = this->selected_text();
  1084. printf("Cut: \"%s\"\n", selected_text.characters());
  1085. Clipboard::the().set_data(selected_text);
  1086. delete_selection();
  1087. }
  1088. void TextEditor::copy()
  1089. {
  1090. auto selected_text = this->selected_text();
  1091. printf("Copy: \"%s\"\n", selected_text.characters());
  1092. Clipboard::the().set_data(selected_text);
  1093. }
  1094. void TextEditor::paste()
  1095. {
  1096. if (is_readonly())
  1097. return;
  1098. auto paste_text = Clipboard::the().data();
  1099. printf("Paste: \"%s\"\n", paste_text.characters());
  1100. TemporaryChange change(m_automatic_indentation_enabled, false);
  1101. insert_at_cursor_or_replace_selection(paste_text);
  1102. }
  1103. void TextEditor::defer_reflow()
  1104. {
  1105. ++m_reflow_deferred;
  1106. }
  1107. void TextEditor::undefer_reflow()
  1108. {
  1109. ASSERT(m_reflow_deferred);
  1110. if (!--m_reflow_deferred) {
  1111. if (m_reflow_requested) {
  1112. recompute_all_visual_lines();
  1113. scroll_cursor_into_view();
  1114. }
  1115. }
  1116. }
  1117. void TextEditor::enter_event(Core::Event&)
  1118. {
  1119. ASSERT(window());
  1120. window()->set_override_cursor(StandardCursor::IBeam);
  1121. m_automatic_selection_scroll_timer->stop();
  1122. }
  1123. void TextEditor::leave_event(Core::Event&)
  1124. {
  1125. ASSERT(window());
  1126. window()->set_override_cursor(StandardCursor::None);
  1127. if (m_in_drag_select)
  1128. m_automatic_selection_scroll_timer->start();
  1129. }
  1130. void TextEditor::did_change()
  1131. {
  1132. update_content_size();
  1133. recompute_all_visual_lines();
  1134. m_undo_action->set_enabled(can_undo());
  1135. m_redo_action->set_enabled(can_redo());
  1136. if (!m_has_pending_change_notification) {
  1137. m_has_pending_change_notification = true;
  1138. deferred_invoke([this](auto&) {
  1139. if (!m_has_pending_change_notification)
  1140. return;
  1141. if (on_change)
  1142. on_change();
  1143. if (m_highlighter)
  1144. m_highlighter->rehighlight(palette());
  1145. m_has_pending_change_notification = false;
  1146. });
  1147. }
  1148. }
  1149. void TextEditor::set_readonly(bool readonly)
  1150. {
  1151. if (m_readonly == readonly)
  1152. return;
  1153. m_readonly = readonly;
  1154. m_cut_action->set_enabled(!is_readonly() && has_selection());
  1155. m_delete_action->set_enabled(!is_readonly());
  1156. m_paste_action->set_enabled(!is_readonly());
  1157. }
  1158. void TextEditor::did_update_selection()
  1159. {
  1160. m_cut_action->set_enabled(!is_readonly() && has_selection());
  1161. m_copy_action->set_enabled(has_selection());
  1162. if (on_selection_change)
  1163. on_selection_change();
  1164. if (is_line_wrapping_enabled()) {
  1165. // FIXME: Try to repaint less.
  1166. update();
  1167. }
  1168. }
  1169. void TextEditor::context_menu_event(ContextMenuEvent& event)
  1170. {
  1171. if (!m_context_menu) {
  1172. m_context_menu = Menu::construct();
  1173. m_context_menu->add_action(undo_action());
  1174. m_context_menu->add_action(redo_action());
  1175. m_context_menu->add_separator();
  1176. m_context_menu->add_action(cut_action());
  1177. m_context_menu->add_action(copy_action());
  1178. m_context_menu->add_action(paste_action());
  1179. m_context_menu->add_action(delete_action());
  1180. m_context_menu->add_separator();
  1181. m_context_menu->add_action(select_all_action());
  1182. if (is_multi_line()) {
  1183. m_context_menu->add_separator();
  1184. m_context_menu->add_action(go_to_line_action());
  1185. }
  1186. if (!m_custom_context_menu_actions.is_empty()) {
  1187. m_context_menu->add_separator();
  1188. for (auto& action : m_custom_context_menu_actions) {
  1189. m_context_menu->add_action(action);
  1190. }
  1191. }
  1192. }
  1193. m_context_menu->popup(event.screen_position());
  1194. }
  1195. void TextEditor::set_text_alignment(Gfx::TextAlignment alignment)
  1196. {
  1197. if (m_text_alignment == alignment)
  1198. return;
  1199. m_text_alignment = alignment;
  1200. update();
  1201. }
  1202. void TextEditor::resize_event(ResizeEvent& event)
  1203. {
  1204. ScrollableWidget::resize_event(event);
  1205. update_content_size();
  1206. recompute_all_visual_lines();
  1207. }
  1208. void TextEditor::theme_change_event(ThemeChangeEvent& event)
  1209. {
  1210. ScrollableWidget::theme_change_event(event);
  1211. if (m_highlighter)
  1212. m_highlighter->rehighlight(palette());
  1213. }
  1214. void TextEditor::set_selection(const TextRange& selection)
  1215. {
  1216. if (m_selection == selection)
  1217. return;
  1218. m_selection = selection;
  1219. set_cursor(m_selection.end());
  1220. scroll_position_into_view(normalized_selection().start());
  1221. update();
  1222. }
  1223. void TextEditor::clear_selection()
  1224. {
  1225. if (!has_selection())
  1226. return;
  1227. m_selection.clear();
  1228. update();
  1229. }
  1230. void TextEditor::recompute_all_visual_lines()
  1231. {
  1232. if (m_reflow_deferred) {
  1233. m_reflow_requested = true;
  1234. return;
  1235. }
  1236. int y_offset = 0;
  1237. for (size_t line_index = 0; line_index < line_count(); ++line_index) {
  1238. recompute_visual_lines(line_index);
  1239. m_line_visual_data[line_index].visual_rect.set_y(y_offset);
  1240. y_offset += m_line_visual_data[line_index].visual_rect.height();
  1241. }
  1242. update_content_size();
  1243. }
  1244. void TextEditor::ensure_cursor_is_valid()
  1245. {
  1246. auto new_cursor = m_cursor;
  1247. if (new_cursor.line() >= line_count())
  1248. new_cursor.set_line(line_count() - 1);
  1249. if (new_cursor.column() > line(new_cursor.line()).length())
  1250. new_cursor.set_column(line(new_cursor.line()).length());
  1251. if (m_cursor != new_cursor)
  1252. set_cursor(new_cursor);
  1253. }
  1254. size_t TextEditor::visual_line_containing(size_t line_index, size_t column) const
  1255. {
  1256. size_t visual_line_index = 0;
  1257. for_each_visual_line(line_index, [&](const Gfx::Rect&, auto& view, size_t start_of_visual_line) {
  1258. if (column >= start_of_visual_line && ((column - start_of_visual_line) < view.length()))
  1259. return IterationDecision::Break;
  1260. ++visual_line_index;
  1261. return IterationDecision::Continue;
  1262. });
  1263. return visual_line_index;
  1264. }
  1265. void TextEditor::recompute_visual_lines(size_t line_index)
  1266. {
  1267. auto& line = document().line(line_index);
  1268. auto& visual_data = m_line_visual_data[line_index];
  1269. visual_data.visual_line_breaks.clear_with_capacity();
  1270. int available_width = visible_text_rect_in_inner_coordinates().width();
  1271. if (is_line_wrapping_enabled()) {
  1272. int line_width_so_far = 0;
  1273. auto glyph_spacing = font().glyph_spacing();
  1274. for (size_t i = 0; i < line.length(); ++i) {
  1275. auto codepoint = line.codepoints()[i];
  1276. auto glyph_width = font().glyph_or_emoji_width(codepoint);
  1277. if ((line_width_so_far + glyph_width + glyph_spacing) > available_width) {
  1278. visual_data.visual_line_breaks.append(i);
  1279. line_width_so_far = glyph_width + glyph_spacing;
  1280. continue;
  1281. }
  1282. line_width_so_far += glyph_width + glyph_spacing;
  1283. }
  1284. }
  1285. visual_data.visual_line_breaks.append(line.length());
  1286. if (is_line_wrapping_enabled())
  1287. visual_data.visual_rect = { m_horizontal_content_padding, 0, available_width, static_cast<int>(visual_data.visual_line_breaks.size()) * line_height() };
  1288. else
  1289. visual_data.visual_rect = { m_horizontal_content_padding, 0, font().width(line.view()), line_height() };
  1290. }
  1291. template<typename Callback>
  1292. void TextEditor::for_each_visual_line(size_t line_index, Callback callback) const
  1293. {
  1294. auto editor_visible_text_rect = visible_text_rect_in_inner_coordinates();
  1295. size_t start_of_line = 0;
  1296. size_t visual_line_index = 0;
  1297. auto& line = document().line(line_index);
  1298. auto& visual_data = m_line_visual_data[line_index];
  1299. for (auto visual_line_break : visual_data.visual_line_breaks) {
  1300. auto visual_line_view = Utf32View(line.codepoints() + start_of_line, visual_line_break - start_of_line);
  1301. Gfx::Rect visual_line_rect {
  1302. visual_data.visual_rect.x(),
  1303. visual_data.visual_rect.y() + ((int)visual_line_index * line_height()),
  1304. font().width(visual_line_view),
  1305. line_height()
  1306. };
  1307. if (is_right_text_alignment(text_alignment()))
  1308. visual_line_rect.set_right_without_resize(editor_visible_text_rect.right());
  1309. if (!is_multi_line())
  1310. visual_line_rect.center_vertically_within(editor_visible_text_rect);
  1311. if (callback(visual_line_rect, visual_line_view, start_of_line) == IterationDecision::Break)
  1312. break;
  1313. start_of_line = visual_line_break;
  1314. ++visual_line_index;
  1315. }
  1316. }
  1317. void TextEditor::set_line_wrapping_enabled(bool enabled)
  1318. {
  1319. if (m_line_wrapping_enabled == enabled)
  1320. return;
  1321. m_line_wrapping_enabled = enabled;
  1322. horizontal_scrollbar().set_visible(!m_line_wrapping_enabled);
  1323. update_content_size();
  1324. recompute_all_visual_lines();
  1325. update();
  1326. }
  1327. void TextEditor::add_custom_context_menu_action(Action& action)
  1328. {
  1329. m_custom_context_menu_actions.append(action);
  1330. }
  1331. void TextEditor::did_change_font()
  1332. {
  1333. vertical_scrollbar().set_step(line_height());
  1334. recompute_all_visual_lines();
  1335. update();
  1336. Widget::did_change_font();
  1337. }
  1338. void TextEditor::document_did_append_line()
  1339. {
  1340. m_line_visual_data.append(make<LineVisualData>());
  1341. recompute_all_visual_lines();
  1342. update();
  1343. }
  1344. void TextEditor::document_did_remove_line(size_t line_index)
  1345. {
  1346. m_line_visual_data.remove(line_index);
  1347. recompute_all_visual_lines();
  1348. update();
  1349. }
  1350. void TextEditor::document_did_remove_all_lines()
  1351. {
  1352. m_line_visual_data.clear();
  1353. recompute_all_visual_lines();
  1354. update();
  1355. }
  1356. void TextEditor::document_did_insert_line(size_t line_index)
  1357. {
  1358. m_line_visual_data.insert(line_index, make<LineVisualData>());
  1359. recompute_all_visual_lines();
  1360. update();
  1361. }
  1362. void TextEditor::document_did_change()
  1363. {
  1364. did_change();
  1365. update();
  1366. }
  1367. void TextEditor::document_did_set_text()
  1368. {
  1369. m_line_visual_data.clear();
  1370. for (size_t i = 0; i < m_document->line_count(); ++i)
  1371. m_line_visual_data.append(make<LineVisualData>());
  1372. document_did_change();
  1373. }
  1374. void TextEditor::document_did_set_cursor(const TextPosition& position)
  1375. {
  1376. set_cursor(position);
  1377. }
  1378. void TextEditor::set_document(TextDocument& document)
  1379. {
  1380. if (m_document.ptr() == &document)
  1381. return;
  1382. if (m_document)
  1383. m_document->unregister_client(*this);
  1384. m_document = document;
  1385. m_line_visual_data.clear();
  1386. for (size_t i = 0; i < m_document->line_count(); ++i) {
  1387. m_line_visual_data.append(make<LineVisualData>());
  1388. }
  1389. m_cursor = { 0, 0 };
  1390. if (has_selection())
  1391. m_selection.clear();
  1392. recompute_all_visual_lines();
  1393. update();
  1394. m_document->register_client(*this);
  1395. }
  1396. void TextEditor::flush_pending_change_notification_if_needed()
  1397. {
  1398. if (!m_has_pending_change_notification)
  1399. return;
  1400. if (on_change)
  1401. on_change();
  1402. if (m_highlighter)
  1403. m_highlighter->rehighlight(palette());
  1404. m_has_pending_change_notification = false;
  1405. }
  1406. const SyntaxHighlighter* TextEditor::syntax_highlighter() const
  1407. {
  1408. return m_highlighter.ptr();
  1409. }
  1410. void TextEditor::set_syntax_highlighter(OwnPtr<SyntaxHighlighter> highlighter)
  1411. {
  1412. if (m_highlighter)
  1413. m_highlighter->detach();
  1414. m_highlighter = move(highlighter);
  1415. if (m_highlighter) {
  1416. m_highlighter->attach(*this);
  1417. m_highlighter->rehighlight(palette());
  1418. } else
  1419. document().set_spans({});
  1420. }
  1421. int TextEditor::line_height() const
  1422. {
  1423. return font().glyph_height() + m_line_spacing;
  1424. }
  1425. int TextEditor::fixed_glyph_width() const
  1426. {
  1427. ASSERT(font().is_fixed_width());
  1428. return font().glyph_width(' ');
  1429. }
  1430. }