summaryrefslogtreecommitdiffstats
path: root/src/ui/widget/canvas/synchronizer.cpp
blob: 331057b96d30c68b32c90accc646326c76d6b8ba (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
97
98
99
100
101
102
103
// SPDX-License-Identifier: GPL-2.0-or-later
#include "synchronizer.h"
#include <cassert>

namespace Inkscape::UI::Widget {

Synchronizer::Synchronizer()
{
    dispatcher.connect([this] { on_dispatcher(); });
}

void Synchronizer::signalExit() const
{
    auto lock = std::unique_lock(mutables);
    awaken();
    assert(slots.empty());
    exitposted = true;
}

void Synchronizer::runInMain(std::function<void()> const &f) const
{
    auto lock = std::unique_lock(mutables);
    awaken();
    auto s = Slot{ &f };
    slots.emplace_back(&s);
    assert(!exitposted);
    slots_cond.wait(lock, [&] { return !s.func; });
}

void Synchronizer::waitForExit() const
{
    auto lock = std::unique_lock(mutables);
    main_blocked = true;
    while (true) {
        if (!slots.empty()) {
            process_slots(lock);
        } else if (exitposted) {
            exitposted = false;
            break;
        }
        main_cond.wait(lock);
    }
    main_blocked = false;
}

sigc::connection Synchronizer::connectExit(sigc::slot<void()> const &slot)
{
    return signal_exit.connect(slot);
}

void Synchronizer::awaken() const
{
    if (exitposted || !slots.empty()) {
        return;
    }

    if (main_blocked) {
        main_cond.notify_all();
    } else {
        const_cast<Glib::Dispatcher&>(dispatcher).emit(); // Glib::Dispatcher is const-incorrect.
    }
}

void Synchronizer::on_dispatcher() const
{
    auto lock = std::unique_lock(mutables);
    if (!slots.empty()) {
        process_slots(lock);
    } else if (exitposted) {
        exitposted = false;
        lock.unlock();
        signal_exit.emit();
    }
}

void Synchronizer::process_slots(std::unique_lock<std::mutex> &lock) const
{
    while (!slots.empty()) {
        auto slots_grabbed = std::move(slots);
        lock.unlock();
        for (auto &s : slots_grabbed) {
            (*s->func)();
        }
        lock.lock();
        for (auto &s : slots_grabbed) {
            s->func = nullptr;
        }
        slots_cond.notify_all();
    }
}

} // namespace Inkscape::UI::Widget

/*
  Local Variables:
  mode:c++
  c-file-style:"stroustrup"
  c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
  indent-tabs-mode:nil
  fill-column:99
  End:
*/
// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :