Serenity Operating System
1/*
2 * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
3 * Copyright (c) 2022, the SerenityOS developers.
4 *
5 * SPDX-License-Identifier: BSD-2-Clause
6 */
7
8#pragma once
9
10#include <AK/AnyOf.h>
11#include <AK/Noncopyable.h>
12#include <AK/Vector.h>
13#include <LibVT/Attribute.h>
14#include <LibVT/Position.h>
15#include <LibVT/XtermColors.h>
16
17namespace VT {
18
19class Line {
20 AK_MAKE_NONCOPYABLE(Line);
21 AK_MAKE_NONMOVABLE(Line);
22
23public:
24 explicit Line(size_t length);
25 ~Line() = default;
26
27 struct Cell {
28 u32 code_point { ' ' };
29 Attribute attribute;
30
31 bool operator!=(Cell const& other) const { return code_point != other.code_point || attribute != other.attribute; }
32 };
33
34 Attribute const& attribute_at(size_t index) const { return m_cells[index].attribute; }
35 Attribute& attribute_at(size_t index) { return m_cells[index].attribute; }
36
37 Cell& cell_at(size_t index) { return m_cells[index]; }
38 Cell const& cell_at(size_t index) const { return m_cells[index]; }
39
40 void clear(Attribute const& attribute = Attribute())
41 {
42 m_terminated_at.clear();
43 clear_range(0, m_cells.size() - 1, attribute);
44 }
45 void clear_range(size_t first_column, size_t last_column, Attribute const& attribute = Attribute());
46 bool has_only_one_background_color() const;
47
48 bool is_empty() const
49 {
50 return !any_of(m_cells, [](auto& cell) { return cell != Cell(); });
51 }
52
53 size_t length() const
54 {
55 return m_cells.size();
56 }
57 void set_length(size_t);
58 void rewrap(size_t new_length, Line* next_line, CursorPosition* cursor, bool cursor_is_on_next_line = true);
59
60 u32 code_point(size_t index) const
61 {
62 return m_cells[index].code_point;
63 }
64
65 void set_code_point(size_t index, u32 code_point)
66 {
67 if (m_terminated_at.has_value()) {
68 if (index > *m_terminated_at) {
69 m_terminated_at = index + 1;
70 }
71 }
72
73 m_cells[index].code_point = code_point;
74 }
75
76 bool is_dirty() const { return m_dirty; }
77 void set_dirty(bool b) { m_dirty = b; }
78
79 Optional<u16> termination_column() const { return m_terminated_at; }
80 void set_terminated(u16 column) { m_terminated_at = column; }
81
82private:
83 void take_cells_from_next_line(size_t new_length, Line* next_line, bool cursor_is_on_next_line, CursorPosition* cursor);
84 void push_cells_into_next_line(size_t new_length, Line* next_line, bool cursor_is_on_next_line, CursorPosition* cursor);
85
86 Vector<Cell> m_cells;
87 bool m_dirty { false };
88 // Note: The alignment is 8, so this member lives in the padding (that already existed before it was introduced)
89 [[no_unique_address]] Optional<u16> m_terminated_at;
90};
91
92}