aboutsummaryrefslogtreecommitdiff
path: root/ttwhy/terminal/scanner.cppm
blob: bda9d8842a4df9a27d37924cd26cdbbe2a1b654b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
module;

#include <algorithm>
#include <boost/sml.hpp>

#include <queue>
#include <span>
#include <string>

export module ttwhy.terminal:scanner;

import :events;
import :policies;
import ttwhy.core;

namespace ttwhy::terminal::detail
{

  /// Events

  struct byte_received
  {
    char value;
  };

  struct c1_received
  {
    unsigned char value;
  };

  struct timeout_expired
  {
  };

  /// States

  constexpr auto idle = boost::sml::state<class idle>;
  constexpr auto escape_sequence = boost::sml::state<class escape_sequence>;
  constexpr auto csi_sequence = boost::sml::state<class csi_sequence>;
  constexpr auto ss3_sequence = boost::sml::state<class ss3_sequence>;

  /// Guards

  constexpr auto is_backspace = [](byte_received e) {
    return e.value == '\x08' || e.value == '\x7f';
  };

  constexpr auto is_tab = [](byte_received e) {
    return e.value == '\x09';
  };

  constexpr auto is_enter = [](byte_received e) {
    return e.value == '\x0a' || e.value == '\x0d';
  };

  constexpr auto is_escape = [](byte_received e) {
    return e.value == '\x1b';
  };

  constexpr auto is_printable = [](byte_received e) {
    return e.value >= ' ' && e.value <= '~';
  };

  constexpr auto is_c0_chord = [](byte_received e) {
    return e.value >= '\0' && e.value <= '\x1f' && !is_backspace(e) && !is_tab(e) && !is_enter(e) && !is_escape(e);
  };

  constexpr auto is_fe = [](byte_received e) {
    return e.value >= '@' && e.value <= '_';
  };

  constexpr auto is_csi = [](c1_received e) {
    return e.value == u'\x9b';
  };

  constexpr auto is_ss3 = [](c1_received e) {
    return e.value == u'\x8f';
  };

  constexpr auto is_unhandled_c1 = [](c1_received e) {
    return !(is_csi(e) || is_ss3(e));
  };

  constexpr auto is_csi_param = [](byte_received e) {
    return e.value >= ' ' && e.value <= '?';
  };

  constexpr auto is_vt100_terminator = [](byte_received e) {
    return e.value >= '@' && e.value <= '}';
  };

  constexpr auto is_vt220_terminator = [](byte_received e) {
    return e.value == '~';
  };

  /// Transitions

  template<event_sink Sink, typename TerminalPolicy>
  struct transition_table
  {
    auto operator()() const noexcept
    {
      using namespace boost::sml;

      constexpr auto push_character = [](byte_received event, Sink & sink) {
        sink(character_event{event.value});
      };

      constexpr auto push_backspace = [](Sink & sink) {
        sink(control_event{control_key::backspace});
      };

      constexpr auto push_tab = [](Sink & sink) {
        sink(control_event(control_key::tab));
      };

      constexpr auto push_enter = [](Sink & sink) {
        sink(control_event(control_key::enter));
      };

      constexpr auto push_c0_chord = [](byte_received event, Sink & sink) {
        sink(ctrl_chord_event{static_cast<char>(event.value + 0x40)});
      };

      constexpr auto dispatch_c1 = [](byte_received event, back::process<c1_received> process) {
        process(c1_received{static_cast<unsigned char>(event.value + 0x40)});
      };

      constexpr auto fallback_fe = [](c1_received event, Sink & sink) {
        sink(control_event{control_key::escape});
        sink(character_event{static_cast<char>(event.value - 0x40)});
      };

      constexpr auto emit_timeout_escape = [](Sink & sink, std::string & buffer) {
        sink(control_event{control_key::escape});
        buffer.clear();
      };

      constexpr auto fallback_escape = [](byte_received event, Sink & sink) {
        sink(control_event{control_key::escape});
        if (event.value >= ' ' && event.value <= '~')
        {
          sink(character_event{event.value});
        }
      };

      constexpr auto clear_csi = [](std::string & buffer) {
        buffer.clear();
      };

      constexpr auto push_csi_parameter = [](byte_received const & event, std::string & buffer) {
        buffer.push_back(event.value);
      };

      constexpr auto resolve_vt100_cursor = [](byte_received event, std::string & buffer, Sink & sink) {
        TerminalPolicy::resolve_vt100_cursor(event.value, buffer, sink);
        buffer.clear();
      };

      constexpr auto resolve_vt220_keypad = [](std::string & buffer, Sink & sink) {
        TerminalPolicy::resolve_vt220_keypad(buffer, sink);
        buffer.clear();
      };

      constexpr auto resolve_ss3 = [](byte_received event, Sink & sink) {
        TerminalPolicy::resolve_ss3(event.value, sink);
      };

      // clang-format off
      return make_transition_table(
          *idle +            event<byte_received>[is_escape]                                    = escape_sequence,
           idle +            event<byte_received>[is_backspace]          / push_backspace       = idle,
           idle +            event<byte_received>[is_tab]                / push_tab             = idle,
           idle +            event<byte_received>[is_enter]              / push_enter           = idle,
           idle +            event<byte_received>[is_c0_chord]           / push_c0_chord        = idle,
           idle +            event<byte_received>[is_printable]          / push_character       = idle,

           escape_sequence + event<byte_received>[is_fe]                 / dispatch_c1          = idle,
           escape_sequence + event<byte_received>[!is_fe]                / fallback_escape      = idle,
           escape_sequence + event<timeout_expired>                      / emit_timeout_escape  = idle,

           idle +            event<c1_received>[is_csi]                  / clear_csi            = csi_sequence,
           idle +            event<c1_received>[is_ss3]                                         = ss3_sequence,
           idle +            event<c1_received>[is_unhandled_c1]         / fallback_fe          = idle,

           csi_sequence +    event<byte_received>[is_csi_param]          / push_csi_parameter   = csi_sequence,
           csi_sequence +    event<byte_received>[is_vt220_terminator]   / resolve_vt220_keypad = idle,
           csi_sequence +    event<byte_received>[is_vt100_terminator]   / resolve_vt100_cursor = idle,
           csi_sequence +    event<timeout_expired>                      / emit_timeout_escape  = idle,

           ss3_sequence +    event<byte_received>                        / resolve_ss3          = idle,
           ss3_sequence +    event<timeout_expired>                      / emit_timeout_escape  = idle
      );
      // clang-format on
    }
  };

}  // namespace ttwhy::terminal::detail

export namespace ttwhy::terminal
{

  //! State machine tokenizer that decodes terminal escape sequences into input events.
  //!
  //! @tparam Sink The event sink callable type.
  //! @tparam TerminalPolicy The terminal escape policy.
  template<event_sink Sink, typename TerminalPolicy>
  struct scanner
  {
    //! Construct a terminal scanner bound to an event sink.
    //!
    //! @param sink The event sink to deliver decoded input events to.
    explicit scanner(Sink & sink)
        : m_state_machine{sink, m_csi_buffer}
    {}

    //! Process a buffer of incoming raw bytes through the state machine.
    //!
    //! @param buffer The view of raw bytes to decode.
    auto process(std::span<char const> buffer) -> void
    {
      std::ranges::for_each(buffer, [&](auto byte) { m_state_machine.process_event(detail::byte_received{byte}); });
    }

    //! Notify the state machine that an inter-byte timeout expired.
    auto timeout()
    {
      m_state_machine.process_event(detail::timeout_expired{});
    }

    //! Check if an escape sequence is currently pending completion.
    //!
    //! @return True if a sequence is incomplete, false otherwise.
    [[nodiscard]] auto is_pending() const -> bool
    {
      return m_state_machine.is(detail::escape_sequence) ||  //
             m_state_machine.is(detail::csi_sequence) ||     //
             m_state_machine.is(detail::ss3_sequence);
    }

  private:
    std::string m_csi_buffer{};
    boost::sml::sm<detail::transition_table<Sink, TerminalPolicy>, boost::sml::process_queue<std::queue>>
        m_state_machine;
  };

  //! Convenience alias for a terminal scanner configured with the ANSI policy.
  //!
  //! @tparam Sink The event sink callable type.
  template<event_sink Sink>
  using ansi = scanner<Sink, ansi_policy>;

  //! Convenience alias for a terminal scanner configured with the xterm policy.
  //!
  //! @tparam Sink The event sink callable type.
  template<event_sink Sink>
  using xterm = scanner<Sink, xterm_policy>;

}  // namespace ttwhy::terminal