TextEditor.cpp 57 KB

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