TextEditor.cpp 51 KB

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