GTextDocument.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  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/StringBuilder.h>
  27. #include <LibCore/CTimer.h>
  28. #include <LibGUI/GTextDocument.h>
  29. #include <ctype.h>
  30. GTextDocument::GTextDocument(Client* client)
  31. {
  32. if (client)
  33. m_clients.set(client);
  34. append_line(make<GTextDocumentLine>(*this));
  35. // TODO: Instead of a repating timer, this we should call a delayed 2 sec timer when the user types.
  36. m_undo_timer = CTimer::construct(
  37. 2000, [this] {
  38. update_undo_timer();
  39. });
  40. }
  41. void GTextDocument::set_text(const StringView& text)
  42. {
  43. m_client_notifications_enabled = false;
  44. m_spans.clear();
  45. remove_all_lines();
  46. size_t start_of_current_line = 0;
  47. auto add_line = [&](size_t current_position) {
  48. size_t line_length = current_position - start_of_current_line;
  49. auto line = make<GTextDocumentLine>(*this);
  50. if (line_length)
  51. line->set_text(*this, text.substring_view(start_of_current_line, current_position - start_of_current_line));
  52. append_line(move(line));
  53. start_of_current_line = current_position + 1;
  54. };
  55. size_t i = 0;
  56. for (i = 0; i < text.length(); ++i) {
  57. if (text[i] == '\n')
  58. add_line(i);
  59. }
  60. add_line(i);
  61. m_client_notifications_enabled = true;
  62. for (auto* client : m_clients)
  63. client->document_did_set_text();
  64. }
  65. size_t GTextDocumentLine::first_non_whitespace_column() const
  66. {
  67. for (size_t i = 0; i < length(); ++i) {
  68. if (!isspace(m_text[(int)i]))
  69. return i;
  70. }
  71. return length();
  72. }
  73. GTextDocumentLine::GTextDocumentLine(GTextDocument& document)
  74. {
  75. clear(document);
  76. }
  77. GTextDocumentLine::GTextDocumentLine(GTextDocument& document, const StringView& text)
  78. {
  79. set_text(document, text);
  80. }
  81. void GTextDocumentLine::clear(GTextDocument& document)
  82. {
  83. m_text.clear();
  84. m_text.append(0);
  85. document.update_views({});
  86. }
  87. void GTextDocumentLine::set_text(GTextDocument& document, const StringView& text)
  88. {
  89. if (text.length() == length() && !memcmp(text.characters_without_null_termination(), characters(), length()))
  90. return;
  91. if (text.is_empty()) {
  92. clear(document);
  93. return;
  94. }
  95. m_text.resize((int)text.length() + 1);
  96. memcpy(m_text.data(), text.characters_without_null_termination(), text.length() + 1);
  97. document.update_views({});
  98. }
  99. void GTextDocumentLine::append(GTextDocument& document, const char* characters, size_t length)
  100. {
  101. int old_length = m_text.size() - 1;
  102. m_text.resize(m_text.size() + length);
  103. memcpy(m_text.data() + old_length, characters, length);
  104. m_text.last() = 0;
  105. document.update_views({});
  106. }
  107. void GTextDocumentLine::append(GTextDocument& document, char ch)
  108. {
  109. insert(document, length(), ch);
  110. }
  111. void GTextDocumentLine::prepend(GTextDocument& document, char ch)
  112. {
  113. insert(document, 0, ch);
  114. }
  115. void GTextDocumentLine::insert(GTextDocument& document, size_t index, char ch)
  116. {
  117. if (index == length()) {
  118. m_text.last() = ch;
  119. m_text.append(0);
  120. } else {
  121. m_text.insert((int)index, move(ch));
  122. }
  123. document.update_views({});
  124. }
  125. void GTextDocumentLine::remove(GTextDocument& document, size_t index)
  126. {
  127. if (index == length()) {
  128. m_text.take_last();
  129. m_text.last() = 0;
  130. } else {
  131. m_text.remove((int)index);
  132. }
  133. document.update_views({});
  134. }
  135. void GTextDocumentLine::truncate(GTextDocument& document, size_t length)
  136. {
  137. m_text.resize((int)length + 1);
  138. m_text.last() = 0;
  139. document.update_views({});
  140. }
  141. void GTextDocument::append_line(NonnullOwnPtr<GTextDocumentLine> line)
  142. {
  143. lines().append(move(line));
  144. if (m_client_notifications_enabled) {
  145. for (auto* client : m_clients)
  146. client->document_did_append_line();
  147. }
  148. }
  149. void GTextDocument::insert_line(size_t line_index, NonnullOwnPtr<GTextDocumentLine> line)
  150. {
  151. lines().insert((int)line_index, move(line));
  152. if (m_client_notifications_enabled) {
  153. for (auto* client : m_clients)
  154. client->document_did_insert_line(line_index);
  155. }
  156. }
  157. void GTextDocument::remove_line(size_t line_index)
  158. {
  159. lines().remove((int)line_index);
  160. if (m_client_notifications_enabled) {
  161. for (auto* client : m_clients)
  162. client->document_did_remove_line(line_index);
  163. }
  164. }
  165. void GTextDocument::remove_all_lines()
  166. {
  167. lines().clear();
  168. if (m_client_notifications_enabled) {
  169. for (auto* client : m_clients)
  170. client->document_did_remove_all_lines();
  171. }
  172. }
  173. GTextDocument::Client::~Client()
  174. {
  175. }
  176. void GTextDocument::register_client(Client& client)
  177. {
  178. m_clients.set(&client);
  179. }
  180. void GTextDocument::unregister_client(Client& client)
  181. {
  182. m_clients.remove(&client);
  183. }
  184. void GTextDocument::update_views(Badge<GTextDocumentLine>)
  185. {
  186. notify_did_change();
  187. }
  188. void GTextDocument::notify_did_change()
  189. {
  190. if (m_client_notifications_enabled) {
  191. for (auto* client : m_clients)
  192. client->document_did_change();
  193. }
  194. }
  195. void GTextDocument::set_all_cursors(const GTextPosition& position)
  196. {
  197. if (m_client_notifications_enabled) {
  198. for (auto* client : m_clients)
  199. client->document_did_set_cursor(position);
  200. }
  201. }
  202. String GTextDocument::text_in_range(const GTextRange& a_range) const
  203. {
  204. auto range = a_range.normalized();
  205. StringBuilder builder;
  206. for (size_t i = range.start().line(); i <= range.end().line(); ++i) {
  207. auto& line = this->line(i);
  208. size_t selection_start_column_on_line = range.start().line() == i ? range.start().column() : 0;
  209. size_t selection_end_column_on_line = range.end().line() == i ? range.end().column() : line.length();
  210. builder.append(line.characters() + selection_start_column_on_line, selection_end_column_on_line - selection_start_column_on_line);
  211. if (i != range.end().line())
  212. builder.append('\n');
  213. }
  214. return builder.to_string();
  215. }
  216. char GTextDocument::character_at(const GTextPosition& position) const
  217. {
  218. ASSERT(position.line() < line_count());
  219. auto& line = this->line(position.line());
  220. if (position.column() == line.length())
  221. return '\n';
  222. return line.characters()[position.column()];
  223. }
  224. GTextPosition GTextDocument::next_position_after(const GTextPosition& position, SearchShouldWrap should_wrap) const
  225. {
  226. auto& line = this->line(position.line());
  227. if (position.column() == line.length()) {
  228. if (position.line() == line_count() - 1) {
  229. if (should_wrap == SearchShouldWrap::Yes)
  230. return { 0, 0 };
  231. return {};
  232. }
  233. return { position.line() + 1, 0 };
  234. }
  235. return { position.line(), position.column() + 1 };
  236. }
  237. GTextPosition GTextDocument::previous_position_before(const GTextPosition& position, SearchShouldWrap should_wrap) const
  238. {
  239. if (position.column() == 0) {
  240. if (position.line() == 0) {
  241. if (should_wrap == SearchShouldWrap::Yes) {
  242. auto& last_line = this->line(line_count() - 1);
  243. return { line_count() - 1, last_line.length() };
  244. }
  245. return {};
  246. }
  247. auto& prev_line = this->line(position.line() - 1);
  248. return { position.line() - 1, prev_line.length() };
  249. }
  250. return { position.line(), position.column() - 1 };
  251. }
  252. GTextRange GTextDocument::find_next(const StringView& needle, const GTextPosition& start, SearchShouldWrap should_wrap) const
  253. {
  254. if (needle.is_empty())
  255. return {};
  256. GTextPosition position = start.is_valid() ? start : GTextPosition(0, 0);
  257. GTextPosition original_position = position;
  258. GTextPosition start_of_potential_match;
  259. size_t needle_index = 0;
  260. do {
  261. auto ch = character_at(position);
  262. if (ch == needle[needle_index]) {
  263. if (needle_index == 0)
  264. start_of_potential_match = position;
  265. ++needle_index;
  266. if (needle_index >= needle.length())
  267. return { start_of_potential_match, next_position_after(position, should_wrap) };
  268. } else {
  269. if (needle_index > 0)
  270. position = start_of_potential_match;
  271. needle_index = 0;
  272. }
  273. position = next_position_after(position, should_wrap);
  274. } while (position.is_valid() && position != original_position);
  275. return {};
  276. }
  277. GTextRange GTextDocument::find_previous(const StringView& needle, const GTextPosition& start, SearchShouldWrap should_wrap) const
  278. {
  279. if (needle.is_empty())
  280. return {};
  281. GTextPosition position = start.is_valid() ? start : GTextPosition(0, 0);
  282. position = previous_position_before(position, should_wrap);
  283. GTextPosition original_position = position;
  284. GTextPosition end_of_potential_match;
  285. size_t needle_index = needle.length() - 1;
  286. do {
  287. auto ch = character_at(position);
  288. if (ch == needle[needle_index]) {
  289. if (needle_index == needle.length() - 1)
  290. end_of_potential_match = position;
  291. if (needle_index == 0)
  292. return { position, next_position_after(end_of_potential_match, should_wrap) };
  293. --needle_index;
  294. } else {
  295. if (needle_index < needle.length() - 1)
  296. position = end_of_potential_match;
  297. needle_index = needle.length() - 1;
  298. }
  299. position = previous_position_before(position, should_wrap);
  300. } while (position.is_valid() && position != original_position);
  301. return {};
  302. }
  303. Vector<GTextRange> GTextDocument::find_all(const StringView& needle) const
  304. {
  305. Vector<GTextRange> ranges;
  306. GTextPosition position;
  307. for (;;) {
  308. auto range = find_next(needle, position, SearchShouldWrap::No);
  309. if (!range.is_valid())
  310. break;
  311. ranges.append(range);
  312. position = range.end();
  313. }
  314. return ranges;
  315. }
  316. Optional<GTextDocumentSpan> GTextDocument::first_non_skippable_span_before(const GTextPosition& position) const
  317. {
  318. for (int i = m_spans.size() - 1; i >= 0; --i) {
  319. if (!m_spans[i].range.contains(position))
  320. continue;
  321. while ((i - 1) >= 0 && m_spans[i - 1].is_skippable)
  322. --i;
  323. if (i <= 0)
  324. return {};
  325. return m_spans[i - 1];
  326. }
  327. return {};
  328. }
  329. Optional<GTextDocumentSpan> GTextDocument::first_non_skippable_span_after(const GTextPosition& position) const
  330. {
  331. for (int i = 0; i < m_spans.size(); ++i) {
  332. if (!m_spans[i].range.contains(position))
  333. continue;
  334. while ((i + 1) < m_spans.size() && m_spans[i + 1].is_skippable)
  335. ++i;
  336. if (i >= (m_spans.size() - 1))
  337. return {};
  338. return m_spans[i + 1];
  339. }
  340. return {};
  341. }
  342. void GTextDocument::undo()
  343. {
  344. if (!can_undo())
  345. return;
  346. m_undo_stack.undo();
  347. notify_did_change();
  348. }
  349. void GTextDocument::redo()
  350. {
  351. if (!can_redo())
  352. return;
  353. m_undo_stack.redo();
  354. notify_did_change();
  355. }
  356. void GTextDocument::add_to_undo_stack(NonnullOwnPtr<GTextDocumentUndoCommand> undo_command)
  357. {
  358. m_undo_stack.push(move(undo_command));
  359. }
  360. GTextDocumentUndoCommand::GTextDocumentUndoCommand(GTextDocument& document)
  361. : m_document(document)
  362. {
  363. }
  364. GTextDocumentUndoCommand::~GTextDocumentUndoCommand()
  365. {
  366. }
  367. InsertTextCommand::InsertTextCommand(GTextDocument& document, const String& text, const GTextPosition& position)
  368. : GTextDocumentUndoCommand(document)
  369. , m_text(text)
  370. , m_range({ position, position })
  371. {
  372. }
  373. void InsertTextCommand::redo()
  374. {
  375. auto new_cursor = m_document.insert_at(m_range.start(), m_text);
  376. // NOTE: We don't know where the range ends until after doing redo().
  377. // This is okay since we always do redo() after adding this to the undo stack.
  378. m_range.set_end(new_cursor);
  379. m_document.set_all_cursors(new_cursor);
  380. }
  381. void InsertTextCommand::undo()
  382. {
  383. m_document.remove(m_range);
  384. m_document.set_all_cursors(m_range.start());
  385. }
  386. RemoveTextCommand::RemoveTextCommand(GTextDocument& document, const String& text, const GTextRange& range)
  387. : GTextDocumentUndoCommand(document)
  388. , m_text(text)
  389. , m_range(range)
  390. {
  391. }
  392. void RemoveTextCommand::redo()
  393. {
  394. m_document.remove(m_range);
  395. m_document.set_all_cursors(m_range.start());
  396. }
  397. void RemoveTextCommand::undo()
  398. {
  399. auto new_cursor = m_document.insert_at(m_range.start(), m_text);
  400. m_document.set_all_cursors(new_cursor);
  401. }
  402. void GTextDocument::update_undo_timer()
  403. {
  404. m_undo_stack.finalize_current_combo();
  405. }
  406. GTextPosition GTextDocument::insert_at(const GTextPosition& position, const StringView& text)
  407. {
  408. GTextPosition cursor = position;
  409. for (size_t i = 0; i < text.length(); ++i)
  410. cursor = insert_at(cursor, text[i]);
  411. return cursor;
  412. }
  413. GTextPosition GTextDocument::insert_at(const GTextPosition& position, char ch)
  414. {
  415. // FIXME: We need these from GTextEditor!
  416. bool m_automatic_indentation_enabled = true;
  417. size_t m_soft_tab_width = 4;
  418. bool at_head = position.column() == 0;
  419. bool at_tail = position.column() == line(position.line()).length();
  420. if (ch == '\n') {
  421. if (at_tail || at_head) {
  422. String new_line_contents;
  423. if (m_automatic_indentation_enabled && at_tail) {
  424. size_t leading_spaces = 0;
  425. auto& old_line = lines()[position.line()];
  426. for (size_t i = 0; i < old_line.length(); ++i) {
  427. if (old_line.characters()[i] == ' ')
  428. ++leading_spaces;
  429. else
  430. break;
  431. }
  432. if (leading_spaces)
  433. new_line_contents = String::repeated(' ', leading_spaces);
  434. }
  435. size_t row = position.line();
  436. Vector<char> line_content;
  437. for (size_t i = position.column(); i < line(row).length(); i++)
  438. line_content.append(line(row).characters()[i]);
  439. insert_line(position.line() + (at_tail ? 1 : 0), make<GTextDocumentLine>(*this, new_line_contents));
  440. notify_did_change();
  441. return { position.line() + 1, line(position.line() + 1).length() };
  442. }
  443. auto new_line = make<GTextDocumentLine>(*this);
  444. new_line->append(*this, line(position.line()).characters() + position.column(), line(position.line()).length() - position.column());
  445. Vector<char> line_content;
  446. for (size_t i = 0; i < new_line->length(); i++)
  447. line_content.append(new_line->characters()[i]);
  448. line(position.line()).truncate(*this, position.column());
  449. insert_line(position.line() + 1, move(new_line));
  450. notify_did_change();
  451. return { position.line() + 1, 0 };
  452. }
  453. if (ch == '\t') {
  454. size_t next_soft_tab_stop = ((position.column() + m_soft_tab_width) / m_soft_tab_width) * m_soft_tab_width;
  455. size_t spaces_to_insert = next_soft_tab_stop - position.column();
  456. for (size_t i = 0; i < spaces_to_insert; ++i) {
  457. line(position.line()).insert(*this, position.column(), ' ');
  458. }
  459. notify_did_change();
  460. return { position.line(), next_soft_tab_stop };
  461. }
  462. line(position.line()).insert(*this, position.column(), ch);
  463. notify_did_change();
  464. return { position.line(), position.column() + 1 };
  465. }
  466. void GTextDocument::remove(const GTextRange& unnormalized_range)
  467. {
  468. if (!unnormalized_range.is_valid())
  469. return;
  470. auto range = unnormalized_range.normalized();
  471. // First delete all the lines in between the first and last one.
  472. for (size_t i = range.start().line() + 1; i < range.end().line();) {
  473. remove_line(i);
  474. range.end().set_line(range.end().line() - 1);
  475. }
  476. if (range.start().line() == range.end().line()) {
  477. // Delete within same line.
  478. auto& line = this->line(range.start().line());
  479. bool whole_line_is_selected = range.start().column() == 0 && range.end().column() == line.length();
  480. if (whole_line_is_selected) {
  481. line.clear(*this);
  482. } else {
  483. auto before_selection = String(line.characters(), line.length()).substring(0, range.start().column());
  484. auto after_selection = String(line.characters(), line.length()).substring(range.end().column(), line.length() - range.end().column());
  485. StringBuilder builder(before_selection.length() + after_selection.length());
  486. builder.append(before_selection);
  487. builder.append(after_selection);
  488. line.set_text(*this, builder.to_string());
  489. }
  490. } else {
  491. // Delete across a newline, merging lines.
  492. ASSERT(range.start().line() == range.end().line() - 1);
  493. auto& first_line = line(range.start().line());
  494. auto& second_line = line(range.end().line());
  495. auto before_selection = String(first_line.characters(), first_line.length()).substring(0, range.start().column());
  496. auto after_selection = String(second_line.characters(), second_line.length()).substring(range.end().column(), second_line.length() - range.end().column());
  497. StringBuilder builder(before_selection.length() + after_selection.length());
  498. builder.append(before_selection);
  499. builder.append(after_selection);
  500. first_line.set_text(*this, builder.to_string());
  501. remove_line(range.end().line());
  502. }
  503. if (lines().is_empty()) {
  504. append_line(make<GTextDocumentLine>(*this));
  505. }
  506. notify_did_change();
  507. }
  508. GTextRange GTextDocument::range_for_entire_line(size_t line_index) const
  509. {
  510. if (line_index >= line_count())
  511. return {};
  512. return { { line_index, 0 }, { line_index, line(line_index).length() } };
  513. }