aboutsummaryrefslogtreecommitdiff
path: root/goldfishterm/simple.h
blob: 0228749e17cdcacdae55039cafb3c3f90348b2f3 (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
// Copyright 2021 Benjamin Barenblat
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

#ifndef EC_GOLDFISHTERM_SIMPLE_H_
#define EC_GOLDFISHTERM_SIMPLE_H_

#include <termios.h>

#include <ostream>
#include <vector>

#include "goldfishterm/internal/string_capability.h"
#include "goldfishterm/terminfo.h"
#include "third_party/abseil/absl/strings/string_view.h"

namespace goldfishterm {

// The type of cursor in use.
enum class CursorVisibility {
  kInvisible,
  kNormal,
  kVeryVisible,
};

// Looks up escape sequences for the specified terminal and allows sending those
// escape sequences to the specified ostream.
//
// This class is thread-safe.
class SimpleTerminalOutput final {
 public:
  explicit SimpleTerminalOutput(absl::string_view terminal_name, const termios&,
                                std::ostream&);

  SimpleTerminalOutput(const SimpleTerminalOutput&) noexcept = default;
  SimpleTerminalOutput& operator=(const SimpleTerminalOutput&) noexcept =
      default;
  SimpleTerminalOutput(SimpleTerminalOutput&&) noexcept = default;
  SimpleTerminalOutput& operator=(SimpleTerminalOutput&&) noexcept = default;

  void Write(absl::string_view s) { out_.write(s.data(), s.size()); }

  void Flush() { out_.flush(); }

  // Rings the bell. On some terminals, this may flash the screen instead.
  void Beep() { Emit(StringCapability::kBell); }

  // Moves the cursor to the beginning of the current line.
  void BeginningOfLine() { Emit(StringCapability::kCarriageReturn); }

  // Clears from the cursor to the end of the current line.
  void ClearToEndOfLine() { Emit(StringCapability::kClrEol); }

  // Moves the cursor down one line.
  void CursorDown() { Emit(StringCapability::kCursorDown); }

  // Sets the cursor visibility.
  void SetCursorVisibility(CursorVisibility);

 private:
  void Emit(StringCapability,
            std::vector<goldfishterm_internal::StringCapabilityParameter> = {});

  TerminfoEntry terminfo_;
  int baud_;
  std::ostream& out_;
};

}  // namespace goldfishterm

#endif  // EC_GOLDFISHTERM_SIMPLE_H_