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
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
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
189
190
191
192
193
194
195
196
#![feature(offset_to)]

use std::ptr;
use std::rc::Rc;

// These functions are used in macros, so sometimes they will be considered dead.
extern "C" {
    #[allow(dead_code)]
    pub fn emscripten_run_script(s: *const std::os::raw::c_char);
    #[allow(dead_code)]
    pub fn emscripten_run_script_int(s: *const std::os::raw::c_char) -> std::os::raw::c_int;
    #[allow(dead_code)]
    pub fn emscripten_run_script_string(s: *const std::os::raw::c_char) -> *const std::os::raw::c_char;
    
    #[allow(dead_code)]
    pub fn emscripten_asm_const(s: *const std::os::raw::c_char);
    #[allow(dead_code)]
    pub fn emscripten_asm_const_int(s: *const std::os::raw::c_char, ...) -> std::os::raw::c_int;
    #[allow(dead_code)]
    pub fn emscripten_asm_const_double(s: *const std::os::raw::c_char, ...) -> std::os::raw::c_double;
    #[allow(dead_code)]
    pub fn emscripten_pause_main_loop();
    #[allow(dead_code)]
    pub fn emscripten_set_main_loop(m: extern fn(), fps: std::os::raw::c_int, infinite: std::os::raw::c_int);

    pub fn free(p: *mut u8);
}

pub fn string_from_js(ptr: *mut u16) -> String {
    unsafe {
        let size : u32 = *(ptr as *const _ as *const u32);
        let string_slice : &'static [u16] = std::slice::from_raw_parts(ptr, size as usize);
        let result = String::from_utf16_lossy(string_slice);
        free(ptr as *mut _);
        result
    }
}

pub fn js_eval(code: &'static [u8]) {
    unsafe {
        emscripten_asm_const(code as *const _ as *const std::os::raw::c_char);
    }
}

        
#[macro_export]
macro_rules! __js_macro {
    ( $emscr_func:ident, $jscode:expr, $($args:expr),* ) => {
        {
            let jscode : &'static [u8] = concat!($jscode, "\0").as_bytes();
            unsafe {
                $crate::$emscr_func(jscode as *const _ as *const std::os::raw::c_char,
                                    $( $crate::JSObject::from($args).value ),* )
            }
        }
    };
}    

#[macro_export]
macro_rules! js {
    ($jscode:expr $(, $args:expr)*) => {
        __js_macro!(emscripten_asm_const_int, $jscode, $($args),*)
    }
}

#[macro_export]
macro_rules! js_obj {
    ($jscode:expr $(, $args:expr )*) => (
        $crate::JSObject {
            value: __js_macro!(emscripten_asm_const_int, $jscode, $($args),*) as f64,
            jshandle: true,
            refcount: Rc::new(()),
        }
    )
}

#[macro_export]
macro_rules! js_int {
    ($jscode:expr $(, $args:expr )*) => (
        __js_macro!(emscripten_asm_const_int, $jscode, $($args),*)
    )
}

#[macro_export]
macro_rules! js_double {
    ($jscode:expr $(, $args:expr )*) => (
        __js_macro!(emscripten_asm_const_double, $jscode, $($args),*);
    )
}

#[derive(Clone)]
pub struct JSObject {
    pub value: f64,
    pub jshandle: bool,
    pub refcount: Rc<()>,
}

// impl<'a, T> std::convert::From<&'a T> for JSObject
//     where JSObject: std::convert::From<T>, T: Clone {
//     fn from(v: &'a T) -> Self {
//         JSObject::from(v.clone())
//     }
// }

impl<'a> std::convert::From<&'a JSObject> for JSObject {
    fn from(v: &'a JSObject) -> Self {
        JSObject::from(v.clone())
    }
}

impl Drop for JSObject {
    fn drop(&mut self) {
        if self.jshandle && Rc::strong_count(&self.refcount) == 1 {
            let code : &'static [u8] = b"RFRAME.releaseObject($0);\0";
            unsafe {
                emscripten_asm_const_int(code as *const _ as *const std::os::raw::c_char, self.value);
            }
        }
    }
}

impl<T> std::convert::From<Vec<T>> for JSObject
    where JSObject: std::convert::From<T> {
    fn from(v: Vec<T>) -> Self {
        let arr = js_obj!("return RFRAME.storeObject([]);");
        for elem in v {
            let elem_js = JSObject::from(elem);
            let code : &'static [u8] = if elem_js.jshandle {
                b"RFRAME.loadObject($0).push(RFRAME.loadObject($1))\0"
            } else {
                b"RFRAME.loadObject($0).push($1)\0"
            };
            unsafe {
                emscripten_asm_const_int(code as *const _ as *const std::os::raw::c_char,
                                         arr.value, elem_js.value);
            }
        }
        arr
    }
}

macro_rules! __js_from_numeric {
    ( $( $type:ty ),+ ) => (
        $(
            impl std::convert::From<$type> for JSObject {
                fn from(v: $type) -> Self {
                    JSObject {
                        value: v as f64,
                        jshandle: false,
                        refcount: Rc::new(()),
                    }
                }
            }
        )+
    )
}

__js_from_numeric!(isize, usize, i32, u32, i16, u16, i8, u8, f32, f64);

impl<'a> std::convert::From<&'a str> for JSObject {
    fn from(s: &'a str) -> Self { // TODO: This won't work when the pointer can't fit in 31bit int.
        let code : &'static [u8] = b"return RFRAME.storeObject(RFRAME.copyStringFromHeap($0, $1));\0";
        let data : Vec<u16> = s.encode_utf16().collect();
        let data_ptr_as_isize = ptr::null::<u16>().offset_to(data.as_ptr()).unwrap_or(0) * 2;
        unsafe {
            JSObject {
                value: emscripten_asm_const_int(code as *const _ as *const std::os::raw::c_char,
                                                 data_ptr_as_isize, data.len()) as f64,
                jshandle: true,
                refcount: Rc::new(()),
            }
        }
    }
}

impl<'a> std::convert::From<&'a String> for JSObject {
    fn from(s: &'a String) -> Self {
        JSObject::from(s.as_str())
    }
}

impl std::convert::From<String> for JSObject {
    fn from(s: String) -> Self {
        JSObject::from(s.as_str())
    }
}

impl std::convert::From<bool> for JSObject {
    fn from(b: bool) -> Self {
        JSObject {
            value: if b { 1.0 } else { 0.0 },
            jshandle: false,
            refcount: Rc::new(()),
        }
    }
}