TextEditor.cpp 62 KB

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