summaryrefslogtreecommitdiff
path: root/src/plugins/terminal/celliterator.cpp
blob: 91a70f76ea3c4778a3e83653fd1279ed287cbb91 (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
// Copyright (C) 2022 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0+ OR GPL-3.0 WITH Qt-GPL-exception-1.0

#include "celliterator.h"

#include "terminalsurface.h"

#include <stdexcept>

namespace Terminal::Internal {

CellIterator::CellIterator(const TerminalSurface *surface, QPoint pos)
    : CellIterator(surface, pos.x() + (pos.y() * surface->liveSize().width()))
{}

CellIterator::CellIterator(const TerminalSurface *surface, int pos)
    : m_state(State::INSIDE)
    , m_surface(surface)
{
    m_maxpos = surface->fullSize().width() * (surface->fullSize().height()) - 1;
    m_pos = qMax(0, qMin(m_maxpos + 1, pos));

    if (m_pos == 0) {
        m_state = State::BEGIN;
    } else if (m_pos == m_maxpos + 1) {
        m_state = State::END;
    }

    if (m_state != State::END)
        updateChar();
}

CellIterator::CellIterator(const TerminalSurface *surface)
    : m_state(State::END)
    , m_surface(surface)
{
    m_maxpos = surface->fullSize().width() * (surface->fullSize().height()) - 1;
    m_pos = m_maxpos + 1;
}

QPoint CellIterator::gridPos() const
{
    return m_surface->posToGrid(m_pos);
}

bool CellIterator::updateChar()
{
    QPoint cell = m_surface->posToGrid(m_pos);
    m_char = m_surface->fetchCharAt(cell.x(), cell.y());
    return m_char != 0;
}

CellIterator &CellIterator::operator-=(int n)
{
    if (n == 0)
        return *this;

    if (m_pos - n < 0)
        throw new std::runtime_error("-= n too big!");

    m_pos -= n;

    while (!updateChar() && m_pos > 0 && m_skipZeros)
        m_pos--;

    m_state = State::INSIDE;

    if (m_pos == 0) {
        m_state = State::BEGIN;
    }

    return *this;
}

CellIterator &CellIterator::operator+=(int n)
{
    if (n == 0)
        return *this;

    if (m_pos + n < m_maxpos + 1) {
        m_state = State::INSIDE;
        m_pos += n;
        while (!updateChar() && m_pos < (m_maxpos + 1) && m_skipZeros)
            m_pos++;

        if (m_pos == m_maxpos + 1)
            m_state = State::END;
    } else {
        *this = m_surface->end();
    }
    return *this;
}

} // namespace Terminal::Internal