summaryrefslogtreecommitdiff
path: root/Userland/Demos/ModelGallery/BasicModel.cpp
blob: 10b76e37af6a223dfc0afd5c16582bc576a7514f (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
/*
 * Copyright (c) 2021, sin-ack <sin-ack@protonmail.com>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include "BasicModel.h"

GUI::Variant BasicModel::data(GUI::ModelIndex const& index, GUI::ModelRole role) const
{
    if (role != GUI::ModelRole::Display)
        return {};
    if (!is_within_range(index))
        return {};

    return m_items.at(index.row());
}

TriState BasicModel::data_matches(GUI::ModelIndex const& index, GUI::Variant const& data) const
{
    if (!is_within_range(index))
        return TriState::False;
    if (!data.is_string())
        return TriState::False;

    auto& value = m_items.at(index.row());
    return value.contains(data.as_string()) ? TriState::True : TriState::False;
}

void BasicModel::invalidate()
{
    Model::invalidate();
    if (on_invalidate)
        on_invalidate();
}

GUI::ModelIndex BasicModel::index(int row, int column, GUI::ModelIndex const& parent) const
{
    if (column != 0)
        return {};
    if (parent.is_valid())
        return {};
    if (row < 0 || row >= static_cast<int>(m_items.size()))
        return {};

    return create_index(row, column);
}

void BasicModel::add_item(String const& item)
{
    begin_insert_rows({}, m_items.size(), m_items.size());
    m_items.append(item);
    end_insert_rows();

    did_update(UpdateFlag::DontInvalidateIndices);
}

void BasicModel::remove_item(GUI::ModelIndex const& index)
{
    if (!index.is_valid() || !is_within_range(index))
        return;

    begin_delete_rows({}, index.row(), index.row());
    m_items.remove(index.row());
    end_delete_rows();

    did_update(UpdateFlag::DontInvalidateIndices);
}