summaryrefslogtreecommitdiff
path: root/Userland/Libraries/LibGUI/ModelSelection.cpp
blob: 1afc5973437695291b2c99c514158eeec19383d5 (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
95
96
/*
 * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <LibGUI/AbstractView.h>
#include <LibGUI/Model.h>
#include <LibGUI/ModelSelection.h>

namespace GUI {

void ModelSelection::remove_matching(Function<bool(const ModelIndex&)> filter)
{
    Vector<ModelIndex> to_remove;
    for (auto& index : m_indices) {
        if (filter(index))
            to_remove.append(index);
    }
    if (!to_remove.is_empty()) {
        for (auto& index : to_remove)
            m_indices.remove(index);
        notify_selection_changed();
    }
}

void ModelSelection::set(const ModelIndex& index)
{
    VERIFY(index.is_valid());
    if (m_indices.size() == 1 && m_indices.contains(index))
        return;
    m_indices.clear();
    m_indices.set(index);
    notify_selection_changed();
}

void ModelSelection::add(const ModelIndex& index)
{
    VERIFY(index.is_valid());
    if (m_indices.contains(index))
        return;
    m_indices.set(index);
    notify_selection_changed();
}

void ModelSelection::add_all(const Vector<ModelIndex>& indices)
{
    {
        TemporaryChange notify_change { m_disable_notify, true };
        for (auto& index : indices)
            add(index);
    }

    if (m_notify_pending)
        notify_selection_changed();
}

void ModelSelection::toggle(const ModelIndex& index)
{
    VERIFY(index.is_valid());
    if (m_indices.contains(index))
        m_indices.remove(index);
    else
        m_indices.set(index);
    notify_selection_changed();
}

bool ModelSelection::remove(const ModelIndex& index)
{
    VERIFY(index.is_valid());
    if (!m_indices.contains(index))
        return false;
    m_indices.remove(index);
    notify_selection_changed();
    return true;
}

void ModelSelection::clear()
{
    if (m_indices.is_empty())
        return;
    m_indices.clear();
    notify_selection_changed();
}

void ModelSelection::notify_selection_changed()
{
    if (!m_disable_notify) {
        m_view.notify_selection_changed({});
        m_notify_pending = false;
    } else {
        m_notify_pending = true;
    }
}

}