TextEditor.cpp 50 KB

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