TextEditor.cpp 55 KB

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