TextEditor.cpp 58 KB

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