Editor.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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. #pragma once
  27. #include <AK/BinarySearch.h>
  28. #include <AK/ByteBuffer.h>
  29. #include <AK/Function.h>
  30. #include <AK/HashMap.h>
  31. #include <AK/NonnullOwnPtr.h>
  32. #include <AK/QuickSort.h>
  33. #include <AK/Result.h>
  34. #include <AK/String.h>
  35. #include <AK/Utf32View.h>
  36. #include <AK/Utf8View.h>
  37. #include <AK/Vector.h>
  38. #include <LibCore/DirIterator.h>
  39. #include <LibCore/Notifier.h>
  40. #include <LibCore/Object.h>
  41. #include <LibLine/Span.h>
  42. #include <LibLine/StringMetrics.h>
  43. #include <LibLine/Style.h>
  44. #include <LibLine/SuggestionDisplay.h>
  45. #include <LibLine/SuggestionManager.h>
  46. #include <LibLine/VT.h>
  47. #include <sys/ioctl.h>
  48. #include <sys/stat.h>
  49. #include <termios.h>
  50. namespace Line {
  51. struct Configuration {
  52. enum RefreshBehaviour {
  53. Lazy,
  54. Eager,
  55. };
  56. enum OperationMode {
  57. Unset,
  58. Full,
  59. NoEscapeSequences,
  60. NonInteractive,
  61. };
  62. Configuration()
  63. {
  64. }
  65. template<typename Arg, typename... Rest>
  66. Configuration(Arg arg, Rest... rest)
  67. : Configuration(rest...)
  68. {
  69. set(arg);
  70. }
  71. void set(RefreshBehaviour refresh) { refresh_behaviour = refresh; }
  72. void set(OperationMode mode) { operation_mode = mode; }
  73. static Configuration from_config(const StringView& libname = "line");
  74. RefreshBehaviour refresh_behaviour { RefreshBehaviour::Lazy };
  75. OperationMode operation_mode { OperationMode::Unset };
  76. };
  77. class Editor : public Core::Object {
  78. C_OBJECT(Editor);
  79. public:
  80. enum class Error {
  81. ReadFailure,
  82. Empty,
  83. Eof,
  84. };
  85. ~Editor();
  86. Result<String, Error> get_line(const String& prompt);
  87. void initialize();
  88. void add_to_history(const String&);
  89. const Vector<String>& history() const { return m_history; }
  90. void register_character_input_callback(char ch, Function<bool(Editor&)> callback);
  91. StringMetrics actual_rendered_string_metrics(const StringView&) const;
  92. StringMetrics actual_rendered_string_metrics(const Utf32View&) const;
  93. Function<Vector<CompletionSuggestion>(const Editor&)> on_tab_complete;
  94. Function<void()> on_interrupt_handled;
  95. Function<void(Editor&)> on_display_refresh;
  96. // FIXME: we will have to kindly ask our instantiators to set our signal handlers,
  97. // since we can not do this cleanly ourselves. (signal() limitation: cannot give member functions)
  98. void interrupted()
  99. {
  100. if (m_is_editing) {
  101. m_was_interrupted = true;
  102. handle_interrupt_event();
  103. }
  104. }
  105. void resized()
  106. {
  107. m_was_resized = true;
  108. m_previous_num_columns = m_num_columns;
  109. get_terminal_size();
  110. m_suggestion_display->set_vt_size(m_num_lines, m_num_columns);
  111. }
  112. size_t cursor() const { return m_cursor; }
  113. const Vector<u32, 1024>& buffer() const { return m_buffer; }
  114. u32 buffer_at(size_t pos) const { return m_buffer.at(pos); }
  115. String line() const { return line(m_buffer.size()); }
  116. String line(size_t up_to_index) const;
  117. // Only makes sense inside a character_input callback or on_* callback.
  118. void set_prompt(const String& prompt)
  119. {
  120. if (m_cached_prompt_valid)
  121. m_old_prompt_metrics = m_cached_prompt_metrics;
  122. m_cached_prompt_valid = false;
  123. m_cached_prompt_metrics = actual_rendered_string_metrics(prompt);
  124. m_new_prompt = prompt;
  125. }
  126. void clear_line();
  127. void insert(const String&);
  128. void insert(const StringView&);
  129. void insert(const Utf32View&);
  130. void insert(const u32);
  131. void stylize(const Span&, const Style&);
  132. void strip_styles(bool strip_anchored = false);
  133. // Invariant Offset is an offset into the suggested data, hinting the editor what parts of the suggestion will not change
  134. // Static Offset is an offset into the token, signifying where the suggestions start
  135. // e.g.
  136. // foobar<suggestion initiated>, on_tab_complete returns "barx", "bary", "barz"
  137. // ^ ^
  138. // +-|- static offset: the suggestions start here
  139. // +- invariant offset: the suggestions do not change up to here
  140. //
  141. void suggest(size_t invariant_offset = 0, size_t static_offset = 0, Span::Mode offset_mode = Span::ByteOriented) const;
  142. const struct termios& termios() const { return m_termios; }
  143. const struct termios& default_termios() const { return m_default_termios; }
  144. struct winsize terminal_size() const
  145. {
  146. winsize ws { (u16)m_num_lines, (u16)m_num_columns, 0, 0 };
  147. return ws;
  148. }
  149. void finish()
  150. {
  151. m_finish = true;
  152. }
  153. bool is_editing() const { return m_is_editing; }
  154. const Utf32View buffer_view() const { return { m_buffer.data(), m_buffer.size() }; }
  155. private:
  156. explicit Editor(Configuration configuration = Configuration::from_config());
  157. enum VTState {
  158. Free = 1,
  159. Escape = 3,
  160. Bracket = 5,
  161. BracketArgsSemi = 7,
  162. Title = 9,
  163. };
  164. VTState actual_rendered_string_length_step(StringMetrics&, size_t& length, u32, u32, VTState) const;
  165. // ^Core::Object
  166. virtual void save_to(JsonObject&) override;
  167. struct KeyCallback {
  168. KeyCallback(Function<bool(Editor&)> cb)
  169. : callback(move(cb))
  170. {
  171. }
  172. Function<bool(Editor&)> callback;
  173. };
  174. void handle_interrupt_event();
  175. void handle_read_event();
  176. Vector<size_t, 2> vt_dsr();
  177. void remove_at_index(size_t);
  178. enum class ModificationKind {
  179. Insertion,
  180. Removal,
  181. ForcedOverlapRemoval,
  182. };
  183. void readjust_anchored_styles(size_t hint_index, ModificationKind);
  184. Style find_applicable_style(size_t offset) const;
  185. bool search(const StringView&, bool allow_empty = false, bool from_beginning = false);
  186. inline void end_search()
  187. {
  188. m_is_searching = false;
  189. m_refresh_needed = true;
  190. m_search_offset = 0;
  191. if (m_reset_buffer_on_search_end) {
  192. m_buffer.clear();
  193. for (auto ch : m_pre_search_buffer)
  194. m_buffer.append(ch);
  195. m_cursor = m_pre_search_cursor;
  196. }
  197. m_reset_buffer_on_search_end = true;
  198. m_search_editor = nullptr;
  199. }
  200. void reset()
  201. {
  202. m_cached_buffer_metrics.reset();
  203. m_cached_prompt_valid = false;
  204. m_cursor = 0;
  205. m_drawn_cursor = 0;
  206. m_inline_search_cursor = 0;
  207. m_old_prompt_metrics = m_cached_prompt_metrics;
  208. set_origin(0, 0);
  209. m_prompt_lines_at_suggestion_initiation = 0;
  210. m_refresh_needed = true;
  211. m_input_error.clear();
  212. m_returned_line = String::empty();
  213. }
  214. void refresh_display();
  215. void cleanup();
  216. void restore()
  217. {
  218. ASSERT(m_initialized);
  219. tcsetattr(0, TCSANOW, &m_default_termios);
  220. m_initialized = false;
  221. }
  222. const StringMetrics& current_prompt_metrics() const
  223. {
  224. return m_cached_prompt_valid ? m_cached_prompt_metrics : m_old_prompt_metrics;
  225. }
  226. size_t num_lines() const
  227. {
  228. return current_prompt_metrics().lines_with_addition(m_cached_buffer_metrics, m_num_columns);
  229. }
  230. size_t cursor_line() const
  231. {
  232. auto cursor = m_drawn_cursor;
  233. if (cursor > m_cursor)
  234. cursor = m_cursor;
  235. return current_prompt_metrics().lines_with_addition(
  236. actual_rendered_string_metrics(buffer_view().substring_view(0, cursor)),
  237. m_num_columns);
  238. }
  239. size_t offset_in_line() const
  240. {
  241. auto cursor = m_drawn_cursor;
  242. if (cursor > m_cursor)
  243. cursor = m_cursor;
  244. auto buffer_metrics = actual_rendered_string_metrics(buffer_view().substring_view(0, cursor));
  245. if (buffer_metrics.line_lengths.size() > 1)
  246. return buffer_metrics.line_lengths.last() % m_num_columns;
  247. return (buffer_metrics.line_lengths.last() + current_prompt_metrics().line_lengths.last()) % m_num_columns;
  248. }
  249. void set_origin()
  250. {
  251. auto position = vt_dsr();
  252. set_origin(position[0], position[1]);
  253. }
  254. void set_origin(int row, int col)
  255. {
  256. m_origin_row = row;
  257. m_origin_column = col;
  258. m_suggestion_display->set_origin(row, col, {});
  259. }
  260. void recalculate_origin();
  261. void reposition_cursor(bool to_end = false);
  262. struct CodepointRange {
  263. size_t start { 0 };
  264. size_t end { 0 };
  265. };
  266. CodepointRange byte_offset_range_to_code_point_offset_range(size_t byte_start, size_t byte_end, size_t code_point_scan_offset, bool reverse = false) const;
  267. void get_terminal_size();
  268. bool m_finish { false };
  269. RefPtr<Editor> m_search_editor;
  270. bool m_is_searching { false };
  271. bool m_reset_buffer_on_search_end { true };
  272. size_t m_search_offset { 0 };
  273. bool m_searching_backwards { true };
  274. size_t m_pre_search_cursor { 0 };
  275. Vector<u32, 1024> m_pre_search_buffer;
  276. Vector<u32, 1024> m_buffer;
  277. ByteBuffer m_pending_chars;
  278. Vector<char, 512> m_incomplete_data;
  279. Optional<Error> m_input_error;
  280. String m_returned_line;
  281. size_t m_cursor { 0 };
  282. size_t m_drawn_cursor { 0 };
  283. size_t m_inline_search_cursor { 0 };
  284. size_t m_chars_inserted_in_the_middle { 0 };
  285. size_t m_times_tab_pressed { 0 };
  286. size_t m_num_columns { 0 };
  287. size_t m_num_lines { 1 };
  288. size_t m_previous_num_columns { 0 };
  289. size_t m_extra_forward_lines { 0 };
  290. StringMetrics m_cached_prompt_metrics;
  291. StringMetrics m_old_prompt_metrics;
  292. StringMetrics m_cached_buffer_metrics;
  293. size_t m_prompt_lines_at_suggestion_initiation { 0 };
  294. bool m_cached_prompt_valid { false };
  295. // Exact position before our prompt in the terminal.
  296. size_t m_origin_row { 0 };
  297. size_t m_origin_column { 0 };
  298. OwnPtr<SuggestionDisplay> m_suggestion_display;
  299. String m_new_prompt;
  300. SuggestionManager m_suggestion_manager;
  301. bool m_always_refresh { false };
  302. enum class TabDirection {
  303. Forward,
  304. Backward,
  305. };
  306. TabDirection m_tab_direction { TabDirection::Forward };
  307. HashMap<char, NonnullOwnPtr<KeyCallback>> m_key_callbacks;
  308. // TODO: handle signals internally.
  309. struct termios m_termios {
  310. };
  311. struct termios m_default_termios {
  312. };
  313. bool m_was_interrupted { false };
  314. bool m_was_resized { false };
  315. // FIXME: This should be something more take_first()-friendly.
  316. Vector<String> m_history;
  317. size_t m_history_cursor { 0 };
  318. size_t m_history_capacity { 100 };
  319. enum class InputState {
  320. Free,
  321. GotEscape,
  322. GotEscapeFollowedByLeftBracket,
  323. ExpectTerminator,
  324. };
  325. InputState m_state { InputState::Free };
  326. HashMap<u32, HashMap<u32, Style>> m_spans_starting;
  327. HashMap<u32, HashMap<u32, Style>> m_spans_ending;
  328. HashMap<u32, HashMap<u32, Style>> m_anchored_spans_starting;
  329. HashMap<u32, HashMap<u32, Style>> m_anchored_spans_ending;
  330. RefPtr<Core::Notifier> m_notifier;
  331. bool m_initialized { false };
  332. bool m_refresh_needed { false };
  333. bool m_is_editing { false };
  334. Configuration m_configuration;
  335. };
  336. }