Skip to main content

script/engine/
handle.rs

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 https://mozilla.org/MPL/2.0/. */
4
5use std::sync::Mutex;
6use std::thread;
7use std::time::Duration;
8
9use js::rust::{JSEngine, JSEngineHandle};
10
11static JS_ENGINE: Mutex<Option<JSEngineHandle>> = Mutex::new(None);
12
13pub(crate) fn current_js_engine_handle() -> JSEngineHandle {
14    JS_ENGINE.lock().unwrap().as_ref().unwrap().clone()
15}
16
17pub struct JSEngineSetup(JSEngine);
18
19impl Default for JSEngineSetup {
20    fn default() -> Self {
21        let engine = JSEngine::init().unwrap();
22        *JS_ENGINE.lock().unwrap() = Some(engine.handle());
23        Self(engine)
24    }
25}
26
27impl Drop for JSEngineSetup {
28    fn drop(&mut self) {
29        *JS_ENGINE.lock().unwrap() = None;
30
31        while !self.0.can_shutdown() {
32            thread::sleep(Duration::from_millis(50));
33        }
34    }
35}