ultralight 0.1.7

Rust bindings for Ultralight: Next-Generation HTML Renderer
Documentation
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
197
198
199
200
201
202
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
235
236
237
238
239
240
241
242
243
244
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
use crate::{
    sys::{
        ulViewLockJSContext, ulViewUnlockJSContext, JSContextGetGlobalObject, JSContextRef,
        JSEvaluateScript, JSObjectCallAsFunction, JSObjectGetProperty, JSObjectGetPropertyAtIndex,
        JSObjectMake, JSObjectMakeArray, JSObjectMakeFunctionWithCallback,
        JSObjectMakeTypedArrayWithArrayBuffer, JSObjectRef, JSObjectSetProperty,
        JSStringCreateWithUTF8CString, JSStringRelease,
        JSTypedArrayType_kJSTypedArrayTypeFloat32Array, JSValueIsArray, JSValueMakeNumber,
        JSValueMakeString, JSValueRef, JSValueToNumber, JSValueToObject,
    },
    View,
};
use std::{ffi::CString, os::raw::c_void, ptr::null_mut};

pub type RustCallback = dyn FnMut(&JSContext<'_>, &[JSValueRef]);

pub trait IntoJSValue {
    fn into_value(self, ctx: &JSContext<'_>) -> JSValueRef;
    fn from_value(ctx: &JSContext<'_>, value: JSValueRef) -> Self
    where
        Self: Sized,
    {
        let _ = ctx;
        let _ = value;
        unimplemented!();
    }
}

pub trait FromJSValue {
    fn from_value(self, ctx: &JSContext<'_>, value: JSValueRef) -> JSValueRef;
}

impl IntoJSValue for &str {
    fn into_value(self, ctx: &JSContext<'_>) -> JSValueRef {
        let string = CString::new(self).unwrap();
        unsafe {
            let utf8 = JSStringCreateWithUTF8CString(string.as_ptr());
            let value = JSValueMakeString(ctx.inner, utf8);
            JSStringRelease(utf8);
            value
        }
    }
}

impl IntoJSValue for f64 {
    fn into_value(self, ctx: &JSContext<'_>) -> JSValueRef {
        unsafe { JSValueMakeNumber(ctx.inner, self) }
    }

    fn from_value(ctx: &JSContext<'_>, value: JSValueRef) -> Self {
        unsafe { JSValueToNumber(ctx.inner, value, null_mut()) }
    }
}

impl IntoJSValue for f32 {
    fn into_value(self, ctx: &JSContext<'_>) -> JSValueRef {
        unsafe { JSValueMakeNumber(ctx.inner, self as f64) }
    }

    fn from_value(ctx: &JSContext<'_>, value: JSValueRef) -> Self {
        unsafe { JSValueToNumber(ctx.inner, value, null_mut()) as Self }
    }
}

impl IntoJSValue for u32 {
    fn into_value(self, ctx: &JSContext<'_>) -> JSValueRef {
        unsafe { JSValueMakeNumber(ctx.inner, self as f64) }
    }

    fn from_value(ctx: &JSContext<'_>, value: JSValueRef) -> Self {
        unsafe { JSValueToNumber(ctx.inner, value, null_mut()) as Self }
    }
}

impl IntoJSValue for String {
    fn into_value(self, ctx: &JSContext<'_>) -> JSValueRef {
        let string = CString::new(self).unwrap();
        unsafe {
            let utf8 = JSStringCreateWithUTF8CString(string.as_ptr());
            let value = JSValueMakeString(ctx.inner, utf8);
            JSStringRelease(utf8);
            value
        }
    }
}

impl<T: IntoJSValue> IntoJSObject for T {
    fn into_obj<'a>(self, ctx: &'a JSContext<'a>) -> JSObject<'a> {
        JSObject::from_value(ctx, self.into_value(ctx))
    }
}

pub trait IntoJSObject {
    fn into_obj<'a>(self, ctx: &'a JSContext<'a>) -> JSObject<'a>;
}

impl IntoJSObject for &[&str] {
    fn into_obj<'a>(self, ctx: &'a JSContext<'a>) -> JSObject<'a> {
        let array = self
            .iter()
            .map(|name| name.into_value(ctx))
            .collect::<Vec<_>>();

        let inner =
            unsafe { JSObjectMakeArray(ctx.inner, array.len(), array.as_ptr(), null_mut()) };

        JSObject::from_object(ctx, inner)
    }
}

pub fn test2<'a>(ctx: &'a JSContext<'a>, obj: JSValueRef) -> bool {
    unsafe { JSValueIsArray(ctx.inner, obj) }
}

pub fn test<'a, const N: usize>(ctx: &'a JSContext<'a>, array: [f32; N]) -> JSObject<'a> {
    let array = array
        .into_iter()
        .map(|v| v.into_obj(ctx).inner)
        .collect::<Vec<_>>();

    let array_buffer = unsafe {
        JSObjectMakeArray(
            ctx.inner,
            array.len(),
            array.as_ptr() as *const _,
            null_mut(),
        )
    };

    let inner = unsafe {
        JSObjectMakeTypedArrayWithArrayBuffer(
            ctx.inner,
            JSTypedArrayType_kJSTypedArrayTypeFloat32Array,
            array_buffer,
            null_mut(),
        )
    };

    JSObject::from_object(ctx, inner)
}

impl<T, const N: usize> IntoJSObject for [T; N]
where
    T: IntoJSObject,
{
    fn into_obj<'a>(self, ctx: &'a JSContext<'a>) -> JSObject<'a> {
        let array = self
            .into_iter()
            .map(|v| v.into_obj(ctx).inner)
            .collect::<Vec<_>>();

        let inner = unsafe {
            JSObjectMakeArray(
                ctx.inner,
                array.len(),
                array.as_ptr() as *const _,
                null_mut(),
            )
        };
        JSObject::from_object(ctx, inner)
    }
}

impl<T> IntoJSObject for Vec<T>
where
    T: IntoJSObject,
{
    fn into_obj<'a>(self, ctx: &'a JSContext<'a>) -> JSObject<'a> {
        let array = self
            .into_iter()
            .map(|v| v.into_obj(ctx).inner)
            .collect::<Vec<_>>();

        let inner = unsafe {
            JSObjectMakeArray(
                ctx.inner,
                array.len(),
                array.as_ptr() as *const _,
                null_mut(),
            )
        };
        JSObject::from_object(ctx, inner)
    }
}

impl<const N: usize> IntoJSObject for [JSObjectRef; N] {
    fn into_obj<'a>(self, ctx: &'a JSContext<'a>) -> JSObject<'a> {
        let inner = unsafe {
            JSObjectMakeArray(
                ctx.into(),
                self.len(),
                self.as_ptr() as *const _,
                null_mut(),
            )
        };
        JSObject::from_object(ctx, inner)
    }
}

pub struct JSContext<'a> {
    owner: Option<&'a View>,
    inner: JSContextRef,
}

impl<'a> JSContext<'a> {
    pub fn new(view: &'a View) -> Self {
        let context = unsafe { ulViewLockJSContext(view.into()) };
        Self {
            owner: Some(view),
            inner: context,
        }
    }

    pub fn get_global_object(&self) -> JSObject<'_> {
        let global_object = unsafe { JSContextGetGlobalObject(self.inner) };
        JSObject::from_object(self, global_object)
    }

    // TODO: Return option
    // TODO: Wrap in wrapper so you can call functions directly?
    pub fn get_function(&self, name: &str) -> JSObjectRef {
        let name = CString::new(name).unwrap();

        unsafe {
            let name = JSStringCreateWithUTF8CString(name.as_ptr());
            let func = JSEvaluateScript(self.inner, name, null_mut(), null_mut(), 0, null_mut());
            JSStringRelease(name);
            JSValueToObject(self.inner, func, null_mut())
        }
    }

    pub fn call_function(&self, func: JSObjectRef, arguments: Vec<JSObject<'_>>) -> JSValueRef {
        let arguments: Vec<_> = arguments.iter().map(|o| o.inner).collect();

        unsafe {
            JSObjectCallAsFunction(
                self.inner,
                func,
                null_mut(),
                arguments.len(),
                arguments.as_ptr() as _,
                null_mut(),
            )
        }
    }
}

impl Drop for JSContext<'_> {
    fn drop(&mut self) {
        if let Some(owner) = self.owner.take() {
            unsafe {
                ulViewUnlockJSContext(owner.into());
            }
        }
    }
}

impl From<JSContextRef> for JSContext<'_> {
    fn from(value: JSContextRef) -> Self {
        Self {
            owner: None,
            inner: value,
        }
    }
}

impl From<&JSContext<'_>> for JSContextRef {
    fn from(value: &JSContext<'_>) -> Self {
        value.inner
    }
}

/* ========================= */
/*         JSObject          */
/* ========================= */

pub struct JSObject<'a> {
    ctx: &'a JSContext<'a>,
    inner: JSObjectRef,
}

impl<'a> JSObject<'a> {
    pub fn new(ctx: &'a JSContext<'a>) -> Self {
        let inner = unsafe { JSObjectMake(ctx.into(), null_mut(), null_mut()) };

        Self { ctx, inner }
    }

    // TODO: Make private as its build using a sys type.
    pub fn from_object(ctx: &'a JSContext<'a>, inner: JSObjectRef) -> Self {
        Self { ctx, inner }
    }

    // TODO: Make private as its build using a sys type.
    pub fn from_value(ctx: &'a JSContext<'a>, inner: JSValueRef) -> Self {
        Self {
            ctx,
            inner: inner as _,
        }
    }

    pub fn set_property(&mut self, name: &str, property_object: impl IntoJSObject) {
        unsafe {
            let name = CString::new(name).unwrap();
            let name = JSStringCreateWithUTF8CString(name.as_ptr());
            JSObjectSetProperty(
                self.ctx.into(),
                self.inner,
                name,
                property_object.into_obj(self.ctx).inner,
                0,
                null_mut(),
            );
            JSStringRelease(name);
        }
    }

    pub fn get_property(&self, name: &str) -> JSValueRef {
        unsafe {
            let name = CString::new(name).unwrap();
            let name = JSStringCreateWithUTF8CString(name.as_ptr());
            let value = JSObjectGetProperty(self.ctx.into(), self.inner, name, null_mut());
            JSStringRelease(name);
            value
        }
    }

    /// TODO: This is very hacky...
    pub fn as_vec3(&self) -> [f32; 3] {
        unsafe {
            [
                f32::from_value(
                    self.ctx.into(),
                    JSObjectGetPropertyAtIndex(self.ctx.into(), self.inner, 0, null_mut()),
                ),
                f32::from_value(
                    self.ctx.into(),
                    JSObjectGetPropertyAtIndex(self.ctx.into(), self.inner, 1, null_mut()),
                ),
                f32::from_value(
                    self.ctx.into(),
                    JSObjectGetPropertyAtIndex(self.ctx.into(), self.inner, 2, null_mut()),
                ),
            ]
        }
    }

    /// TODO: This is very hacky...
    pub fn as_vec4(&self) -> [f32; 4] {
        unsafe {
            [
                f32::from_value(
                    self.ctx.into(),
                    JSObjectGetPropertyAtIndex(self.ctx.into(), self.inner, 0, null_mut()),
                ),
                f32::from_value(
                    self.ctx.into(),
                    JSObjectGetPropertyAtIndex(self.ctx.into(), self.inner, 1, null_mut()),
                ),
                f32::from_value(
                    self.ctx.into(),
                    JSObjectGetPropertyAtIndex(self.ctx.into(), self.inner, 2, null_mut()),
                ),
                f32::from_value(
                    self.ctx.into(),
                    JSObjectGetPropertyAtIndex(self.ctx.into(), self.inner, 3, null_mut()),
                ),
            ]
        }
    }

    pub fn set_rust_callback(&mut self, function_name: &str, callback: Box<Box<RustCallback>>) {
        unsafe {
            // callback field
            let func_obj = {
                let prop_name = CString::new(function_name).unwrap();
                let prop_name = JSStringCreateWithUTF8CString(prop_name.as_ptr());
                let func = JSObjectMakeFunctionWithCallback(
                    self.ctx.into(),
                    prop_name,
                    Some(callback_wrapper),
                );
                JSObjectSetProperty(self.ctx.into(), self.inner, prop_name, func, 0, null_mut());
                JSStringRelease(prop_name);

                func
            };

            // private callback field
            {
                let prop_name = CString::new("internalpointer").unwrap();
                let prop_name = JSStringCreateWithUTF8CString(prop_name.as_ptr());

                // TODO: I think this is a memory leak.
                // TODO: Actually im pretty sure. See https://stackoverflow.com/questions/32270030/how-do-i-convert-a-rust-closure-to-a-c-style-callback to how to unset
                let func_pointer = Box::into_raw(callback) as *mut _;

                let func = JSValueMakeNumber(self.ctx.into(), f64::from_bits(func_pointer as u64));
                JSObjectSetProperty(self.ctx.into(), func_obj, prop_name, func, 0, null_mut());
                JSStringRelease(prop_name);
            }
        }
    }
}

impl From<&JSObject<'_>> for JSObjectRef {
    fn from(value: &JSObject<'_>) -> Self {
        value.inner
    }
}

impl Drop for JSObject<'_> {
    fn drop(&mut self) {}
}

/// Wraps rust callbacks for `JSObject`
extern "C" fn callback_wrapper(
    ctx: JSContextRef,
    function: JSObjectRef,
    _this_object: JSObjectRef,
    argument_count: usize,
    arguments: *const JSValueRef,
    _exception: *mut JSValueRef,
) -> JSValueRef {
    unsafe {
        let prop_name = CString::new("internalpointer").unwrap();
        let prop_name = JSStringCreateWithUTF8CString(prop_name.as_ptr());
        let internalpointer = JSObjectGetProperty(ctx, function, prop_name, null_mut());
        JSStringRelease(prop_name);

        let ptr =
            JSValueToNumber(ctx, internalpointer, null_mut()).to_bits() as usize as *mut c_void;
        let closure: &mut Box<RustCallback> = std::mem::transmute(ptr);

        // Closure arguments
        let ctx = JSContext::from(ctx);
        let arguments = std::slice::from_raw_parts(arguments, argument_count);

        closure(&ctx, arguments);
    }

    std::ptr::null()
}