GTextEditor.cpp 49 KB

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