blob: 426172a57830b8f4c45d4ecef3ef113f1dc5f111 [file] [log] [blame]
Chris Mumford54514cf2022-11-01 20:23:47 +00001// Copyright 2022 The Pigweed Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not
4// use this file except in compliance with the License. You may obtain a copy of
5// the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12// License for the specific language governing permissions and limitations under
13// the License.
14
15#include "text_buffer.h"
16
17using pw::color::color_rgb565_t;
Anthony DiGirolamod1b0bbb2024-04-10 20:15:41 +000018using pw::geometry::Vector2;
Chris Mumford54514cf2022-11-01 20:23:47 +000019
20namespace {
21constexpr int kMaxColIdx = kNumCharsWide - 1;
22constexpr int kMaxRowIdx = kNumRows - 1;
23
24static_assert(kNumRows > 1, "Text buffer too small");
25} // namespace
26
27void TextBuffer::InsertNewline() {
28 if (cursor_.y == kMaxRowIdx) {
29 ScrollUp();
30 } else {
31 cursor_.y++;
32 }
33 cursor_.x = 0;
34}
35
36pw::Result<TextBuffer::Char> TextBuffer::GetChar(Vector2<int> loc) const {
37 if (loc.x < 0 || static_cast<size_t>(loc.x) > kMaxColIdx || loc.y < 0 ||
38 static_cast<size_t>(loc.y) > kMaxRowIdx) {
39 return pw::Status::OutOfRange();
40 }
41 return text_rows_[loc.y].chars[loc.x];
42}
43
44void TextBuffer::DrawCharacter(const Char& ch) {
45 if (ch.ch == '\n') {
46 InsertNewline();
47 cursor_.x = 0;
48 return;
49 }
50
51 if (character_wrap_enabled_ && cursor_.x > kMaxColIdx) {
52 InsertNewline();
53 }
54
55 if (cursor_.x > kMaxColIdx) {
56 // The current line has grown too long.
57 return;
58 }
59
60 PW_ASSERT(cursor_.x >= 0 && cursor_.y >= 0);
61 PW_ASSERT(cursor_.y <= kMaxRowIdx);
62 PW_ASSERT(cursor_.x <= kMaxColIdx);
63
64 text_rows_[cursor_.y].chars[cursor_.x] = ch;
65
66 cursor_.x++;
67}
68
69void TextBuffer::ScrollUp() {
70 for (size_t r = 0; r < kMaxRowIdx; r++) {
71 text_rows_[r] = text_rows_[r + 1];
72 }
73 text_rows_.back().Clear();
74}