summaryrefslogtreecommitdiff
path: root/modules/script/mainloop.js
blob: 029e2805d00d266337741fd556000786f1b53073 (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
/* -*- mode: js; indent-tabs-mode: nil; -*- */
// SPDX-License-Identifier: MIT OR LGPL-2.0-or-later
// SPDX-FileCopyrightText: 2012 Giovanni Campagna <scampa.giovanni@gmail.com>

/* exported idle_add, idle_source, quit, run, source_remove, timeout_add,
timeout_add_seconds, timeout_seconds_source, timeout_source */

// A layer of convenience and backwards-compatibility over GLib MainLoop facilities

const GLib = imports.gi.GLib;
const GObject = imports.gi.GObject;

var _mainLoops = {};

function run(name) {
    if (!_mainLoops[name])
        _mainLoops[name] = GLib.MainLoop.new(null, false);

    _mainLoops[name].run();
}

function quit(name) {
    if (!_mainLoops[name])
        throw new Error('No main loop with this id');

    let loop = _mainLoops[name];
    _mainLoops[name] = null;

    if (!loop.is_running())
        throw new Error('Main loop was stopped already');

    loop.quit();
}

// eslint-disable-next-line camelcase
function idle_source(handler, priority) {
    let s = GLib.idle_source_new();
    GObject.source_set_closure(s, handler);
    if (priority !== undefined)
        s.set_priority(priority);
    return s;
}

// eslint-disable-next-line camelcase
function idle_add(handler, priority) {
    return idle_source(handler, priority).attach(null);
}

// eslint-disable-next-line camelcase
function timeout_source(timeout, handler, priority) {
    let s = GLib.timeout_source_new(timeout);
    GObject.source_set_closure(s, handler);
    if (priority !== undefined)
        s.set_priority(priority);
    return s;
}

// eslint-disable-next-line camelcase
function timeout_seconds_source(timeout, handler, priority) {
    let s = GLib.timeout_source_new_seconds(timeout);
    GObject.source_set_closure(s, handler);
    if (priority !== undefined)
        s.set_priority(priority);
    return s;
}

// eslint-disable-next-line camelcase
function timeout_add(timeout, handler, priority) {
    return timeout_source(timeout, handler, priority).attach(null);
}

// eslint-disable-next-line camelcase
function timeout_add_seconds(timeout, handler, priority) {
    return timeout_seconds_source(timeout, handler, priority).attach(null);
}

// eslint-disable-next-line camelcase
function source_remove(id) {
    return GLib.source_remove(id);
}