aboutsummaryrefslogtreecommitdiff
path: root/tools/plink/callback.c
blob: c70dc53fb85fb06d5de6b77ac872833dbee8a22a (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
/*
 * Facility for queueing callback functions to be run from the
 * top-level event loop after the current top-level activity finishes.
 */

#include <stddef.h>

#include "putty.h"

struct callback {
    struct callback *next;

    toplevel_callback_fn_t fn;
    void *ctx;
};

struct callback *cbhead = NULL, *cbtail = NULL;

toplevel_callback_notify_fn_t notify_frontend = NULL;
void *frontend = NULL;

void request_callback_notifications(toplevel_callback_notify_fn_t fn,
                                    void *fr)
{
    notify_frontend = fn;
    frontend = fr;
}

void queue_toplevel_callback(toplevel_callback_fn_t fn, void *ctx)
{
    struct callback *cb;

    cb = snew(struct callback);
    cb->fn = fn;
    cb->ctx = ctx;

    /* If the front end has requested notification of pending
     * callbacks, and we didn't already have one queued, let it know
     * we do have one now. */
    if (notify_frontend && !cbhead)
        notify_frontend(frontend);

    if (cbtail)
        cbtail->next = cb;
    else
        cbhead = cb;
    cbtail = cb;
    cb->next = NULL;
}

void run_toplevel_callbacks(void)
{
    if (cbhead) {
        struct callback *cb = cbhead;
        /*
         * Careful ordering here. We call the function _before_
         * advancing cbhead (though, of course, we must free cb
         * _after_ advancing it). This means that if the very last
         * callback schedules another callback, cbhead does not become
         * NULL at any point, and so the frontend notification
         * function won't be needlessly pestered.
         */
        cb->fn(cb->ctx);
        cbhead = cb->next;
        sfree(cb);
        if (!cbhead)
            cbtail = NULL;
    }
}

int toplevel_callback_pending(void)
{
    return cbhead != NULL;
}