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