mainloop.c 11 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/* -*- mode: C; c-basic-offset: 4; indent-tabs-mode: nil; -*- */
/*
 * Copyright (c) 2008  litl, LLC
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

#include "mainloop.h"
25
#include <gjs/gjs-module.h>
26
#include <gjs/compat.h>
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44

#include "../gi/closure.h"

#include <util/log.h>

#include <glib.h>

#include <jsapi.h>

static GHashTable *pending_main_loops;

static JSBool
gjs_main_loop_quit(JSContext *context,
                      JSObject  *obj,
                      uintN      argc,
                      jsval     *argv,
                      jsval     *retval)
{
45
    char *cancel_id;
46
    GMainLoop *main_loop;
47

48 49 50
    if (!gjs_parse_args(context, "quit", "s", argc, argv,
                        "cancelId", &cancel_id))
      return JS_FALSE;
51 52 53 54

    main_loop = g_hash_table_lookup(pending_main_loops, cancel_id);

    if (!main_loop) {
55
        g_free(cancel_id);
56 57 58 59 60 61 62
        gjs_throw(context, "No main loop with this id");
        return JS_FALSE;
    }

    g_hash_table_remove(pending_main_loops, cancel_id);

    if (!g_main_loop_is_running(main_loop)) {
63
        g_free(cancel_id);
64 65 66 67 68 69 70 71 72
        gjs_throw(context, "Main loop was stopped already");
        return JS_FALSE;
    }

    gjs_debug(GJS_DEBUG_MAINLOOP,
              "main loop %s quitting in context %p",
              cancel_id,
              context);

73
    g_free(cancel_id);
74 75 76 77 78 79 80 81 82 83 84
    g_main_loop_quit(main_loop);
    return JS_TRUE;
}

static JSBool
gjs_main_loop_run(JSContext *context,
                     JSObject  *obj,
                     uintN      argc,
                     jsval     *argv,
                     jsval     *retval)
{
85
    char *cancel_id;
86 87
    GMainLoop *main_loop;

88 89 90
    if (!gjs_parse_args(context, "run", "s", argc, argv,
                        "cancelId", &cancel_id))
      return JS_FALSE;
91 92 93 94 95 96 97

    main_loop = g_hash_table_lookup(pending_main_loops, cancel_id);

    if (!main_loop) {
        main_loop = g_main_loop_new(NULL, FALSE);
        g_hash_table_replace(pending_main_loops, g_strdup(cancel_id), main_loop);
    } else {
98
        g_main_loop_ref(main_loop);
99 100 101 102 103 104
    }

    gjs_debug(GJS_DEBUG_MAINLOOP,
              "main loop %s being run in context %p",
              cancel_id,
              context);
105
    g_free(cancel_id);
106

107
    gjs_runtime_push_context(JS_GetRuntime(context), context);
108
    g_main_loop_run(main_loop);
109 110
    gjs_runtime_pop_context(JS_GetRuntime(context));

111 112 113 114 115 116 117 118 119 120
    g_main_loop_unref(main_loop);
    return JS_TRUE;
}

static gboolean
closure_source_func(void *data)
{
    jsval retval;
    GClosure *closure;
    JSBool bool_val;
121
    JSRuntime *runtime;
122 123 124 125
    JSContext *context;

    closure = data;

126
    if (!gjs_closure_is_valid(closure))
127
        return FALSE;
128 129 130 131

    runtime = gjs_closure_get_runtime(closure);
    context = gjs_runtime_get_current_context(runtime);

132
    JS_BeginRequest(context);
133 134

    retval = JSVAL_VOID;
135
    JS_AddValueRoot(context, &retval);
136 137 138 139 140 141 142 143 144

    gjs_closure_invoke(closure,
                          0, NULL,
                          &retval);

    /* ValueToBoolean pretty much always succeeds, just as
     * JavaScript always makes some sense of any value in
     * an "if (value) {}" context.
     */
145
    if (!JS_ValueToBoolean(context,
146 147 148
                           retval, &bool_val))
        bool_val = FALSE;

149
    JS_RemoveValueRoot(context, &retval);
150

151
    JS_EndRequest(context);
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
    return bool_val;
}

static void
closure_destroy_notify(void *data)
{
    GClosure *closure;

    closure = data;

    g_closure_invalidate(closure);
    g_closure_unref(closure);
}

static void
closure_invalidated(gpointer  data,
                    GClosure *closure)
{
    /* We may be invalidated because the source was removed and
     * destroy notify called, or we may be invalidated for an external
     * reason like JSContext destroy, in which case removing the
     * source here will call our destroy notify.
     *
     * If we're invalidated due to the source being removed, then
     * removing it here will be a no-op.
     */
    g_source_remove(GPOINTER_TO_UINT(data));
}

static JSBool
gjs_timeout_add(JSContext *context,
                   JSObject  *obj,
                   uintN      argc,
                   jsval     *argv,
                   jsval     *retval)
{
    GClosure *closure;
189 190
    JSObject *callback;
    guint32 interval;
191 192 193 194 195 196 197
    guint id;

    /* Best I can tell, there is no way to know if argv[1] is really
     * callable other than to just try it. Checking whether it's a
     * function will not detect native objects that provide
     * JSClass::call, for example.
     */
198 199 200
    if (!gjs_parse_args(context, "timeout_add", "uo", argc, argv,
                        "interval", &interval, "callback", &callback))
      return JS_FALSE;
201

202
    closure = gjs_closure_new(context, callback, "timeout");
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
    if (closure == NULL)
        return JS_FALSE;

    g_closure_ref(closure);
    g_closure_sink(closure);

    id = g_timeout_add_full(G_PRIORITY_DEFAULT,
                            interval,
                            closure_source_func,
                            closure,
                            closure_destroy_notify);

    /* this is needed to remove the timeout if the JSContext is
     * destroyed.
     */
    g_closure_add_invalidate_notifier(closure, GUINT_TO_POINTER(id),
                                      closure_invalidated);

    if (!JS_NewNumberValue(context, id, retval))
        return JS_FALSE;

    return JS_TRUE;
}

static JSBool
gjs_timeout_add_seconds(JSContext *context,
                           JSObject  *obj,
                           uintN      argc,
                           jsval     *argv,
                           jsval     *retval)
{
    GClosure *closure;
235 236
    JSObject *callback;
    guint32 interval;
237 238
    guint id;

239 240 241 242
    /* See comment for timeout_add above */
    if (!gjs_parse_args(context, "timeout_add_seconds", "uo", argc, argv,
                        "interval", &interval, "callback", &callback))
      return JS_FALSE;
243

244
    closure = gjs_closure_new(context, callback, "timeout_seconds");
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
    if (closure == NULL)
        return JS_FALSE;

    g_closure_ref(closure);
    g_closure_sink(closure);

    id = g_timeout_add_seconds_full(G_PRIORITY_DEFAULT,
                                    interval,
                                    closure_source_func,
                                    closure,
                                    closure_destroy_notify);

    /* this is needed to remove the timeout if the JSContext is
     * destroyed.
     */
    g_closure_add_invalidate_notifier(closure, GUINT_TO_POINTER(id),
                                      closure_invalidated);

    if (!JS_NewNumberValue(context, id, retval))
        return JS_FALSE;

    return JS_TRUE;
}

static JSBool
gjs_idle_add(JSContext *context,
                JSObject  *obj,
                uintN      argc,
                jsval     *argv,
                jsval     *retval)
{
276
    JSObject *callback;
277 278
    GClosure *closure;
    guint id;
279
    int priority = G_PRIORITY_DEFAULT_IDLE;
280

281 282 283 284 285
    /* Best I can tell, there is no way to know if argv[0] is really
     * callable other than to just try it. Checking whether it's a
     * function will not detect native objects that provide
     * JSClass::call, for example.
     */
286 287 288
    if (!gjs_parse_args(context, "idle_add", "o|i", argc, argv,
                        "callback", &callback, "priority", &priority))
      return JS_FALSE;
289

290
    closure = gjs_closure_new(context, callback, "idle");
291 292 293 294 295 296
    if (closure == NULL)
        return JS_FALSE;

    g_closure_ref(closure);
    g_closure_sink(closure);

297
    id = g_idle_add_full(priority,
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
                         closure_source_func,
                         closure,
                         closure_destroy_notify);

    /* this is needed to remove the idle if the JSContext is
     * destroyed.
     */
    g_closure_add_invalidate_notifier(closure, GUINT_TO_POINTER(id),
                                      closure_invalidated);

    if (!JS_NewNumberValue(context, id, retval))
        return JS_FALSE;

    return JS_TRUE;
}

static JSBool
gjs_source_remove(JSContext *context,
                     JSObject  *obj,
                     uintN      argc,
                     jsval     *argv,
                     jsval     *retval)
{
321
    guint32 source_id;
322 323
    gboolean success;

324 325 326
    if (!gjs_parse_args(context, "source_remove", "u", argc, argv,
                        "sourceId", &source_id))
      return JS_FALSE;
327

328
    success = g_source_remove(source_id);
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382

    *retval = BOOLEAN_TO_JSVAL(success);

    return JS_TRUE;
}

JSBool
gjs_define_mainloop_stuff(JSContext      *context,
                             JSObject      *module_obj)
{
    // FIXME this should be per JSObject, and we should free it when
    // the object is finalized
    pending_main_loops = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, NULL);

    if (!JS_DefineFunction(context, module_obj,
                           "run",
                           gjs_main_loop_run,
                           1, GJS_MODULE_PROP_FLAGS))
        return JS_FALSE;

    if (!JS_DefineFunction(context, module_obj,
                           "quit",
                           gjs_main_loop_quit,
                           1, GJS_MODULE_PROP_FLAGS))
        return JS_FALSE;

    if (!JS_DefineFunction(context, module_obj,
                           "idle_add",
                           gjs_idle_add,
                           1, GJS_MODULE_PROP_FLAGS))
        return JS_FALSE;

    if (!JS_DefineFunction(context, module_obj,
                           "timeout_add",
                           gjs_timeout_add,
                           2, GJS_MODULE_PROP_FLAGS))
        return JS_FALSE;

    if (!JS_DefineFunction(context, module_obj,
                           "timeout_add_seconds",
                           gjs_timeout_add_seconds,
                           2, GJS_MODULE_PROP_FLAGS))
        return JS_FALSE;

    if (!JS_DefineFunction(context, module_obj,
                           "source_remove",
                           gjs_source_remove,
                           1, GJS_MODULE_PROP_FLAGS))
        return JS_FALSE;

    return JS_TRUE;
}

GJS_REGISTER_NATIVE_MODULE("mainloop", gjs_define_mainloop_stuff)