|
| 1 | +/* This Source Code Form is subject to the terms of the Mozilla Public |
| 2 | + * License, v. 2.0. If a copy of the MPL was not distributed with this |
| 3 | + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
| 4 | + |
| 5 | +use std::ptr; |
| 6 | +use std::sync::mpsc::channel; |
| 7 | +use std::thread; |
| 8 | + |
| 9 | +use mozjs::jsapi::GCContext; |
| 10 | +use mozjs::jsapi::JSCLASS_FOREGROUND_FINALIZE; |
| 11 | +use mozjs::jsapi::{JSClass, JSClassOps, JSObject, OnNewGlobalHookOption}; |
| 12 | +use mozjs::realm::AutoRealm; |
| 13 | +use mozjs::rooted; |
| 14 | +use mozjs::rust::wrappers2::{JS_NewGlobalObject, JS_NewObject}; |
| 15 | +use mozjs::rust::{JSEngine, RealmOptions, Runtime, SIMPLE_GLOBAL_CLASS}; |
| 16 | + |
| 17 | +fn main() { |
| 18 | + println!("Hello, world!"); |
| 19 | + let engine = JSEngine::init().expect("Could not init JSEngine"); |
| 20 | + println!("JSEngine initialized"); |
| 21 | + let mut runtime = Runtime::new(engine.handle()); |
| 22 | + println!("Runtime initialized"); |
| 23 | + let context = runtime.cx(); |
| 24 | + let h_option = OnNewGlobalHookOption::FireOnNewGlobalHook; |
| 25 | + let c_option = RealmOptions::default(); |
| 26 | + |
| 27 | + unsafe { |
| 28 | + rooted!(&in(context) let global = JS_NewGlobalObject( |
| 29 | + context, |
| 30 | + &SIMPLE_GLOBAL_CLASS, |
| 31 | + ptr::null_mut(), |
| 32 | + h_option, |
| 33 | + &*c_option, |
| 34 | + )); |
| 35 | + let mut realm = AutoRealm::new_from_handle(context, global.handle()); |
| 36 | + let context = &mut realm; |
| 37 | + rooted!(&in(context) let _object = JS_NewObject(context, &CLASS as *const _)); |
| 38 | + } |
| 39 | + |
| 40 | + let parent = runtime.prepare_for_new_child(); |
| 41 | + let (sender, receiver) = channel(); |
| 42 | + thread::spawn(move || { |
| 43 | + let runtime = unsafe { Runtime::create_with_parent(parent) }; |
| 44 | + assert!(Runtime::get().is_some()); |
| 45 | + drop(runtime); |
| 46 | + let _ = sender.send(()); |
| 47 | + }); |
| 48 | + let _ = receiver.recv(); |
| 49 | + println!("Example ran without issues..."); |
| 50 | +} |
| 51 | + |
| 52 | +unsafe extern "C" fn finalize(_fop: *mut GCContext, _object: *mut JSObject) { |
| 53 | + assert!(Runtime::get().is_some()); |
| 54 | +} |
| 55 | + |
| 56 | +static CLASS_OPS: JSClassOps = JSClassOps { |
| 57 | + addProperty: None, |
| 58 | + delProperty: None, |
| 59 | + enumerate: None, |
| 60 | + newEnumerate: None, |
| 61 | + resolve: None, |
| 62 | + mayResolve: None, |
| 63 | + finalize: Some(finalize), |
| 64 | + call: None, |
| 65 | + construct: None, |
| 66 | + trace: None, |
| 67 | +}; |
| 68 | + |
| 69 | +static CLASS: JSClass = JSClass { |
| 70 | + name: c"EventTargetPrototype".as_ptr(), |
| 71 | + flags: JSCLASS_FOREGROUND_FINALIZE, |
| 72 | + cOps: &CLASS_OPS as *const JSClassOps, |
| 73 | + spec: ptr::null(), |
| 74 | + ext: ptr::null(), |
| 75 | + oOps: ptr::null(), |
| 76 | +}; |
0 commit comments