TextEditor.cpp 53 KB

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