TextEditor.cpp 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/QuickSort.h>
  27. #include <AK/StringBuilder.h>
  28. #include <Kernel/KeyCode.h>
  29. #include <LibCore/Timer.h>
  30. #include <LibGUI/Action.h>
  31. #include <LibGUI/Clipboard.h>
  32. #include <LibGUI/FontDatabase.h>
  33. #include <LibGUI/InputBox.h>
  34. #include <LibGUI/Menu.h>
  35. #include <LibGUI/Painter.h>
  36. #include <LibGUI/ScrollBar.h>
  37. #include <LibGUI/SyntaxHighlighter.h>
  38. #include <LibGUI/TextEditor.h>
  39. #include <LibGUI/Window.h>
  40. #include <LibGfx/Bitmap.h>
  41. #include <LibGfx/Font.h>
  42. #include <LibGfx/Palette.h>
  43. #include <ctype.h>
  44. #include <fcntl.h>
  45. #include <stdio.h>
  46. #include <unistd.h>
  47. //#define DEBUG_TEXTEDITOR
  48. namespace GUI {
  49. TextEditor::TextEditor(Type type)
  50. : m_type(type)
  51. {
  52. set_background_role(ColorRole::Base);
  53. set_foreground_role(ColorRole::BaseText);
  54. set_document(TextDocument::create());
  55. set_scrollbars_enabled(is_multi_line());
  56. set_font(FontDatabase::the().get_by_name("Csilla Thin"));
  57. // FIXME: Recompute vertical scrollbar step size on font change.
  58. vertical_scrollbar().set_step(line_height());
  59. m_cursor = { 0, 0 };
  60. m_automatic_selection_scroll_timer = add<Core::Timer>(100, [this] {
  61. automatic_selection_scroll_timer_fired();
  62. });
  63. m_automatic_selection_scroll_timer->stop();
  64. create_actions();
  65. }
  66. TextEditor::~TextEditor()
  67. {
  68. if (m_document)
  69. m_document->unregister_client(*this);
  70. }
  71. void TextEditor::create_actions()
  72. {
  73. m_undo_action = CommonActions::make_undo_action([&](auto&) { undo(); }, this);
  74. m_redo_action = CommonActions::make_redo_action([&](auto&) { redo(); }, this);
  75. m_undo_action->set_enabled(false);
  76. m_redo_action->set_enabled(false);
  77. m_cut_action = CommonActions::make_cut_action([&](auto&) { cut(); }, this);
  78. m_copy_action = CommonActions::make_copy_action([&](auto&) { copy(); }, this);
  79. m_paste_action = CommonActions::make_paste_action([&](auto&) { paste(); }, this);
  80. m_delete_action = CommonActions::make_delete_action([&](auto&) { do_delete(); }, this);
  81. if (is_multi_line()) {
  82. m_go_to_line_action = Action::create(
  83. "Go to line...", { Mod_Ctrl, Key_L }, Gfx::Bitmap::load_from_file("/res/icons/16x16/go-forward.png"), [this](auto&) {
  84. auto input_box = InputBox::construct("Line:", "Go to line", window());
  85. auto result = input_box->exec();
  86. if (result == InputBox::ExecOK) {
  87. bool ok;
  88. auto line_number = input_box->text_value().to_uint(ok);
  89. if (ok)
  90. set_cursor(line_number - 1, 0);
  91. }
  92. },
  93. this);
  94. }
  95. m_select_all_action = Action::create(
  96. "Select all", { Mod_Ctrl, Key_A }, Gfx::Bitmap::load_from_file("/res/icons/16x16/select-all.png"), [this](auto&) { select_all(); }, this);
  97. }
  98. void TextEditor::set_text(const StringView& text)
  99. {
  100. if (is_single_line() && text.length() == line(0).length() && !memcmp(text.characters_without_null_termination(), line(0).characters(), text.length()))
  101. return;
  102. m_selection.clear();
  103. document().set_text(text);
  104. update_content_size();
  105. recompute_all_visual_lines();
  106. if (is_single_line())
  107. set_cursor(0, line(0).length());
  108. else
  109. set_cursor(0, 0);
  110. did_update_selection();
  111. update();
  112. }
  113. void TextEditor::update_content_size()
  114. {
  115. int content_width = 0;
  116. int content_height = 0;
  117. for (auto& line : m_line_visual_data) {
  118. content_width = max(line.visual_rect.width(), content_width);
  119. content_height += line.visual_rect.height();
  120. }
  121. content_width += m_horizontal_content_padding * 2;
  122. if (is_right_text_alignment(m_text_alignment))
  123. content_width = max(frame_inner_rect().width(), content_width);
  124. set_content_size({ content_width, content_height });
  125. set_size_occupied_by_fixed_elements({ ruler_width(), 0 });
  126. }
  127. TextPosition TextEditor::text_position_at(const Gfx::Point& a_position) const
  128. {
  129. auto position = a_position;
  130. position.move_by(horizontal_scrollbar().value(), vertical_scrollbar().value());
  131. position.move_by(-(m_horizontal_content_padding + ruler_width()), 0);
  132. position.move_by(-frame_thickness(), -frame_thickness());
  133. size_t line_index = 0;
  134. if (is_line_wrapping_enabled()) {
  135. for (size_t i = 0; i < line_count(); ++i) {
  136. auto& rect = m_line_visual_data[i].visual_rect;
  137. if (position.y() >= rect.top() && position.y() <= rect.bottom()) {
  138. line_index = i;
  139. break;
  140. }
  141. if (position.y() > rect.bottom())
  142. line_index = line_count() - 1;
  143. }
  144. } else {
  145. line_index = (size_t)(position.y() / line_height());
  146. }
  147. line_index = max((size_t)0, min(line_index, line_count() - 1));
  148. size_t column_index;
  149. switch (m_text_alignment) {
  150. case Gfx::TextAlignment::CenterLeft:
  151. if (position.x() <= 0)
  152. column_index = 0;
  153. else
  154. column_index = (position.x() + glyph_width() / 2) / glyph_width();
  155. if (is_line_wrapping_enabled()) {
  156. for_each_visual_line(line_index, [&](const Gfx::Rect& rect, const StringView&, size_t start_of_line) {
  157. if (rect.contains_vertically(position.y())) {
  158. column_index += start_of_line;
  159. return IterationDecision::Break;
  160. }
  161. return IterationDecision::Continue;
  162. });
  163. }
  164. break;
  165. case Gfx::TextAlignment::CenterRight:
  166. // FIXME: Support right-aligned line wrapping, I guess.
  167. ASSERT(!is_line_wrapping_enabled());
  168. column_index = (position.x() - content_x_for_position({ line_index, 0 }) + glyph_width() / 2) / glyph_width();
  169. break;
  170. default:
  171. ASSERT_NOT_REACHED();
  172. }
  173. column_index = max((size_t)0, min(column_index, line(line_index).length()));
  174. return { line_index, column_index };
  175. }
  176. void TextEditor::doubleclick_event(MouseEvent& event)
  177. {
  178. if (event.button() != MouseButton::Left)
  179. return;
  180. // NOTE: This ensures that spans are updated before we look at them.
  181. flush_pending_change_notification_if_needed();
  182. m_triple_click_timer.start();
  183. m_in_drag_select = false;
  184. auto start = text_position_at(event.position());
  185. auto end = start;
  186. auto& line = this->line(start.line());
  187. if (!document().has_spans()) {
  188. while (start.column() > 0) {
  189. if (isspace(line.characters()[start.column() - 1]))
  190. break;
  191. start.set_column(start.column() - 1);
  192. }
  193. while (end.column() < line.length()) {
  194. if (isspace(line.characters()[end.column()]))
  195. break;
  196. end.set_column(end.column() + 1);
  197. }
  198. } else {
  199. for (auto& span : document().spans()) {
  200. if (!span.range.contains(start))
  201. continue;
  202. start = span.range.start();
  203. end = span.range.end();
  204. end.set_column(end.column() + 1);
  205. break;
  206. }
  207. }
  208. m_selection.set(start, end);
  209. set_cursor(end);
  210. update();
  211. did_update_selection();
  212. }
  213. void TextEditor::mousedown_event(MouseEvent& event)
  214. {
  215. if (event.button() != MouseButton::Left) {
  216. return;
  217. }
  218. if (m_triple_click_timer.is_valid() && m_triple_click_timer.elapsed() < 250) {
  219. m_triple_click_timer = Core::ElapsedTimer();
  220. TextPosition start;
  221. TextPosition end;
  222. if (is_multi_line()) {
  223. // select *current* line
  224. start = TextPosition(m_cursor.line(), 0);
  225. end = TextPosition(m_cursor.line(), line(m_cursor.line()).length());
  226. } else {
  227. // select *whole* line
  228. start = TextPosition(0, 0);
  229. end = TextPosition(line_count() - 1, line(line_count() - 1).length());
  230. }
  231. m_selection.set(start, end);
  232. set_cursor(end);
  233. return;
  234. }
  235. if (event.modifiers() & Mod_Shift) {
  236. if (!has_selection())
  237. m_selection.set(m_cursor, {});
  238. } else {
  239. m_selection.clear();
  240. }
  241. m_in_drag_select = true;
  242. m_automatic_selection_scroll_timer->start();
  243. set_cursor(text_position_at(event.position()));
  244. if (!(event.modifiers() & Mod_Shift)) {
  245. if (!has_selection())
  246. m_selection.set(m_cursor, {});
  247. }
  248. if (m_selection.start().is_valid() && m_selection.start() != m_cursor)
  249. m_selection.set_end(m_cursor);
  250. // FIXME: Only update the relevant rects.
  251. update();
  252. did_update_selection();
  253. }
  254. void TextEditor::mouseup_event(MouseEvent& event)
  255. {
  256. if (event.button() == MouseButton::Left) {
  257. if (m_in_drag_select) {
  258. m_in_drag_select = false;
  259. }
  260. return;
  261. }
  262. }
  263. void TextEditor::mousemove_event(MouseEvent& event)
  264. {
  265. m_last_mousemove_position = event.position();
  266. if (m_in_drag_select && (rect().contains(event.position()) || !m_automatic_selection_scroll_timer->is_active())) {
  267. set_cursor(text_position_at(event.position()));
  268. m_selection.set_end(m_cursor);
  269. did_update_selection();
  270. update();
  271. return;
  272. }
  273. }
  274. void TextEditor::automatic_selection_scroll_timer_fired()
  275. {
  276. if (!m_in_drag_select) {
  277. m_automatic_selection_scroll_timer->stop();
  278. return;
  279. }
  280. set_cursor(text_position_at(m_last_mousemove_position));
  281. m_selection.set_end(m_cursor);
  282. did_update_selection();
  283. update();
  284. }
  285. int TextEditor::ruler_width() const
  286. {
  287. if (!m_ruler_visible)
  288. return 0;
  289. // FIXME: Resize based on needed space.
  290. return 5 * font().glyph_width('x') + 4;
  291. }
  292. Gfx::Rect TextEditor::ruler_content_rect(size_t line_index) const
  293. {
  294. if (!m_ruler_visible)
  295. return {};
  296. return {
  297. 0 - ruler_width() + horizontal_scrollbar().value(),
  298. line_content_rect(line_index).y(),
  299. ruler_width(),
  300. line_content_rect(line_index).height()
  301. };
  302. }
  303. Gfx::Rect TextEditor::ruler_rect_in_inner_coordinates() const
  304. {
  305. return { 0, 0, ruler_width(), height() - height_occupied_by_horizontal_scrollbar() };
  306. }
  307. Gfx::Rect TextEditor::visible_text_rect_in_inner_coordinates() const
  308. {
  309. return {
  310. m_horizontal_content_padding + (m_ruler_visible ? (ruler_rect_in_inner_coordinates().right() + 1) : 0),
  311. 0,
  312. frame_inner_rect().width() - (m_horizontal_content_padding * 2) - width_occupied_by_vertical_scrollbar() - ruler_width(),
  313. frame_inner_rect().height() - height_occupied_by_horizontal_scrollbar()
  314. };
  315. }
  316. void TextEditor::paint_event(PaintEvent& event)
  317. {
  318. Color widget_background_color = palette().color(is_enabled() ? background_role() : Gfx::ColorRole::Window);
  319. // NOTE: This ensures that spans are updated before we look at them.
  320. flush_pending_change_notification_if_needed();
  321. Frame::paint_event(event);
  322. Painter painter(*this);
  323. painter.add_clip_rect(widget_inner_rect());
  324. painter.add_clip_rect(event.rect());
  325. painter.fill_rect(event.rect(), widget_background_color);
  326. painter.translate(frame_thickness(), frame_thickness());
  327. auto ruler_rect = ruler_rect_in_inner_coordinates();
  328. if (m_ruler_visible) {
  329. painter.fill_rect(ruler_rect, palette().ruler());
  330. painter.draw_line(ruler_rect.top_right(), ruler_rect.bottom_right(), palette().ruler_border());
  331. }
  332. painter.translate(-horizontal_scrollbar().value(), -vertical_scrollbar().value());
  333. if (m_ruler_visible)
  334. painter.translate(ruler_width(), 0);
  335. size_t first_visible_line = text_position_at(event.rect().top_left()).line();
  336. size_t last_visible_line = text_position_at(event.rect().bottom_right()).line();
  337. auto selection = normalized_selection();
  338. bool has_selection = selection.is_valid();
  339. if (m_ruler_visible) {
  340. for (size_t i = first_visible_line; i <= last_visible_line; ++i) {
  341. bool is_current_line = i == m_cursor.line();
  342. auto ruler_line_rect = ruler_content_rect(i);
  343. painter.draw_text(
  344. ruler_line_rect.shrunken(2, 0).translated(0, m_line_spacing / 2),
  345. String::number(i + 1),
  346. is_current_line ? Gfx::Font::default_bold_font() : font(),
  347. Gfx::TextAlignment::TopRight,
  348. is_current_line ? palette().ruler_active_text() : palette().ruler_inactive_text());
  349. }
  350. }
  351. Gfx::Rect text_clip_rect {
  352. (m_ruler_visible ? (ruler_rect_in_inner_coordinates().right() + frame_thickness() + 1) : frame_thickness()),
  353. frame_thickness(),
  354. width() - width_occupied_by_vertical_scrollbar() - ruler_width(),
  355. height() - height_occupied_by_horizontal_scrollbar()
  356. };
  357. painter.add_clip_rect(text_clip_rect);
  358. for (size_t line_index = first_visible_line; line_index <= last_visible_line; ++line_index) {
  359. auto& line = this->line(line_index);
  360. bool physical_line_has_selection = has_selection && line_index >= selection.start().line() && line_index <= selection.end().line();
  361. size_t first_visual_line_with_selection = 0;
  362. size_t last_visual_line_with_selection = 0;
  363. if (physical_line_has_selection) {
  364. if (selection.start().line() < line_index)
  365. first_visual_line_with_selection = 0;
  366. else
  367. first_visual_line_with_selection = visual_line_containing(line_index, selection.start().column());
  368. if (selection.end().line() > line_index)
  369. last_visual_line_with_selection = m_line_visual_data[line_index].visual_line_breaks.size();
  370. else
  371. last_visual_line_with_selection = visual_line_containing(line_index, selection.end().column());
  372. }
  373. size_t selection_start_column_within_line = selection.start().line() == line_index ? selection.start().column() : 0;
  374. size_t selection_end_column_within_line = selection.end().line() == line_index ? selection.end().column() : line.length();
  375. size_t visual_line_index = 0;
  376. for_each_visual_line(line_index, [&](const Gfx::Rect& visual_line_rect, const StringView& visual_line_text, size_t start_of_visual_line) {
  377. if (is_multi_line() && line_index == m_cursor.line())
  378. painter.fill_rect(visual_line_rect, widget_background_color.darkened(0.9f));
  379. #ifdef DEBUG_TEXTEDITOR
  380. painter.draw_rect(visual_line_rect, Color::Cyan);
  381. #endif
  382. if (!document().has_spans()) {
  383. // Fast-path for plain text
  384. auto color = palette().color(is_enabled() ? foreground_role() : Gfx::ColorRole::DisabledText);
  385. painter.draw_text(visual_line_rect, visual_line_text, m_text_alignment, color);
  386. } else {
  387. int advance = font().glyph_width(' ') + font().glyph_spacing();
  388. Gfx::Rect character_rect = { visual_line_rect.location(), { font().glyph_width(' '), line_height() } };
  389. for (size_t i = 0; i < visual_line_text.length(); ++i) {
  390. const Gfx::Font* font = &this->font();
  391. Color color;
  392. Optional<Color> background_color;
  393. bool underline = false;
  394. TextPosition physical_position(line_index, start_of_visual_line + i);
  395. // FIXME: This is *horribly* inefficient.
  396. for (auto& span : document().spans()) {
  397. if (!span.range.contains(physical_position))
  398. continue;
  399. color = span.color;
  400. if (span.font)
  401. font = span.font;
  402. background_color = span.background_color;
  403. underline = span.is_underlined;
  404. break;
  405. }
  406. if (background_color.has_value())
  407. painter.fill_rect(character_rect, background_color.value());
  408. painter.draw_text(character_rect, visual_line_text.substring_view(i, 1), *font, m_text_alignment, color);
  409. if (underline) {
  410. painter.draw_line(character_rect.bottom_left().translated(0, 1), character_rect.bottom_right().translated(0, 1), color);
  411. }
  412. character_rect.move_by(advance, 0);
  413. }
  414. }
  415. bool physical_line_has_selection = has_selection && line_index >= selection.start().line() && line_index <= selection.end().line();
  416. if (physical_line_has_selection) {
  417. size_t start_of_selection_within_visual_line = (size_t)max(0, (int)selection_start_column_within_line - (int)start_of_visual_line);
  418. size_t end_of_selection_within_visual_line = selection_end_column_within_line - start_of_visual_line;
  419. bool current_visual_line_has_selection = start_of_selection_within_visual_line != end_of_selection_within_visual_line
  420. && ((line_index != selection.start().line() && line_index != selection.end().line())
  421. || (visual_line_index >= first_visual_line_with_selection && visual_line_index <= last_visual_line_with_selection));
  422. if (current_visual_line_has_selection) {
  423. bool selection_begins_on_current_visual_line = visual_line_index == first_visual_line_with_selection;
  424. bool selection_ends_on_current_visual_line = visual_line_index == last_visual_line_with_selection;
  425. int selection_left = selection_begins_on_current_visual_line
  426. ? content_x_for_position({ line_index, (size_t)selection_start_column_within_line })
  427. : m_horizontal_content_padding;
  428. int selection_right = selection_ends_on_current_visual_line
  429. ? content_x_for_position({ line_index, (size_t)selection_end_column_within_line })
  430. : visual_line_rect.right() + 1;
  431. Gfx::Rect selection_rect {
  432. selection_left,
  433. visual_line_rect.y(),
  434. selection_right - selection_left,
  435. visual_line_rect.height()
  436. };
  437. Color background_color = is_focused() ? palette().selection() : palette().inactive_selection();
  438. Color text_color = is_focused() ? palette().selection_text() : palette().inactive_selection_text();
  439. painter.fill_rect(selection_rect, background_color);
  440. StringView visual_selected_text {
  441. visual_line_text.characters_without_null_termination() + start_of_selection_within_visual_line,
  442. end_of_selection_within_visual_line - start_of_selection_within_visual_line
  443. };
  444. painter.draw_text(selection_rect, visual_selected_text, Gfx::TextAlignment::CenterLeft, text_color);
  445. }
  446. }
  447. ++visual_line_index;
  448. return IterationDecision::Continue;
  449. });
  450. }
  451. if (is_focused() && m_cursor_state)
  452. painter.fill_rect(cursor_content_rect(), palette().text_cursor());
  453. }
  454. void TextEditor::toggle_selection_if_needed_for_event(const KeyEvent& event)
  455. {
  456. if (event.shift() && !m_selection.is_valid()) {
  457. m_selection.set(m_cursor, {});
  458. did_update_selection();
  459. update();
  460. return;
  461. }
  462. if (!event.shift() && m_selection.is_valid()) {
  463. m_selection.clear();
  464. did_update_selection();
  465. update();
  466. return;
  467. }
  468. }
  469. void TextEditor::select_all()
  470. {
  471. TextPosition start_of_document { 0, 0 };
  472. TextPosition end_of_document { line_count() - 1, line(line_count() - 1).length() };
  473. m_selection.set(start_of_document, end_of_document);
  474. did_update_selection();
  475. set_cursor(end_of_document);
  476. update();
  477. }
  478. void TextEditor::get_selection_line_boundaries(size_t& first_line, size_t& last_line)
  479. {
  480. auto selection = normalized_selection();
  481. if (!selection.is_valid()) {
  482. first_line = m_cursor.line();
  483. last_line = m_cursor.line();
  484. return;
  485. }
  486. first_line = selection.start().line();
  487. last_line = selection.end().line();
  488. if (first_line != last_line && selection.end().column() == 0)
  489. last_line -= 1;
  490. }
  491. void TextEditor::move_selected_lines_up()
  492. {
  493. size_t first_line;
  494. size_t last_line;
  495. get_selection_line_boundaries(first_line, last_line);
  496. if (first_line == 0)
  497. return;
  498. auto& lines = document().lines();
  499. lines.insert((int)last_line, lines.take((int)first_line - 1));
  500. m_cursor = { first_line - 1, 0 };
  501. if (has_selection()) {
  502. m_selection.set_start({ first_line - 1, 0 });
  503. m_selection.set_end({ last_line - 1, line(last_line - 1).length() });
  504. }
  505. did_change();
  506. update();
  507. }
  508. void TextEditor::move_selected_lines_down()
  509. {
  510. size_t first_line;
  511. size_t last_line;
  512. get_selection_line_boundaries(first_line, last_line);
  513. auto& lines = document().lines();
  514. ASSERT(lines.size() != 0);
  515. if (last_line >= lines.size() - 1)
  516. return;
  517. lines.insert((int)first_line, lines.take((int)last_line + 1));
  518. m_cursor = { first_line + 1, 0 };
  519. if (has_selection()) {
  520. m_selection.set_start({ first_line + 1, 0 });
  521. m_selection.set_end({ last_line + 1, line(last_line + 1).length() });
  522. }
  523. did_change();
  524. update();
  525. }
  526. void TextEditor::sort_selected_lines()
  527. {
  528. if (is_readonly())
  529. return;
  530. if (!has_selection())
  531. return;
  532. size_t first_line;
  533. size_t last_line;
  534. get_selection_line_boundaries(first_line, last_line);
  535. auto& lines = document().lines();
  536. auto start = lines.begin() + (int)first_line;
  537. auto end = lines.begin() + (int)last_line + 1;
  538. quick_sort(start, end, [](auto& a, auto& b) {
  539. return strcmp(a.characters(), b.characters()) < 0;
  540. });
  541. did_change();
  542. update();
  543. }
  544. void TextEditor::keydown_event(KeyEvent& event)
  545. {
  546. if (is_single_line() && event.key() == KeyCode::Key_Tab)
  547. return Widget::keydown_event(event);
  548. if (is_single_line() && event.key() == KeyCode::Key_Return) {
  549. if (on_return_pressed)
  550. on_return_pressed();
  551. return;
  552. }
  553. if (event.key() == KeyCode::Key_Escape) {
  554. if (on_escape_pressed)
  555. on_escape_pressed();
  556. return;
  557. }
  558. if (is_multi_line() && event.key() == KeyCode::Key_Up) {
  559. if (m_cursor.line() > 0) {
  560. if (event.ctrl() && event.shift()) {
  561. move_selected_lines_up();
  562. return;
  563. }
  564. size_t new_line = m_cursor.line() - 1;
  565. size_t new_column = min(m_cursor.column(), line(new_line).length());
  566. toggle_selection_if_needed_for_event(event);
  567. set_cursor(new_line, new_column);
  568. if (event.shift() && m_selection.start().is_valid()) {
  569. m_selection.set_end(m_cursor);
  570. did_update_selection();
  571. }
  572. }
  573. return;
  574. }
  575. if (is_multi_line() && event.key() == KeyCode::Key_Down) {
  576. if (m_cursor.line() < (line_count() - 1)) {
  577. if (event.ctrl() && event.shift()) {
  578. move_selected_lines_down();
  579. return;
  580. }
  581. size_t new_line = m_cursor.line() + 1;
  582. size_t new_column = min(m_cursor.column(), line(new_line).length());
  583. toggle_selection_if_needed_for_event(event);
  584. set_cursor(new_line, new_column);
  585. if (event.shift() && m_selection.start().is_valid()) {
  586. m_selection.set_end(m_cursor);
  587. did_update_selection();
  588. }
  589. }
  590. return;
  591. }
  592. if (is_multi_line() && event.key() == KeyCode::Key_PageUp) {
  593. if (m_cursor.line() > 0) {
  594. size_t page_step = (size_t)visible_content_rect().height() / (size_t)line_height();
  595. size_t new_line = m_cursor.line() < page_step ? 0 : m_cursor.line() - page_step;
  596. size_t new_column = min(m_cursor.column(), line(new_line).length());
  597. toggle_selection_if_needed_for_event(event);
  598. set_cursor(new_line, new_column);
  599. if (event.shift() && m_selection.start().is_valid()) {
  600. m_selection.set_end(m_cursor);
  601. did_update_selection();
  602. }
  603. }
  604. return;
  605. }
  606. if (is_multi_line() && event.key() == KeyCode::Key_PageDown) {
  607. if (m_cursor.line() < (line_count() - 1)) {
  608. int new_line = min(line_count() - 1, m_cursor.line() + visible_content_rect().height() / line_height());
  609. int new_column = min(m_cursor.column(), lines()[new_line].length());
  610. toggle_selection_if_needed_for_event(event);
  611. set_cursor(new_line, new_column);
  612. if (event.shift() && m_selection.start().is_valid()) {
  613. m_selection.set_end(m_cursor);
  614. did_update_selection();
  615. }
  616. }
  617. return;
  618. }
  619. if (event.key() == KeyCode::Key_Left) {
  620. if (event.ctrl() && document().has_spans()) {
  621. // FIXME: Do something nice when the document has no spans.
  622. auto span = document().first_non_skippable_span_before(m_cursor);
  623. TextPosition new_cursor = !span.has_value()
  624. ? TextPosition(0, 0)
  625. : span.value().range.start();
  626. toggle_selection_if_needed_for_event(event);
  627. set_cursor(new_cursor);
  628. if (event.shift() && m_selection.start().is_valid()) {
  629. m_selection.set_end(m_cursor);
  630. did_update_selection();
  631. }
  632. return;
  633. }
  634. if (m_cursor.column() > 0) {
  635. int new_column = m_cursor.column() - 1;
  636. toggle_selection_if_needed_for_event(event);
  637. set_cursor(m_cursor.line(), new_column);
  638. if (event.shift() && m_selection.start().is_valid()) {
  639. m_selection.set_end(m_cursor);
  640. did_update_selection();
  641. }
  642. } else if (m_cursor.line() > 0) {
  643. int new_line = m_cursor.line() - 1;
  644. int new_column = lines()[new_line].length();
  645. toggle_selection_if_needed_for_event(event);
  646. set_cursor(new_line, new_column);
  647. if (event.shift() && m_selection.start().is_valid()) {
  648. m_selection.set_end(m_cursor);
  649. did_update_selection();
  650. }
  651. }
  652. return;
  653. }
  654. if (event.key() == KeyCode::Key_Right) {
  655. if (event.ctrl() && document().has_spans()) {
  656. // FIXME: Do something nice when the document has no spans.
  657. auto span = document().first_non_skippable_span_after(m_cursor);
  658. TextPosition new_cursor = !span.has_value()
  659. ? document().spans().last().range.end()
  660. : span.value().range.start();
  661. toggle_selection_if_needed_for_event(event);
  662. set_cursor(new_cursor);
  663. if (event.shift() && m_selection.start().is_valid()) {
  664. m_selection.set_end(m_cursor);
  665. did_update_selection();
  666. }
  667. return;
  668. }
  669. int new_line = m_cursor.line();
  670. int new_column = m_cursor.column();
  671. if (m_cursor.column() < current_line().length()) {
  672. new_line = m_cursor.line();
  673. new_column = m_cursor.column() + 1;
  674. } else if (m_cursor.line() != line_count() - 1) {
  675. new_line = m_cursor.line() + 1;
  676. new_column = 0;
  677. }
  678. toggle_selection_if_needed_for_event(event);
  679. set_cursor(new_line, new_column);
  680. if (event.shift() && m_selection.start().is_valid()) {
  681. m_selection.set_end(m_cursor);
  682. did_update_selection();
  683. }
  684. return;
  685. }
  686. if (!event.ctrl() && event.key() == KeyCode::Key_Home) {
  687. size_t first_nonspace_column = current_line().first_non_whitespace_column();
  688. toggle_selection_if_needed_for_event(event);
  689. if (m_cursor.column() == first_nonspace_column)
  690. set_cursor(m_cursor.line(), 0);
  691. else
  692. set_cursor(m_cursor.line(), first_nonspace_column);
  693. if (event.shift() && m_selection.start().is_valid()) {
  694. m_selection.set_end(m_cursor);
  695. did_update_selection();
  696. }
  697. return;
  698. }
  699. if (!event.ctrl() && event.key() == KeyCode::Key_End) {
  700. toggle_selection_if_needed_for_event(event);
  701. set_cursor(m_cursor.line(), current_line().length());
  702. if (event.shift() && m_selection.start().is_valid()) {
  703. m_selection.set_end(m_cursor);
  704. did_update_selection();
  705. }
  706. return;
  707. }
  708. if (event.ctrl() && event.key() == KeyCode::Key_Home) {
  709. toggle_selection_if_needed_for_event(event);
  710. set_cursor(0, 0);
  711. if (event.shift() && m_selection.start().is_valid()) {
  712. m_selection.set_end(m_cursor);
  713. did_update_selection();
  714. }
  715. return;
  716. }
  717. if (event.ctrl() && event.key() == KeyCode::Key_End) {
  718. toggle_selection_if_needed_for_event(event);
  719. set_cursor(line_count() - 1, lines()[line_count() - 1].length());
  720. if (event.shift() && m_selection.start().is_valid()) {
  721. m_selection.set_end(m_cursor);
  722. did_update_selection();
  723. }
  724. return;
  725. }
  726. if (event.alt() && event.shift() && event.key() == KeyCode::Key_S) {
  727. sort_selected_lines();
  728. return;
  729. }
  730. if (event.key() == KeyCode::Key_Backspace) {
  731. if (is_readonly())
  732. return;
  733. if (has_selection()) {
  734. delete_selection();
  735. did_update_selection();
  736. return;
  737. }
  738. if (m_cursor.column() > 0) {
  739. int erase_count = 1;
  740. if (current_line().first_non_whitespace_column() >= m_cursor.column()) {
  741. int new_column;
  742. if (m_cursor.column() % m_soft_tab_width == 0)
  743. new_column = m_cursor.column() - m_soft_tab_width;
  744. else
  745. new_column = (m_cursor.column() / m_soft_tab_width) * m_soft_tab_width;
  746. erase_count = m_cursor.column() - new_column;
  747. }
  748. // Backspace within line
  749. TextRange erased_range({ m_cursor.line(), m_cursor.column() - erase_count }, m_cursor);
  750. auto erased_text = document().text_in_range(erased_range);
  751. execute<RemoveTextCommand>(erased_text, erased_range);
  752. return;
  753. }
  754. if (m_cursor.column() == 0 && m_cursor.line() != 0) {
  755. // Backspace at column 0; merge with previous line
  756. size_t previous_length = line(m_cursor.line() - 1).length();
  757. TextRange erased_range({ m_cursor.line() - 1, previous_length }, m_cursor);
  758. execute<RemoveTextCommand>("\n", erased_range);
  759. return;
  760. }
  761. return;
  762. }
  763. if (event.modifiers() == Mod_Shift && event.key() == KeyCode::Key_Delete) {
  764. if (is_readonly())
  765. return;
  766. delete_current_line();
  767. return;
  768. }
  769. if (event.key() == KeyCode::Key_Delete) {
  770. if (is_readonly())
  771. return;
  772. do_delete();
  773. return;
  774. }
  775. if (!is_readonly() && !event.ctrl() && !event.alt() && !event.text().is_empty()) {
  776. insert_at_cursor_or_replace_selection(event.text());
  777. return;
  778. }
  779. event.ignore();
  780. }
  781. void TextEditor::delete_current_line()
  782. {
  783. if (has_selection())
  784. return delete_selection();
  785. TextPosition start;
  786. TextPosition end;
  787. if (m_cursor.line() == 0 && line_count() == 1) {
  788. start = { 0, 0 };
  789. end = { 0, line(0).length() };
  790. } else if (m_cursor.line() == line_count() - 1) {
  791. start = { m_cursor.line() - 1, line(m_cursor.line()).length() };
  792. end = { m_cursor.line(), line(m_cursor.line()).length() };
  793. } else {
  794. start = { m_cursor.line(), 0 };
  795. end = { m_cursor.line() + 1, 0 };
  796. }
  797. TextRange erased_range(start, end);
  798. execute<RemoveTextCommand>(document().text_in_range(erased_range), erased_range);
  799. }
  800. void TextEditor::do_delete()
  801. {
  802. if (is_readonly())
  803. return;
  804. if (has_selection())
  805. return delete_selection();
  806. if (m_cursor.column() < current_line().length()) {
  807. // Delete within line
  808. TextRange erased_range(m_cursor, { m_cursor.line(), m_cursor.column() + 1 });
  809. execute<RemoveTextCommand>(document().text_in_range(erased_range), erased_range);
  810. return;
  811. }
  812. if (m_cursor.column() == current_line().length() && m_cursor.line() != line_count() - 1) {
  813. // Delete at end of line; merge with next line
  814. TextRange erased_range(m_cursor, { m_cursor.line() + 1, 0 });
  815. execute<RemoveTextCommand>(document().text_in_range(erased_range), erased_range);
  816. return;
  817. }
  818. }
  819. int TextEditor::content_x_for_position(const TextPosition& position) const
  820. {
  821. auto& line = this->line(position.line());
  822. int x_offset = -1;
  823. switch (m_text_alignment) {
  824. case Gfx::TextAlignment::CenterLeft:
  825. for_each_visual_line(position.line(), [&](const Gfx::Rect&, const StringView& view, size_t start_of_visual_line) {
  826. if (position.column() >= start_of_visual_line && ((position.column() - start_of_visual_line) <= view.length())) {
  827. x_offset = (position.column() - start_of_visual_line) * glyph_width();
  828. return IterationDecision::Break;
  829. }
  830. return IterationDecision::Continue;
  831. });
  832. return m_horizontal_content_padding + x_offset;
  833. case Gfx::TextAlignment::CenterRight:
  834. // FIXME
  835. ASSERT(!is_line_wrapping_enabled());
  836. return content_width() - m_horizontal_content_padding - (line.length() * glyph_width()) + (position.column() * glyph_width());
  837. default:
  838. ASSERT_NOT_REACHED();
  839. }
  840. }
  841. Gfx::Rect TextEditor::content_rect_for_position(const TextPosition& position) const
  842. {
  843. if (!position.is_valid())
  844. return {};
  845. ASSERT(!lines().is_empty());
  846. ASSERT(position.column() <= (current_line().length() + 1));
  847. int x = content_x_for_position(position);
  848. if (is_single_line()) {
  849. Gfx::Rect rect { x, 0, 1, font().glyph_height() + 2 };
  850. rect.center_vertically_within({ {}, frame_inner_rect().size() });
  851. return rect;
  852. }
  853. Gfx::Rect rect;
  854. for_each_visual_line(position.line(), [&](const Gfx::Rect& visual_line_rect, const StringView& view, size_t start_of_visual_line) {
  855. if (position.column() >= start_of_visual_line && ((position.column() - start_of_visual_line) <= view.length())) {
  856. // NOTE: We have to subtract the horizontal padding here since it's part of the visual line rect
  857. // *and* included in what we get from content_x_for_position().
  858. rect = {
  859. visual_line_rect.x() + x - (m_horizontal_content_padding),
  860. visual_line_rect.y(),
  861. 1,
  862. line_height()
  863. };
  864. return IterationDecision::Break;
  865. }
  866. return IterationDecision::Continue;
  867. });
  868. return rect;
  869. }
  870. Gfx::Rect TextEditor::cursor_content_rect() const
  871. {
  872. return content_rect_for_position(m_cursor);
  873. }
  874. Gfx::Rect TextEditor::line_widget_rect(size_t line_index) const
  875. {
  876. auto rect = line_content_rect(line_index);
  877. rect.set_x(frame_thickness());
  878. rect.set_width(frame_inner_rect().width());
  879. rect.move_by(0, -(vertical_scrollbar().value()));
  880. rect.move_by(0, frame_thickness());
  881. rect.intersect(frame_inner_rect());
  882. return rect;
  883. }
  884. void TextEditor::scroll_position_into_view(const TextPosition& position)
  885. {
  886. auto rect = content_rect_for_position(position);
  887. if (position.column() == 0)
  888. rect.set_x(content_x_for_position({ position.line(), 0 }) - 2);
  889. else if (position.column() == line(position.line()).length())
  890. rect.set_x(content_x_for_position({ position.line(), line(position.line()).length() }) + 2);
  891. scroll_into_view(rect, true, true);
  892. }
  893. void TextEditor::scroll_cursor_into_view()
  894. {
  895. scroll_position_into_view(m_cursor);
  896. }
  897. Gfx::Rect TextEditor::line_content_rect(size_t line_index) const
  898. {
  899. auto& line = this->line(line_index);
  900. if (is_single_line()) {
  901. Gfx::Rect line_rect = { content_x_for_position({ line_index, 0 }), 0, (int)line.length() * glyph_width(), font().glyph_height() + 2 };
  902. line_rect.center_vertically_within({ {}, frame_inner_rect().size() });
  903. return line_rect;
  904. }
  905. if (is_line_wrapping_enabled())
  906. return m_line_visual_data[line_index].visual_rect;
  907. return {
  908. content_x_for_position({ line_index, 0 }),
  909. (int)line_index * line_height(),
  910. (int)line.length() * glyph_width(),
  911. line_height()
  912. };
  913. }
  914. void TextEditor::update_cursor()
  915. {
  916. update(line_widget_rect(m_cursor.line()));
  917. }
  918. void TextEditor::set_cursor(size_t line, size_t column)
  919. {
  920. set_cursor({ line, column });
  921. }
  922. void TextEditor::set_cursor(const TextPosition& a_position)
  923. {
  924. ASSERT(!lines().is_empty());
  925. TextPosition position = a_position;
  926. if (position.line() >= line_count())
  927. position.set_line(line_count() - 1);
  928. if (position.column() > lines()[position.line()].length())
  929. position.set_column(lines()[position.line()].length());
  930. if (m_cursor != position) {
  931. // NOTE: If the old cursor is no longer valid, repaint everything just in case.
  932. auto old_cursor_line_rect = m_cursor.line() < line_count()
  933. ? line_widget_rect(m_cursor.line())
  934. : rect();
  935. m_cursor = position;
  936. m_cursor_state = true;
  937. scroll_cursor_into_view();
  938. update(old_cursor_line_rect);
  939. update_cursor();
  940. }
  941. cursor_did_change();
  942. if (on_cursor_change)
  943. on_cursor_change();
  944. if (m_highlighter)
  945. m_highlighter->cursor_did_change();
  946. }
  947. void TextEditor::focusin_event(Core::Event&)
  948. {
  949. update_cursor();
  950. start_timer(500);
  951. }
  952. void TextEditor::focusout_event(Core::Event&)
  953. {
  954. stop_timer();
  955. }
  956. void TextEditor::timer_event(Core::TimerEvent&)
  957. {
  958. m_cursor_state = !m_cursor_state;
  959. if (is_focused())
  960. update_cursor();
  961. }
  962. bool TextEditor::write_to_file(const StringView& path)
  963. {
  964. int fd = open_with_path_length(path.characters_without_null_termination(), path.length(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
  965. if (fd < 0) {
  966. perror("open");
  967. return false;
  968. }
  969. // Compute the final file size and ftruncate() to make writing fast.
  970. // FIXME: Remove this once the kernel is smart enough to do this instead.
  971. off_t file_size = 0;
  972. for (size_t i = 0; i < line_count(); ++i)
  973. file_size += line(i).length();
  974. file_size += line_count() - 1;
  975. int rc = ftruncate(fd, file_size);
  976. if (rc < 0) {
  977. perror("ftruncate");
  978. return false;
  979. }
  980. for (size_t i = 0; i < line_count(); ++i) {
  981. auto& line = this->line(i);
  982. if (line.length()) {
  983. ssize_t nwritten = write(fd, line.characters(), line.length());
  984. if (nwritten < 0) {
  985. perror("write");
  986. close(fd);
  987. return false;
  988. }
  989. }
  990. if (i != line_count() - 1) {
  991. char ch = '\n';
  992. ssize_t nwritten = write(fd, &ch, 1);
  993. if (nwritten != 1) {
  994. perror("write");
  995. close(fd);
  996. return false;
  997. }
  998. }
  999. }
  1000. close(fd);
  1001. return true;
  1002. }
  1003. String TextEditor::text() const
  1004. {
  1005. StringBuilder builder;
  1006. for (size_t i = 0; i < line_count(); ++i) {
  1007. auto& line = this->line(i);
  1008. builder.append(line.characters(), line.length());
  1009. if (i != line_count() - 1)
  1010. builder.append('\n');
  1011. }
  1012. return builder.to_string();
  1013. }
  1014. void TextEditor::clear()
  1015. {
  1016. document().remove_all_lines();
  1017. document().append_line(make<TextDocumentLine>(document()));
  1018. m_selection.clear();
  1019. did_update_selection();
  1020. set_cursor(0, 0);
  1021. update();
  1022. }
  1023. String TextEditor::selected_text() const
  1024. {
  1025. if (!has_selection())
  1026. return {};
  1027. return document().text_in_range(m_selection);
  1028. }
  1029. void TextEditor::delete_selection()
  1030. {
  1031. auto selection = normalized_selection();
  1032. execute<RemoveTextCommand>(selected_text(), selection);
  1033. m_selection.clear();
  1034. did_update_selection();
  1035. did_change();
  1036. set_cursor(selection.start());
  1037. update();
  1038. }
  1039. void TextEditor::insert_at_cursor_or_replace_selection(const StringView& text)
  1040. {
  1041. ASSERT(!is_readonly());
  1042. if (has_selection())
  1043. delete_selection();
  1044. execute<InsertTextCommand>(text, m_cursor);
  1045. }
  1046. void TextEditor::cut()
  1047. {
  1048. if (is_readonly())
  1049. return;
  1050. auto selected_text = this->selected_text();
  1051. printf("Cut: \"%s\"\n", selected_text.characters());
  1052. Clipboard::the().set_data(selected_text);
  1053. delete_selection();
  1054. }
  1055. void TextEditor::copy()
  1056. {
  1057. auto selected_text = this->selected_text();
  1058. printf("Copy: \"%s\"\n", selected_text.characters());
  1059. Clipboard::the().set_data(selected_text);
  1060. }
  1061. void TextEditor::paste()
  1062. {
  1063. if (is_readonly())
  1064. return;
  1065. auto paste_text = Clipboard::the().data();
  1066. printf("Paste: \"%s\"\n", paste_text.characters());
  1067. TemporaryChange change(m_automatic_indentation_enabled, false);
  1068. insert_at_cursor_or_replace_selection(paste_text);
  1069. }
  1070. void TextEditor::enter_event(Core::Event&)
  1071. {
  1072. ASSERT(window());
  1073. window()->set_override_cursor(StandardCursor::IBeam);
  1074. m_automatic_selection_scroll_timer->stop();
  1075. }
  1076. void TextEditor::leave_event(Core::Event&)
  1077. {
  1078. ASSERT(window());
  1079. window()->set_override_cursor(StandardCursor::None);
  1080. if (m_in_drag_select)
  1081. m_automatic_selection_scroll_timer->start();
  1082. }
  1083. void TextEditor::did_change()
  1084. {
  1085. update_content_size();
  1086. recompute_all_visual_lines();
  1087. m_undo_action->set_enabled(can_undo());
  1088. m_redo_action->set_enabled(can_redo());
  1089. if (!m_has_pending_change_notification) {
  1090. m_has_pending_change_notification = true;
  1091. deferred_invoke([this](auto&) {
  1092. if (!m_has_pending_change_notification)
  1093. return;
  1094. if (on_change)
  1095. on_change();
  1096. if (m_highlighter)
  1097. m_highlighter->rehighlight(palette());
  1098. m_has_pending_change_notification = false;
  1099. });
  1100. }
  1101. }
  1102. void TextEditor::set_readonly(bool readonly)
  1103. {
  1104. if (m_readonly == readonly)
  1105. return;
  1106. m_readonly = readonly;
  1107. m_cut_action->set_enabled(!is_readonly() && has_selection());
  1108. m_delete_action->set_enabled(!is_readonly());
  1109. m_paste_action->set_enabled(!is_readonly());
  1110. }
  1111. void TextEditor::did_update_selection()
  1112. {
  1113. m_cut_action->set_enabled(!is_readonly() && has_selection());
  1114. m_copy_action->set_enabled(has_selection());
  1115. if (on_selection_change)
  1116. on_selection_change();
  1117. if (is_line_wrapping_enabled()) {
  1118. // FIXME: Try to repaint less.
  1119. update();
  1120. }
  1121. }
  1122. void TextEditor::context_menu_event(ContextMenuEvent& event)
  1123. {
  1124. if (!m_context_menu) {
  1125. m_context_menu = Menu::construct();
  1126. m_context_menu->add_action(undo_action());
  1127. m_context_menu->add_action(redo_action());
  1128. m_context_menu->add_separator();
  1129. m_context_menu->add_action(cut_action());
  1130. m_context_menu->add_action(copy_action());
  1131. m_context_menu->add_action(paste_action());
  1132. m_context_menu->add_action(delete_action());
  1133. m_context_menu->add_separator();
  1134. m_context_menu->add_action(select_all_action());
  1135. if (is_multi_line()) {
  1136. m_context_menu->add_separator();
  1137. m_context_menu->add_action(go_to_line_action());
  1138. }
  1139. if (!m_custom_context_menu_actions.is_empty()) {
  1140. m_context_menu->add_separator();
  1141. for (auto& action : m_custom_context_menu_actions) {
  1142. m_context_menu->add_action(action);
  1143. }
  1144. }
  1145. }
  1146. m_context_menu->popup(event.screen_position());
  1147. }
  1148. void TextEditor::set_text_alignment(Gfx::TextAlignment alignment)
  1149. {
  1150. if (m_text_alignment == alignment)
  1151. return;
  1152. m_text_alignment = alignment;
  1153. update();
  1154. }
  1155. void TextEditor::resize_event(ResizeEvent& event)
  1156. {
  1157. ScrollableWidget::resize_event(event);
  1158. update_content_size();
  1159. recompute_all_visual_lines();
  1160. }
  1161. void TextEditor::theme_change_event(ThemeChangeEvent& event)
  1162. {
  1163. ScrollableWidget::theme_change_event(event);
  1164. if (m_highlighter)
  1165. m_highlighter->rehighlight(palette());
  1166. }
  1167. void TextEditor::set_selection(const TextRange& selection)
  1168. {
  1169. if (m_selection == selection)
  1170. return;
  1171. m_selection = selection;
  1172. set_cursor(m_selection.end());
  1173. scroll_position_into_view(normalized_selection().start());
  1174. update();
  1175. }
  1176. void TextEditor::clear_selection()
  1177. {
  1178. if (!has_selection())
  1179. return;
  1180. m_selection.clear();
  1181. update();
  1182. }
  1183. void TextEditor::recompute_all_visual_lines()
  1184. {
  1185. int y_offset = 0;
  1186. for (size_t line_index = 0; line_index < line_count(); ++line_index) {
  1187. recompute_visual_lines(line_index);
  1188. m_line_visual_data[line_index].visual_rect.set_y(y_offset);
  1189. y_offset += m_line_visual_data[line_index].visual_rect.height();
  1190. }
  1191. update_content_size();
  1192. }
  1193. void TextEditor::ensure_cursor_is_valid()
  1194. {
  1195. auto new_cursor = m_cursor;
  1196. if (new_cursor.line() >= line_count())
  1197. new_cursor.set_line(line_count() - 1);
  1198. if (new_cursor.column() > line(new_cursor.line()).length())
  1199. new_cursor.set_column(line(new_cursor.line()).length());
  1200. if (m_cursor != new_cursor)
  1201. set_cursor(new_cursor);
  1202. }
  1203. size_t TextEditor::visual_line_containing(size_t line_index, size_t column) const
  1204. {
  1205. size_t visual_line_index = 0;
  1206. for_each_visual_line(line_index, [&](const Gfx::Rect&, const StringView& view, size_t start_of_visual_line) {
  1207. if (column >= start_of_visual_line && ((column - start_of_visual_line) < view.length()))
  1208. return IterationDecision::Break;
  1209. ++visual_line_index;
  1210. return IterationDecision::Continue;
  1211. });
  1212. return visual_line_index;
  1213. }
  1214. void TextEditor::recompute_visual_lines(size_t line_index)
  1215. {
  1216. auto& line = document().line(line_index);
  1217. auto& visual_data = m_line_visual_data[line_index];
  1218. visual_data.visual_line_breaks.clear_with_capacity();
  1219. int available_width = visible_text_rect_in_inner_coordinates().width();
  1220. if (is_line_wrapping_enabled()) {
  1221. int line_width_so_far = 0;
  1222. for (size_t i = 0; i < line.length(); ++i) {
  1223. auto ch = line.characters()[i];
  1224. auto glyph_width = font().glyph_width(ch);
  1225. if ((line_width_so_far + glyph_width) > available_width) {
  1226. visual_data.visual_line_breaks.append(i);
  1227. line_width_so_far = glyph_width;
  1228. continue;
  1229. }
  1230. line_width_so_far += glyph_width;
  1231. }
  1232. }
  1233. visual_data.visual_line_breaks.append(line.length());
  1234. if (is_line_wrapping_enabled())
  1235. visual_data.visual_rect = { m_horizontal_content_padding, 0, available_width, static_cast<int>(visual_data.visual_line_breaks.size()) * line_height() };
  1236. else
  1237. visual_data.visual_rect = { m_horizontal_content_padding, 0, font().width(line.view()), line_height() };
  1238. }
  1239. template<typename Callback>
  1240. void TextEditor::for_each_visual_line(size_t line_index, Callback callback) const
  1241. {
  1242. auto editor_visible_text_rect = visible_text_rect_in_inner_coordinates();
  1243. size_t start_of_line = 0;
  1244. size_t visual_line_index = 0;
  1245. auto& line = document().line(line_index);
  1246. auto& visual_data = m_line_visual_data[line_index];
  1247. for (auto visual_line_break : visual_data.visual_line_breaks) {
  1248. auto visual_line_view = StringView(line.characters() + start_of_line, visual_line_break - start_of_line);
  1249. Gfx::Rect visual_line_rect {
  1250. visual_data.visual_rect.x(),
  1251. visual_data.visual_rect.y() + ((int)visual_line_index * line_height()),
  1252. font().width(visual_line_view),
  1253. line_height()
  1254. };
  1255. if (is_right_text_alignment(text_alignment()))
  1256. visual_line_rect.set_right_without_resize(editor_visible_text_rect.right());
  1257. if (!is_multi_line())
  1258. visual_line_rect.center_vertically_within(editor_visible_text_rect);
  1259. if (callback(visual_line_rect, visual_line_view, start_of_line) == IterationDecision::Break)
  1260. break;
  1261. start_of_line = visual_line_break;
  1262. ++visual_line_index;
  1263. }
  1264. }
  1265. void TextEditor::set_line_wrapping_enabled(bool enabled)
  1266. {
  1267. if (m_line_wrapping_enabled == enabled)
  1268. return;
  1269. m_line_wrapping_enabled = enabled;
  1270. horizontal_scrollbar().set_visible(!m_line_wrapping_enabled);
  1271. update_content_size();
  1272. recompute_all_visual_lines();
  1273. update();
  1274. }
  1275. void TextEditor::add_custom_context_menu_action(Action& action)
  1276. {
  1277. m_custom_context_menu_actions.append(action);
  1278. }
  1279. void TextEditor::did_change_font()
  1280. {
  1281. vertical_scrollbar().set_step(line_height());
  1282. recompute_all_visual_lines();
  1283. update();
  1284. Widget::did_change_font();
  1285. }
  1286. void TextEditor::document_did_append_line()
  1287. {
  1288. m_line_visual_data.append(make<LineVisualData>());
  1289. recompute_all_visual_lines();
  1290. update();
  1291. }
  1292. void TextEditor::document_did_remove_line(size_t line_index)
  1293. {
  1294. m_line_visual_data.remove(line_index);
  1295. recompute_all_visual_lines();
  1296. update();
  1297. }
  1298. void TextEditor::document_did_remove_all_lines()
  1299. {
  1300. m_line_visual_data.clear();
  1301. recompute_all_visual_lines();
  1302. update();
  1303. }
  1304. void TextEditor::document_did_insert_line(size_t line_index)
  1305. {
  1306. m_line_visual_data.insert(line_index, make<LineVisualData>());
  1307. recompute_all_visual_lines();
  1308. update();
  1309. }
  1310. void TextEditor::document_did_change()
  1311. {
  1312. did_change();
  1313. update();
  1314. }
  1315. void TextEditor::document_did_set_text()
  1316. {
  1317. m_line_visual_data.clear();
  1318. for (size_t i = 0; i < m_document->line_count(); ++i)
  1319. m_line_visual_data.append(make<LineVisualData>());
  1320. document_did_change();
  1321. }
  1322. void TextEditor::document_did_set_cursor(const TextPosition& position)
  1323. {
  1324. set_cursor(position);
  1325. }
  1326. void TextEditor::set_document(TextDocument& document)
  1327. {
  1328. if (m_document.ptr() == &document)
  1329. return;
  1330. if (m_document)
  1331. m_document->unregister_client(*this);
  1332. m_document = document;
  1333. m_line_visual_data.clear();
  1334. for (size_t i = 0; i < m_document->line_count(); ++i) {
  1335. m_line_visual_data.append(make<LineVisualData>());
  1336. }
  1337. m_cursor = { 0, 0 };
  1338. if (has_selection())
  1339. m_selection.clear();
  1340. recompute_all_visual_lines();
  1341. update();
  1342. m_document->register_client(*this);
  1343. }
  1344. void TextEditor::flush_pending_change_notification_if_needed()
  1345. {
  1346. if (!m_has_pending_change_notification)
  1347. return;
  1348. if (on_change)
  1349. on_change();
  1350. if (m_highlighter)
  1351. m_highlighter->rehighlight(palette());
  1352. m_has_pending_change_notification = false;
  1353. }
  1354. const SyntaxHighlighter* TextEditor::syntax_highlighter() const
  1355. {
  1356. return m_highlighter.ptr();
  1357. }
  1358. void TextEditor::set_syntax_highlighter(OwnPtr<SyntaxHighlighter> highlighter)
  1359. {
  1360. if (m_highlighter)
  1361. m_highlighter->detach();
  1362. m_highlighter = move(highlighter);
  1363. if (m_highlighter) {
  1364. m_highlighter->attach(*this);
  1365. m_highlighter->rehighlight(palette());
  1366. } else
  1367. document().set_spans({});
  1368. }
  1369. int TextEditor::line_height() const
  1370. {
  1371. return font().glyph_height() + m_line_spacing;
  1372. }
  1373. int TextEditor::glyph_width() const
  1374. {
  1375. return font().glyph_width('x');
  1376. }
  1377. }