slint-ui 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.md ADDED
@@ -0,0 +1,6 @@
1
+ # Slint License
2
+
3
+ Slint is available under either a [commercial license](LICENSES/LicenseRef-Slint-commercial.md)
4
+ or at your choice under [GPL 3.0](LICENSES/GPL-3.0-only.txt).
5
+
6
+ Third party licenses listed in the `LICENSES` folder also apply to parts of the product.
package/README.md ADDED
@@ -0,0 +1,146 @@
1
+ # Slint-node
2
+
3
+ [![npm](https://img.shields.io/npm/v/slint-ui)](https://www.npmjs.com/package/slint-ui)
4
+
5
+ [Slint](https://slint-ui.com/) is a UI toolkit that supports different programming languages.
6
+ Slint-node is the integration with node.
7
+
8
+ The complete Node documentation can be viewed online at https://slint-ui.com/docs/node/.
9
+
10
+ **Warning: Pre-Alpha**
11
+ Slint is still in the early stages of development: APIs will change and important features are still being developed.
12
+
13
+ ## Installing Slint
14
+
15
+ Slint is available via NPM, so you can install by running the following command:
16
+
17
+ ```sh
18
+ npm install slint-ui
19
+ ```
20
+
21
+ ## Using Slint
22
+
23
+ To initialize the API, you first need to import the `slint-ui` module in our code:
24
+
25
+ ```js
26
+ let slint = require("slint-ui");
27
+ ```
28
+
29
+ This step also installs a hook in NodeJS that allows you to import `.slint` files directly:
30
+
31
+ ```js
32
+ let ui = require("../ui/main.slint");
33
+ ```
34
+
35
+ Combining these two steps leads us to the obligatory "Hello World" example:
36
+
37
+ ```js
38
+ require("slint-ui");
39
+ let ui = require("../ui/main.slint");
40
+ let main = new ui.Main();
41
+ main.run();
42
+ ```
43
+
44
+ See [/examples/printerdemo/node](/examples/printerdemo/node) for a full example.
45
+
46
+ ## API Overview
47
+
48
+ ### Instantiating a component
49
+
50
+ The exported component is exposed as a type constructor. The type constructor takes as parameter
51
+ an object which allow to initialize the value of public properties or callbacks.
52
+
53
+ ```js
54
+ require("slint-ui");
55
+ // In this example, the main.slint file exports a module which
56
+ // has a counter property and a clicked callback
57
+ let ui = require("ui/main.slint");
58
+ let component = new ui.MainWindow({
59
+ counter: 42,
60
+ clicked: function() { console.log("hello"); }
61
+ });
62
+ ```
63
+
64
+ ### Accessing a property
65
+
66
+ Properties are exposed as properties on the component instance
67
+
68
+ ```js
69
+ component.counter = 42;
70
+ console.log(component.counter);
71
+ ```
72
+
73
+ ### Callbacks
74
+
75
+ The callbacks are also exposed as property that have a setHandler function, and that can can be called.
76
+
77
+ ```js
78
+ // connect to a callback
79
+ component.clicked.setHandler(function() { console.log("hello"); })
80
+ // emit a callback
81
+ component.clicked();
82
+ ```
83
+
84
+ ### Type Mappings
85
+
86
+ | `.slint` Type | JavaScript Type | Notes |
87
+ | --- | --- | --- |
88
+ | `int` | `Number` | |
89
+ | `float` | `Number` | |
90
+ | `string` | `String` | |
91
+ | `color` | `String` | Colors are represented as strings in the form `"#rrggbbaa"`. When setting a color property, any CSS compliant color is accepted as a string. |
92
+ | `length` | `Number` | |
93
+ | `physical_length` | `Number` | |
94
+ | `duration` | `Number` | The number of milliseconds |
95
+ | `angle` | `Number` | The value in degrees |
96
+ | structure | `Object` | Structures are mapped to JavaScrip objects with structure fields mapped to properties. |
97
+ | array | `Array` or Model Object | |
98
+
99
+ ### Models
100
+
101
+ For property of array type, they can either be set using an array.
102
+ In that case, getting the property also return an array.
103
+ If the array was set within the .slint file, the array can be obtained
104
+
105
+ ```js
106
+ component.model = [1, 2, 3];
107
+ // component.model.push(4); // does not work, because it operate on a copy
108
+ // but re-assigning works
109
+ component.model = component.model.concat(4);
110
+ ```
111
+
112
+ Another option is to set a model object. A model object has the following function:
113
+
114
+ * `rowCount()`: returns the number of element in the model.
115
+ * `rowData(index)`: return the row at the given index
116
+ * `setRowData(index, data)`: called when the model need to be changed. `this.notify.rowDataChanged` must be called if successful.
117
+
118
+ When such an object is set to a model property, it gets a new `notify` object with the following function
119
+
120
+ * `rowDataChanged(index)`: notify the view that the row was changed.
121
+ * `rowAdded(index, count)`: notify the view that rows were added.
122
+ * `rowRemoved(index, count)`: notify the view that a row were removed.
123
+
124
+ As an example, here is the implementation of the `ArrayModel` (which is available as `slint.ArrayModel`)
125
+
126
+ ```js
127
+ let array = [1, 2, 3];
128
+ let model = {
129
+ rowCount() { return a.length; },
130
+ rowData(row) { return a[row]; },
131
+ setRowData(row, data) { a[row] = data; this.notify.rowDataChanged(row); },
132
+ push() {
133
+ let size = a.length;
134
+ Array.prototype.push.apply(a, arguments);
135
+ this.notify.rowAdded(size, arguments.length);
136
+ },
137
+ remove(index, size) {
138
+ let r = a.splice(index, size);
139
+ this.notify.rowRemoved(size, arguments.length);
140
+ },
141
+ };
142
+ component.model = model;
143
+ model.push(4); // this works
144
+ // does NOT work, getting the model does not return the right object
145
+ // component.model.push(5);
146
+ ```
package/lib/index.ts ADDED
@@ -0,0 +1,239 @@
1
+ // Copyright © SixtyFPS GmbH <info@slint-ui.com>
2
+ // SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-commercial
3
+
4
+ // Load the native library with `process.dlopen` instead of with `require`.
5
+ // This is only done for autotest that do not require nom or neon_cli to
6
+ // copy the lib to its right place
7
+ /**
8
+ * @hidden
9
+ */
10
+ function load_native_lib() {
11
+ const os = require('os');
12
+ (process as any).dlopen(module, process.env.SLINT_NODE_NATIVE_LIB,
13
+ os.constants.dlopen.RTLD_NOW);
14
+ return module.exports;
15
+ }
16
+
17
+ /**
18
+ * @hidden
19
+ */
20
+ let native = !process.env.SLINT_NODE_NATIVE_LIB ? require('../native/index.node') : load_native_lib();
21
+
22
+ /**
23
+ * @hidden
24
+ */
25
+ class Component {
26
+ protected comp: any;
27
+
28
+ constructor(comp: any) {
29
+ this.comp = comp;
30
+ }
31
+
32
+ run() {
33
+ this.comp.run();
34
+ }
35
+
36
+ show() {
37
+ this.window.show();
38
+ }
39
+
40
+ hide() {
41
+ this.window.hide()
42
+ }
43
+
44
+ get window(): Window {
45
+ return this.comp.window();
46
+ }
47
+
48
+ send_mouse_click(x: number, y: number) {
49
+ this.comp.send_mouse_click(x, y)
50
+ }
51
+
52
+ send_keyboard_string_sequence(s: String) {
53
+ this.comp.send_keyboard_string_sequence(s)
54
+ }
55
+ }
56
+
57
+ interface Window {
58
+ show(): void;
59
+ hide(): void;
60
+ }
61
+
62
+ /**
63
+ * @hidden
64
+ */
65
+ interface Callback {
66
+ (): any;
67
+ setHandler(cb: any): void;
68
+ }
69
+
70
+ require.extensions['.60'] = require.extensions['.slint'] =
71
+ function (module, filename) {
72
+ var c = native.load(filename);
73
+ module.exports[c.name().replace(/-/g, '_')] = function (init_properties: any) {
74
+ let comp = c.create(init_properties);
75
+ let ret = new Component(comp);
76
+ c.properties().forEach((x: string) => {
77
+ Object.defineProperty(ret, x.replace(/-/g, '_'), {
78
+ get() { return comp.get_property(x); },
79
+ set(newValue) { comp.set_property(x, newValue); },
80
+ enumerable: true,
81
+ })
82
+ });
83
+ c.callbacks().forEach((x: string) => {
84
+ Object.defineProperty(ret, x.replace(/-/g, '_'), {
85
+ get() {
86
+ let callback = function () { return comp.invoke_callback(x, [...arguments]); } as Callback;
87
+ callback.setHandler = function (callback) { comp.connect_callback(x, callback) };
88
+ return callback;
89
+ },
90
+ enumerable: true,
91
+ })
92
+ });
93
+ return ret;
94
+ }
95
+ }
96
+
97
+ /**
98
+ * ModelPeer is the interface that the run-time implements. An instance is
99
+ * set on dynamic Model<T> instances and can be used to notify the run-time
100
+ * of changes in the structure or data of the model.
101
+ */
102
+ interface ModelPeer {
103
+ /**
104
+ * Call this function from our own model to notify that fields of data
105
+ * in the specified row have changed.
106
+ * @argument row
107
+ */
108
+ rowDataChanged(row: number): void;
109
+ /**
110
+ * Call this function from your own model to notify that one or multiple
111
+ * rows were added to the model, starting at the specified row.
112
+ * @param row
113
+ * @param count
114
+ */
115
+ rowAdded(row: number, count: number): void;
116
+ /**
117
+ * Call this function from your own model to notify that one or multiple
118
+ * rows were removed from the model, starting at the specified row.
119
+ * @param row
120
+ * @param count
121
+ */
122
+ rowRemoved(row: number, count: number): void;
123
+ }
124
+
125
+ /**
126
+ * Model<T> is the interface for feeding dynamic data into
127
+ * `.slint` views.
128
+ *
129
+ * A model is organized like a table with rows of data. The
130
+ * fields of the data type T behave like columns.
131
+ */
132
+ interface Model<T> {
133
+ /**
134
+ * Implementations of this function must return the current number of rows.
135
+ */
136
+ rowCount(): number;
137
+ /**
138
+ * Implementations of this function must return the data at the specified row.
139
+ * @param row
140
+ */
141
+ rowData(row: number): T;
142
+ /**
143
+ * Implementations of this function must store the provided data parameter
144
+ * in the model at the specified row.
145
+ * @param row
146
+ * @param data
147
+ */
148
+ setRowData(row: number, data: T): void;
149
+ /**
150
+ * This public member is set by the run-time and implementation must use this
151
+ * to notify the run-time of changes in the model.
152
+ */
153
+ notify: ModelPeer;
154
+ }
155
+
156
+ /**
157
+ * @hidden
158
+ */
159
+ class NullPeer implements ModelPeer {
160
+ rowDataChanged(row: number): void { }
161
+ rowAdded(row: number, count: number): void { }
162
+ rowRemoved(row: number, count: number): void { }
163
+ }
164
+
165
+ /**
166
+ * ArrayModel wraps a JavaScript array for use in `.slint` views. The underlying
167
+ * array can be modified with the [[ArrayModel.push]] and [[ArrayModel.remove]] methods.
168
+ */
169
+ class ArrayModel<T> implements Model<T> {
170
+ /**
171
+ * @hidden
172
+ */
173
+ private a: Array<T>
174
+ notify: ModelPeer;
175
+
176
+ /**
177
+ * Creates a new ArrayModel.
178
+ *
179
+ * @param arr
180
+ */
181
+ constructor(arr: Array<T>) {
182
+ this.a = arr;
183
+ this.notify = new NullPeer();
184
+ }
185
+
186
+ rowCount() {
187
+ return this.a.length;
188
+ }
189
+ rowData(row: number) {
190
+ return this.a[row];
191
+ }
192
+ setRowData(row: number, data: T) {
193
+ this.a[row] = data;
194
+ this.notify.rowDataChanged(row);
195
+ }
196
+ /**
197
+ * Pushes new values to the array that's backing the model and notifies
198
+ * the run-time about the added rows.
199
+ * @param values
200
+ */
201
+ push(...values: T[]) {
202
+ let size = this.a.length;
203
+ Array.prototype.push.apply(this.a, values);
204
+ this.notify.rowAdded(size, arguments.length);
205
+ }
206
+ // FIXME: should this be named splice and have the splice api?
207
+ /**
208
+ * Removes the specified number of element from the array that's backing
209
+ * the model, starting at the specified index. This is equivalent to calling
210
+ * Array.slice() on the array and notifying the run-time about the removed
211
+ * rows.
212
+ * @param index
213
+ * @param size
214
+ */
215
+ remove(index: number, size: number) {
216
+ let r = this.a.splice(index, size);
217
+ this.notify.rowRemoved(index, size);
218
+ }
219
+
220
+ get length(): number {
221
+ return this.a.length;
222
+ }
223
+
224
+ values(): IterableIterator<T> {
225
+ return this.a.values();
226
+ }
227
+
228
+ entries(): IterableIterator<[number, T]> {
229
+ return this.a.entries()
230
+ }
231
+ }
232
+
233
+ module.exports = {
234
+ private_api: native,
235
+ ArrayModel: ArrayModel,
236
+ Timer: {
237
+ singleShot: native.singleshot_timer,
238
+ },
239
+ };
package/loader.mjs ADDED
@@ -0,0 +1,42 @@
1
+ // Copyright © SixtyFPS GmbH <info@slint-ui.com>
2
+ // SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-commercial
3
+
4
+ import { URL, pathToFileURL } from 'url';
5
+
6
+ const extensionsRegex = /\.(60|slint)$/;
7
+ const baseURL = pathToFileURL(`${process.cwd()}/`).href;
8
+
9
+ export function resolve(specifier, context, defaultResolve) {
10
+
11
+ const { parentURL = baseURL } = context;
12
+
13
+ if (extensionsRegex.test(specifier)) {
14
+ return { url: new URL(specifier, parentURL).href };
15
+ }
16
+
17
+ return defaultResolve(specifier, context, defaultResolve);
18
+ }
19
+
20
+
21
+ export function getFormat(url, context, defaultGetFormat) {
22
+ if (extensionsRegex.test(url)) {
23
+ return {
24
+ format: 'module'
25
+ };
26
+ }
27
+ return defaultGetFormat(url, context, defaultGetFormat);
28
+ }
29
+
30
+ export function transformSource(source, context, defaultTransformSource) {
31
+ const { url, format } = context;
32
+
33
+ if (extensionsRegex.test(url)) {
34
+ console.log(`This is where one can compile ${url}`)
35
+ return {
36
+ source: "console.log('Hey'); export function foo(x) { return x + 55 }"
37
+ };
38
+ }
39
+
40
+ // Let Node.js handle all other sources.
41
+ return defaultTransformSource(source, context, defaultTransformSource);
42
+ }
@@ -0,0 +1,38 @@
1
+ # Copyright © SixtyFPS GmbH <info@slint-ui.com>
2
+ # SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-commercial
3
+
4
+ [package]
5
+ name = "slint-node"
6
+ version = "0.2.0"
7
+ authors = ["Slint Developers <info@slint-ui.com>"]
8
+ edition = "2021"
9
+ build = "build.rs"
10
+ # This is not meant to be used as a library from crate.io
11
+ publish = false
12
+ license = "GPL-3.0-only OR LicenseRef-Slint-commercial"
13
+ repository = "https://github.com/slint-ui/slint"
14
+ homepage = "https://slint-ui.com"
15
+
16
+
17
+ [lib]
18
+ path = "lib.rs"
19
+ crate-type = ["cdylib"]
20
+ name = "slint_node_native"
21
+
22
+ [dependencies]
23
+ i-slint-compiler = { version = "=0.2.0"}
24
+ i-slint-core = { version = "=0.2.0"}
25
+ slint-interpreter = { version = "=0.2.0", features = ["display-diagnostics"] }
26
+
27
+ vtable = { version = "0.1.1"}
28
+
29
+ css-color-parser2 = "1.0.1"
30
+ generativity = "1"
31
+ neon = "0.8.0"
32
+ once_cell = "1.5"
33
+ rand = "0.8"
34
+ scoped-tls-hkt = "0.1"
35
+ spin_on = "0.1" #FIXME: remove and delegate to async JS instead
36
+
37
+ [build-dependencies]
38
+ neon-build = "0.8.0"
@@ -0,0 +1,6 @@
1
+ // Copyright © SixtyFPS GmbH <info@slint-ui.com>
2
+ // SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-commercial
3
+
4
+ fn main() {
5
+ neon_build::setup();
6
+ }
@@ -0,0 +1,148 @@
1
+ // Copyright © SixtyFPS GmbH <info@slint-ui.com>
2
+ // SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-commercial
3
+
4
+ use i_slint_compiler::langtype::Type;
5
+ use i_slint_core::model::Model;
6
+ use neon::prelude::*;
7
+ use std::cell::Cell;
8
+ use std::rc::{Rc, Weak};
9
+
10
+ /// Model coming from JS
11
+ pub struct JsModel {
12
+ notify: i_slint_core::model::ModelNotify,
13
+ /// The index of the value in the PersistentContext
14
+ value_index: u32,
15
+ data_type: Type,
16
+ }
17
+
18
+ impl JsModel {
19
+ pub fn new<'cx>(
20
+ obj: Handle<'cx, JsObject>,
21
+ data_type: Type,
22
+ cx: &mut impl Context<'cx>,
23
+ persistent_context: &crate::persistent_context::PersistentContext<'cx>,
24
+ ) -> NeonResult<Rc<Self>> {
25
+ let val = obj.as_value(cx);
26
+ let model = Rc::new(JsModel {
27
+ notify: Default::default(),
28
+ value_index: persistent_context.allocate(cx, val),
29
+ data_type,
30
+ });
31
+
32
+ let mut notify = SlintModelNotify::new::<_, JsValue, _>(cx, std::iter::empty())?;
33
+ cx.borrow_mut(&mut notify, |mut notify| notify.0 = Rc::downgrade(&model));
34
+ let notify = notify.as_value(cx);
35
+ obj.set(cx, "notify", notify)?;
36
+
37
+ Ok(model)
38
+ }
39
+
40
+ pub fn get_object<'cx>(
41
+ &self,
42
+ cx: &mut impl Context<'cx>,
43
+ persistent_context: &crate::persistent_context::PersistentContext<'cx>,
44
+ ) -> JsResult<'cx, JsObject> {
45
+ persistent_context.get(cx, self.value_index)?.downcast_or_throw(cx)
46
+ }
47
+ }
48
+
49
+ impl Model for JsModel {
50
+ type Data = slint_interpreter::Value;
51
+
52
+ fn row_count(&self) -> usize {
53
+ let r = Cell::new(0usize);
54
+ crate::run_with_global_context(&|cx, persistent_context| {
55
+ let obj = self.get_object(cx, persistent_context).unwrap();
56
+ let _ = obj
57
+ .get(cx, "rowCount")
58
+ .ok()
59
+ .and_then(|func| func.downcast::<JsFunction>().ok())
60
+ .and_then(|func| func.call(cx, obj, std::iter::empty::<Handle<JsValue>>()).ok())
61
+ .and_then(|res| res.downcast::<JsNumber>().ok())
62
+ .map(|num| r.set(num.value() as _));
63
+ });
64
+ r.get()
65
+ }
66
+
67
+ fn row_data(&self, row: usize) -> Option<Self::Data> {
68
+ if row >= self.row_count() {
69
+ None
70
+ } else {
71
+ let r = Cell::new(slint_interpreter::Value::default());
72
+ crate::run_with_global_context(&|cx, persistent_context| {
73
+ let row = JsNumber::new(cx, row as f64);
74
+ let obj = self.get_object(cx, persistent_context).unwrap();
75
+ let _ = obj
76
+ .get(cx, "rowData")
77
+ .ok()
78
+ .and_then(|func| func.downcast::<JsFunction>().ok())
79
+ .and_then(|func| func.call(cx, obj, std::iter::once(row)).ok())
80
+ .and_then(|res| {
81
+ crate::to_eval_value(res, self.data_type.clone(), cx, persistent_context)
82
+ .ok()
83
+ })
84
+ .map(|res| r.set(res));
85
+ });
86
+ Some(r.into_inner())
87
+ }
88
+ }
89
+
90
+ fn model_tracker(&self) -> &dyn i_slint_core::model::ModelTracker {
91
+ &self.notify
92
+ }
93
+
94
+ fn set_row_data(&self, row: usize, data: Self::Data) {
95
+ crate::run_with_global_context(&|cx, persistent_context| {
96
+ let row = JsNumber::new(cx, row as f64).as_value(cx);
97
+ let data = crate::to_js_value(data.clone(), cx, persistent_context).unwrap();
98
+ let obj = self.get_object(cx, persistent_context).unwrap();
99
+ let _ = obj
100
+ .get(cx, "setRowData")
101
+ .ok()
102
+ .and_then(|func| func.downcast::<JsFunction>().ok())
103
+ .and_then(|func| func.call(cx, obj, [row, data].iter().cloned()).ok());
104
+ });
105
+ }
106
+
107
+ fn as_any(&self) -> &dyn core::any::Any {
108
+ self
109
+ }
110
+ }
111
+
112
+ struct WrappedJsModel(Weak<JsModel>);
113
+
114
+ declare_types! {
115
+ class SlintModelNotify for WrappedJsModel {
116
+ init(_) {
117
+ Ok(WrappedJsModel(Weak::default()))
118
+ }
119
+ method rowDataChanged(mut cx) {
120
+ let this = cx.this();
121
+ let row = cx.argument::<JsNumber>(0)?.value() as usize;
122
+ if let Some(model) = cx.borrow(&this, |x| x.0.upgrade()) {
123
+ model.notify.row_changed(row)
124
+ }
125
+ Ok(JsUndefined::new().as_value(&mut cx))
126
+ }
127
+ method rowAdded(mut cx) {
128
+ let this = cx.this();
129
+ let row = cx.argument::<JsNumber>(0)?.value() as usize;
130
+ let count = cx.argument::<JsNumber>(1)?.value() as usize;
131
+ if let Some(model) = cx.borrow(&this, |x| x.0.upgrade()) {
132
+ model.notify.row_added(row, count)
133
+ }
134
+ Ok(JsUndefined::new().as_value(&mut cx))
135
+ }
136
+ method rowRemoved(mut cx) {
137
+ let this = cx.this();
138
+ let row = cx.argument::<JsNumber>(0)?.value() as usize;
139
+ let count = cx.argument::<JsNumber>(1)?.value() as usize;
140
+ if let Some(model) = cx.borrow(&this, |x| x.0.upgrade()) {
141
+ model.notify.row_removed(row, count)
142
+ }
143
+ Ok(JsUndefined::new().as_value(&mut cx))
144
+ }
145
+
146
+ }
147
+
148
+ }
package/native/lib.rs ADDED
@@ -0,0 +1,569 @@
1
+ // Copyright © SixtyFPS GmbH <info@slint-ui.com>
2
+ // SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-commercial
3
+
4
+ use core::cell::RefCell;
5
+ use i_slint_compiler::langtype::Type;
6
+ use i_slint_core::model::{Model, ModelRc};
7
+ use i_slint_core::window::WindowHandleAccess;
8
+ use i_slint_core::{ImageInner, SharedVector};
9
+ use neon::prelude::*;
10
+ use rand::RngCore;
11
+ use slint_interpreter::ComponentHandle;
12
+
13
+ mod js_model;
14
+ mod persistent_context;
15
+
16
+ struct WrappedComponentType(Option<slint_interpreter::ComponentDefinition>);
17
+ struct WrappedComponentRc(Option<slint_interpreter::ComponentInstance>);
18
+ struct WrappedWindow(Option<i_slint_core::window::WindowRc>);
19
+
20
+ /// We need to do some gymnastic with closures to pass the ExecuteContext with the right lifetime
21
+ type GlobalContextCallback<'c> =
22
+ dyn for<'b> Fn(&mut ExecuteContext<'b>, &persistent_context::PersistentContext<'b>) + 'c;
23
+ scoped_tls_hkt::scoped_thread_local!(static GLOBAL_CONTEXT:
24
+ for <'a> &'a dyn for<'c> Fn(&'c GlobalContextCallback<'c>));
25
+
26
+ /// This function exists as a workaround so one can access the ExecuteContext from callback handler
27
+ fn run_scoped<'cx, T>(
28
+ cx: &mut impl Context<'cx>,
29
+ object_with_persistent_context: Handle<'cx, JsObject>,
30
+ functor: impl FnOnce() -> Result<T, String>,
31
+ ) -> NeonResult<T> {
32
+ let persistent_context =
33
+ persistent_context::PersistentContext::from_object(cx, object_with_persistent_context)?;
34
+ cx.execute_scoped(|cx| {
35
+ let cx = RefCell::new(cx);
36
+ let cx_fn = move |callback: &GlobalContextCallback| {
37
+ callback(&mut *cx.borrow_mut(), &persistent_context)
38
+ };
39
+ GLOBAL_CONTEXT.set(&&cx_fn, functor)
40
+ })
41
+ .or_else(|e| cx.throw_error(e))
42
+ }
43
+
44
+ fn run_with_global_context(f: &GlobalContextCallback) {
45
+ GLOBAL_CONTEXT.with(|cx_fn| cx_fn(f))
46
+ }
47
+
48
+ /// Load a .slint files.
49
+ ///
50
+ /// The first argument of this function is a string to the .slint file
51
+ ///
52
+ /// The return value is a SlintComponentType
53
+ fn load(mut cx: FunctionContext) -> JsResult<JsValue> {
54
+ let path = cx.argument::<JsString>(0)?.value();
55
+ let path = std::path::Path::new(path.as_str());
56
+ let include_paths = match std::env::var_os("SLINT_INCLUDE_PATH") {
57
+ Some(paths) => {
58
+ std::env::split_paths(&paths).filter(|path| !path.as_os_str().is_empty()).collect()
59
+ }
60
+ None => vec![],
61
+ };
62
+ let mut compiler = slint_interpreter::ComponentCompiler::default();
63
+ compiler.set_include_paths(include_paths);
64
+ let c = spin_on::spin_on(compiler.build_from_path(path));
65
+
66
+ slint_interpreter::print_diagnostics(compiler.diagnostics());
67
+
68
+ let c = if let Some(c) = c { c } else { return cx.throw_error("Compilation error") };
69
+
70
+ let mut obj = SlintComponentType::new::<_, JsValue, _>(&mut cx, std::iter::empty())?;
71
+ cx.borrow_mut(&mut obj, |mut obj| obj.0 = Some(c));
72
+ Ok(obj.as_value(&mut cx))
73
+ }
74
+
75
+ fn make_callback_handler<'cx>(
76
+ cx: &mut impl Context<'cx>,
77
+ persistent_context: &persistent_context::PersistentContext<'cx>,
78
+ fun: Handle<'cx, JsFunction>,
79
+ return_type: Option<Box<Type>>,
80
+ ) -> Box<dyn Fn(&[slint_interpreter::Value]) -> slint_interpreter::Value> {
81
+ let fun_value = fun.as_value(cx);
82
+ let fun_idx = persistent_context.allocate(cx, fun_value);
83
+ Box::new(move |args| {
84
+ let args = args.to_vec();
85
+ let ret = core::cell::Cell::new(slint_interpreter::Value::Void);
86
+ let borrow_ret = &ret;
87
+ let return_type = &return_type;
88
+ run_with_global_context(&move |cx, persistent_context| {
89
+ let args = args
90
+ .iter()
91
+ .map(|a| to_js_value(a.clone(), cx, persistent_context).unwrap())
92
+ .collect::<Vec<_>>();
93
+ let ret = persistent_context
94
+ .get(cx, fun_idx)
95
+ .unwrap()
96
+ .downcast::<JsFunction>()
97
+ .unwrap()
98
+ .call::<_, _, JsValue, _>(cx, JsUndefined::new(), args)
99
+ .unwrap();
100
+ if let Some(return_type) = return_type {
101
+ borrow_ret.set(
102
+ to_eval_value(ret, (**return_type).clone(), cx, persistent_context).unwrap(),
103
+ );
104
+ }
105
+ });
106
+ ret.into_inner()
107
+ })
108
+ }
109
+
110
+ fn create<'cx>(
111
+ cx: &mut CallContext<'cx, impl neon::object::This>,
112
+ component_type: slint_interpreter::ComponentDefinition,
113
+ ) -> JsResult<'cx, JsValue> {
114
+ let component = component_type.create();
115
+ let persistent_context = persistent_context::PersistentContext::new(cx);
116
+
117
+ if let Some(args) = cx.argument_opt(0).and_then(|arg| arg.downcast::<JsObject>().ok()) {
118
+ let properties = component_type
119
+ .properties_and_callbacks()
120
+ .map(|(k, v)| (k.replace('_', "-"), v))
121
+ .collect::<std::collections::HashMap<_, _>>();
122
+ for x in args.get_own_property_names(cx)?.to_vec(cx)? {
123
+ let prop_name = x.to_string(cx)?.value().replace('_', "-");
124
+ let value = args.get(cx, x)?;
125
+ let ty = properties
126
+ .get(&prop_name)
127
+ .ok_or(())
128
+ .or_else(|()| {
129
+ cx.throw_error(format!("Property {} not found in the component", prop_name))
130
+ })?
131
+ .clone();
132
+ if let Type::Callback { return_type, .. } = ty {
133
+ let fun = value.downcast_or_throw::<JsFunction, _>(cx)?;
134
+ component
135
+ .set_callback(
136
+ prop_name.as_str(),
137
+ make_callback_handler(cx, &persistent_context, fun, return_type),
138
+ )
139
+ .or_else(|_| cx.throw_error("Cannot set callback"))?;
140
+ } else {
141
+ let value = to_eval_value(value, ty, cx, &persistent_context)?;
142
+ component
143
+ .set_property(prop_name.as_str(), value)
144
+ .or_else(|_| cx.throw_error("Cannot assign property"))?;
145
+ }
146
+ }
147
+ }
148
+
149
+ let mut obj = SlintComponent::new::<_, JsValue, _>(cx, std::iter::empty())?;
150
+ persistent_context.save_to_object(cx, obj.downcast().unwrap());
151
+ cx.borrow_mut(&mut obj, |mut obj| obj.0 = Some(component));
152
+ Ok(obj.as_value(cx))
153
+ }
154
+
155
+ fn to_eval_value<'cx>(
156
+ val: Handle<'cx, JsValue>,
157
+ ty: i_slint_compiler::langtype::Type,
158
+ cx: &mut impl Context<'cx>,
159
+ persistent_context: &persistent_context::PersistentContext<'cx>,
160
+ ) -> NeonResult<slint_interpreter::Value> {
161
+ use slint_interpreter::Value;
162
+ match ty {
163
+ Type::Float32
164
+ | Type::Int32
165
+ | Type::Duration
166
+ | Type::Angle
167
+ | Type::PhysicalLength
168
+ | Type::LogicalLength
169
+ | Type::Percent
170
+ | Type::UnitProduct(_) => {
171
+ Ok(Value::Number(val.downcast_or_throw::<JsNumber, _>(cx)?.value()))
172
+ }
173
+ Type::String => Ok(Value::String(val.to_string(cx)?.value().into())),
174
+ Type::Color | Type::Brush => {
175
+ let c = val
176
+ .to_string(cx)?
177
+ .value()
178
+ .parse::<css_color_parser2::Color>()
179
+ .or_else(|e| cx.throw_error(&e.to_string()))?;
180
+ Ok((i_slint_core::Color::from_argb_u8((c.a * 255.) as u8, c.r, c.g, c.b)).into())
181
+ }
182
+ Type::Array(a) => match val.downcast::<JsArray>() {
183
+ Ok(arr) => {
184
+ let vec = arr.to_vec(cx)?;
185
+ Ok(Value::Model(ModelRc::new(i_slint_core::model::SharedVectorModel::from(
186
+ vec.into_iter()
187
+ .map(|i| to_eval_value(i, (*a).clone(), cx, persistent_context))
188
+ .collect::<Result<SharedVector<_>, _>>()?,
189
+ ))))
190
+ }
191
+ Err(_) => {
192
+ let obj = val.downcast_or_throw::<JsObject, _>(cx)?;
193
+ obj.get(cx, "rowCount")?.downcast_or_throw::<JsFunction, _>(cx)?;
194
+ obj.get(cx, "rowData")?.downcast_or_throw::<JsFunction, _>(cx)?;
195
+ let m = js_model::JsModel::new(obj, *a, cx, persistent_context)?;
196
+ Ok(Value::Model(m.into()))
197
+ }
198
+ },
199
+ Type::Image => {
200
+ let path = val.to_string(cx)?.value();
201
+ Ok(Value::Image(
202
+ i_slint_core::graphics::Image::load_from_path(std::path::Path::new(&path))
203
+ .or_else(|_| cx.throw_error(format!("cannot load image {:?}", path)))?,
204
+ ))
205
+ }
206
+ Type::Bool => Ok(Value::Bool(val.downcast_or_throw::<JsBoolean, _>(cx)?.value())),
207
+ Type::Struct { fields, .. } => {
208
+ let obj = val.downcast_or_throw::<JsObject, _>(cx)?;
209
+ Ok(Value::Struct(
210
+ fields
211
+ .iter()
212
+ .map(|(pro_name, pro_ty)| {
213
+ Ok((
214
+ pro_name.clone(),
215
+ to_eval_value(
216
+ obj.get(cx, pro_name.replace('-', "_").as_str())?,
217
+ pro_ty.clone(),
218
+ cx,
219
+ persistent_context,
220
+ )?,
221
+ ))
222
+ })
223
+ .collect::<Result<_, _>>()?,
224
+ ))
225
+ }
226
+ Type::Enumeration(_) => todo!(),
227
+ Type::Invalid
228
+ | Type::Void
229
+ | Type::InferredProperty
230
+ | Type::InferredCallback
231
+ | Type::Builtin(_)
232
+ | Type::Native(_)
233
+ | Type::Function { .. }
234
+ | Type::Model
235
+ | Type::Callback { .. }
236
+ | Type::Easing
237
+ | Type::Component(_)
238
+ | Type::PathData
239
+ | Type::LayoutCache
240
+ | Type::ElementReference => cx.throw_error("Cannot convert to a Slint property value"),
241
+ }
242
+ }
243
+
244
+ fn to_js_value<'cx>(
245
+ val: slint_interpreter::Value,
246
+ cx: &mut impl Context<'cx>,
247
+ persistent_context: &persistent_context::PersistentContext<'cx>,
248
+ ) -> NeonResult<Handle<'cx, JsValue>> {
249
+ use slint_interpreter::Value;
250
+ Ok(match val {
251
+ Value::Void => JsUndefined::new().as_value(cx),
252
+ Value::Number(n) => JsNumber::new(cx, n).as_value(cx),
253
+ Value::String(s) => JsString::new(cx, s.as_str()).as_value(cx),
254
+ Value::Bool(b) => JsBoolean::new(cx, b).as_value(cx),
255
+ Value::Image(r) => match (&r).into() {
256
+ &ImageInner::None => JsUndefined::new().as_value(cx),
257
+ &ImageInner::AbsoluteFilePath(ref path) => {
258
+ JsString::new(cx, path.as_str()).as_value(cx)
259
+ }
260
+ &ImageInner::EmbeddedData { .. }
261
+ | &ImageInner::EmbeddedImage { .. }
262
+ | &ImageInner::StaticTextures { .. } => JsNull::new().as_value(cx), // TODO: maybe pass around node buffers?
263
+ },
264
+ Value::Model(model) => {
265
+ if let Some(js_model) = model.as_any().downcast_ref::<js_model::JsModel>() {
266
+ js_model.get_object(cx, persistent_context)?.as_value(cx)
267
+ } else {
268
+ // TODO: this should probably create a proxy object instead of extracting the entire model. On the other hand
269
+ // we should encounter this only if the model was created in .slint, which is when it'll be an array
270
+ // of values.
271
+ let js_array = JsArray::new(cx, model.row_count() as _);
272
+ for i in 0..model.row_count() {
273
+ let v = to_js_value(model.row_data(i).unwrap(), cx, persistent_context)?;
274
+ js_array.set(cx, i as u32, v)?;
275
+ }
276
+ js_array.as_value(cx)
277
+ }
278
+ }
279
+ Value::Struct(o) => {
280
+ let js_object = JsObject::new(cx);
281
+ for (k, e) in o.iter() {
282
+ let v = to_js_value(e.clone(), cx, persistent_context)?;
283
+ js_object.set(cx, k.replace('-', "_").as_str(), v)?;
284
+ }
285
+ js_object.as_value(cx)
286
+ }
287
+ Value::Brush(i_slint_core::Brush::SolidColor(c)) => JsString::new(
288
+ cx,
289
+ &format!("#{:02x}{:02x}{:02x}{:02x}", c.red(), c.green(), c.blue(), c.alpha()),
290
+ )
291
+ .as_value(cx),
292
+ _ => todo!("converting {:?} to js has not been implemented", val),
293
+ })
294
+ }
295
+
296
+ declare_types! {
297
+ class SlintComponentType for WrappedComponentType {
298
+ init(_) {
299
+ Ok(WrappedComponentType(None))
300
+ }
301
+ method create(mut cx) {
302
+ let this = cx.this();
303
+ let ct = cx.borrow(&this, |x| x.0.clone());
304
+ let ct = ct.ok_or(()).or_else(|()| cx.throw_error("Invalid type"))?;
305
+ create(&mut cx, ct)
306
+ }
307
+ method name(mut cx) {
308
+ let this = cx.this();
309
+ let ct = cx.borrow(&this, |x| x.0.clone());
310
+ let ct = ct.ok_or(()).or_else(|()| cx.throw_error("Invalid type"))?;
311
+ Ok(cx.string(ct.name()).as_value(&mut cx))
312
+ }
313
+ method properties(mut cx) {
314
+ let this = cx.this();
315
+ let ct = cx.borrow(&this, |x| x.0.clone());
316
+ let ct = ct.ok_or(()).or_else(|()| cx.throw_error("Invalid type"))?;
317
+ let properties = ct.properties_and_callbacks().filter(|(_, prop_type)| prop_type.is_property_type());
318
+ let array = JsArray::new(&mut cx, 0);
319
+ for (len, (p, _)) in properties.enumerate() {
320
+ let prop_name = JsString::new(&mut cx, p);
321
+ array.set(&mut cx, len as u32, prop_name)?;
322
+ }
323
+ Ok(array.as_value(&mut cx))
324
+ }
325
+ method callbacks(mut cx) {
326
+ let this = cx.this();
327
+ let ct = cx.borrow(&this, |x| x.0.clone());
328
+ let ct = ct.ok_or(()).or_else(|()| cx.throw_error("Invalid type"))?;
329
+ let callbacks = ct.properties_and_callbacks().filter(|(_, prop_type)| matches!(prop_type, Type::Callback{..}));
330
+ let array = JsArray::new(&mut cx, 0);
331
+ for (len , (p, _)) in callbacks.enumerate() {
332
+ let prop_name = JsString::new(&mut cx, p);
333
+ array.set(&mut cx, len as u32, prop_name)?;
334
+ }
335
+ Ok(array.as_value(&mut cx))
336
+ }
337
+ }
338
+
339
+ class SlintComponent for WrappedComponentRc {
340
+ init(_) {
341
+ Ok(WrappedComponentRc(None))
342
+ }
343
+ method run(mut cx) {
344
+ let this = cx.this();
345
+ let component = cx.borrow(&this, |x| x.0.as_ref().map(|c| c.clone_strong()));
346
+ let component = component.ok_or(()).or_else(|()| cx.throw_error("Invalid type"))?;
347
+ run_scoped(&mut cx,this.downcast().unwrap(), || {
348
+ component.run();
349
+ Ok(())
350
+ })?;
351
+ Ok(JsUndefined::new().as_value(&mut cx))
352
+ }
353
+ method window(mut cx) {
354
+ let this = cx.this();
355
+ let component = cx.borrow(&this, |x| x.0.as_ref().map(|c| c.clone_strong()));
356
+ let component = component.ok_or(()).or_else(|()| cx.throw_error("Invalid type"))?;
357
+ let window = component.window().window_handle().clone();
358
+ let mut obj = SlintWindow::new::<_, JsValue, _>(&mut cx, std::iter::empty())?;
359
+ cx.borrow_mut(&mut obj, |mut obj| obj.0 = Some(window));
360
+ Ok(obj.as_value(&mut cx))
361
+ }
362
+ method get_property(mut cx) {
363
+ let prop_name = cx.argument::<JsString>(0)?.value();
364
+ let this = cx.this();
365
+ let persistent_context =
366
+ persistent_context::PersistentContext::from_object(&mut cx, this.downcast().unwrap())?;
367
+ let component = cx.borrow(&this, |x| x.0.as_ref().map(|c| c.clone_strong()));
368
+ let component = component.ok_or(()).or_else(|()| cx.throw_error("Invalid type"))?;
369
+ let value = run_scoped(&mut cx,this.downcast().unwrap(), || {
370
+ component.get_property(prop_name.as_str())
371
+ .map_err(|_| "Cannot read property".to_string())
372
+ })?;
373
+ to_js_value(value, &mut cx, &persistent_context)
374
+ }
375
+ method set_property(mut cx) {
376
+ let prop_name = cx.argument::<JsString>(0)?.value();
377
+ let this = cx.this();
378
+ let component = cx.borrow(&this, |x| x.0.as_ref().map(|c| c.clone_strong()));
379
+ let component = component.ok_or(()).or_else(|()| cx.throw_error("Invalid type"))?;
380
+ let ty = component.definition().properties_and_callbacks()
381
+ .find_map(|(name, proptype)| if name == prop_name { Some(proptype) } else { None })
382
+ .ok_or(())
383
+ .or_else(|()| {
384
+ cx.throw_error(format!("Property {} not found in the component", prop_name))
385
+ })?;
386
+
387
+ let persistent_context =
388
+ persistent_context::PersistentContext::from_object(&mut cx, this.downcast().unwrap())?;
389
+
390
+ let value = to_eval_value(cx.argument::<JsValue>(1)?, ty, &mut cx, &persistent_context)?;
391
+ run_scoped(&mut cx, this.downcast().unwrap(), || {
392
+ component.set_property(prop_name.as_str(), value)
393
+ .map_err(|_| "Cannot assign property".to_string())
394
+ })?;
395
+
396
+ Ok(JsUndefined::new().as_value(&mut cx))
397
+ }
398
+ method invoke_callback(mut cx) {
399
+ let callback_name = cx.argument::<JsString>(0)?.value();
400
+ let arguments = cx.argument::<JsArray>(1)?.to_vec(&mut cx)?;
401
+ let this = cx.this();
402
+ let component = cx.borrow(&this, |x| x.0.as_ref().map(|c| c.clone_strong()));
403
+ let component = component.ok_or(()).or_else(|()| cx.throw_error("Invalid type"))?;
404
+ let ty = component.definition().properties_and_callbacks()
405
+ .find_map(|(name, proptype)| if name == callback_name { Some(proptype) } else { None })
406
+ .ok_or(())
407
+ .or_else(|()| {
408
+ cx.throw_error(format!("Callback {} not found in the component", callback_name))
409
+ })?;
410
+ let persistent_context =
411
+ persistent_context::PersistentContext::from_object(&mut cx, this.downcast().unwrap())?;
412
+ let args = if let Type::Callback {args, ..} = ty {
413
+ let count = args.len();
414
+ let args = arguments.into_iter()
415
+ .zip(args.into_iter())
416
+ .map(|(a, ty)| to_eval_value(a, ty, &mut cx, &persistent_context))
417
+ .collect::<Result<Vec<_>, _>>()?;
418
+ if args.len() != count {
419
+ cx.throw_error(format!("{} expect {} arguments, but {} where provided", callback_name, count, args.len()))?;
420
+ }
421
+ args
422
+
423
+ } else {
424
+ cx.throw_error(format!("{} is not a callback", callback_name))?;
425
+ unreachable!()
426
+ };
427
+
428
+ let res = run_scoped(&mut cx,this.downcast().unwrap(), || {
429
+ component.invoke_callback(callback_name.as_str(), args.as_slice())
430
+ .map_err(|_| "Cannot emit callback".to_string())
431
+ })?;
432
+ to_js_value(res, &mut cx, &persistent_context)
433
+ }
434
+
435
+ method connect_callback(mut cx) {
436
+ let callback_name = cx.argument::<JsString>(0)?.value();
437
+ let handler = cx.argument::<JsFunction>(1)?;
438
+ let this = cx.this();
439
+ let persistent_context =
440
+ persistent_context::PersistentContext::from_object(&mut cx, this.downcast().unwrap())?;
441
+ let component = cx.borrow(&this, |x| x.0.as_ref().map(|c| c.clone_strong()));
442
+ let component = component.ok_or(()).or_else(|()| cx.throw_error("Invalid type"))?;
443
+
444
+ let ty = component.definition().properties_and_callbacks()
445
+ .find_map(|(name, proptype)| if name == callback_name { Some(proptype) } else { None })
446
+ .ok_or(())
447
+ .or_else(|()| {
448
+ cx.throw_error(format!("Callback {} not found in the component", callback_name))
449
+ })?;
450
+ if let Type::Callback {return_type, ..} = ty {
451
+ component.set_callback(
452
+ callback_name.as_str(),
453
+ make_callback_handler(&mut cx, &persistent_context, handler, return_type)
454
+ ).or_else(|_| cx.throw_error("Cannot set callback"))?;
455
+ Ok(JsUndefined::new().as_value(&mut cx))
456
+ } else {
457
+ cx.throw_error(format!("{} is not a callback", callback_name))?;
458
+ unreachable!()
459
+ }
460
+ }
461
+
462
+ method send_mouse_click(mut cx) {
463
+ let x = cx.argument::<JsNumber>(0)?.value() as f32;
464
+ let y = cx.argument::<JsNumber>(1)?.value() as f32;
465
+ let this = cx.this();
466
+ let component = cx.borrow(&this, |x| x.0.as_ref().map(|c| c.clone_strong()));
467
+ let component = component.ok_or(()).or_else(|()| cx.throw_error("Invalid type"))?;
468
+ run_scoped(&mut cx,this.downcast().unwrap(), || {
469
+ slint_interpreter::testing::send_mouse_click(&component, x, y);
470
+ Ok(())
471
+ })?;
472
+ Ok(JsUndefined::new().as_value(&mut cx))
473
+ }
474
+
475
+ method send_keyboard_string_sequence(mut cx) {
476
+ let sequence = cx.argument::<JsString>(0)?.value();
477
+ let this = cx.this();
478
+ let component = cx.borrow(&this, |x| x.0.as_ref().map(|c| c.clone_strong()));
479
+ let component = component.ok_or(()).or_else(|()| cx.throw_error("Invalid type"))?;
480
+ run_scoped(&mut cx,this.downcast().unwrap(), || {
481
+ slint_interpreter::testing::send_keyboard_string_sequence(&component, sequence.into());
482
+ Ok(())
483
+ })?;
484
+ Ok(JsUndefined::new().as_value(&mut cx))
485
+ }
486
+ }
487
+
488
+ class SlintWindow for WrappedWindow {
489
+ init(_) {
490
+ Ok(WrappedWindow(None))
491
+ }
492
+
493
+ method show(mut cx) {
494
+ let this = cx.this();
495
+ let window = cx.borrow(&this, |x| x.0.as_ref().cloned());
496
+ let window = window.ok_or(()).or_else(|()| cx.throw_error("Invalid type"))?;
497
+ window.show();
498
+ Ok(JsUndefined::new().as_value(&mut cx))
499
+ }
500
+
501
+ method hide(mut cx) {
502
+ let this = cx.this();
503
+ let window = cx.borrow(&this, |x| x.0.as_ref().cloned());
504
+ let window = window.ok_or(()).or_else(|()| cx.throw_error("Invalid type"))?;
505
+ window.hide();
506
+ Ok(JsUndefined::new().as_value(&mut cx))
507
+ }
508
+ }
509
+ }
510
+
511
+ fn singleshot_timer_property(id: u32) -> String {
512
+ format!("$__slint_singleshot_timer_{}", id)
513
+ }
514
+
515
+ fn singleshot_timer(mut cx: FunctionContext) -> JsResult<JsValue> {
516
+ let duration_in_msecs = cx.argument::<JsNumber>(0)?.value() as u64;
517
+ let handler = cx.argument::<JsFunction>(1)?;
518
+
519
+ let global_object: Handle<JsObject> = cx.global().downcast().unwrap();
520
+ let unique_timer_property = {
521
+ let mut rng = rand::thread_rng();
522
+ loop {
523
+ let id = rng.next_u32();
524
+ let key = singleshot_timer_property(id);
525
+ if global_object.get(&mut cx, &*key)?.is_a::<JsUndefined>() {
526
+ break key;
527
+ }
528
+ }
529
+ };
530
+
531
+ let handler_value = handler.as_value(&mut cx);
532
+ global_object.set(&mut cx, &*unique_timer_property, handler_value).unwrap();
533
+ let callback = move || {
534
+ run_with_global_context(&move |cx, _| {
535
+ let global_object: Handle<JsObject> = cx.global().downcast().unwrap();
536
+
537
+ let callback = global_object
538
+ .get(cx, &*unique_timer_property)
539
+ .unwrap()
540
+ .downcast::<JsFunction>()
541
+ .unwrap();
542
+
543
+ global_object.set(cx, &*unique_timer_property, JsUndefined::new()).unwrap();
544
+
545
+ callback.call::<_, _, JsValue, _>(cx, JsUndefined::new(), vec![]).unwrap();
546
+ });
547
+ };
548
+
549
+ i_slint_core::timers::Timer::single_shot(
550
+ std::time::Duration::from_millis(duration_in_msecs),
551
+ callback,
552
+ );
553
+
554
+ Ok(JsUndefined::new().upcast())
555
+ }
556
+
557
+ register_module!(mut m, {
558
+ m.export_function("load", load)?;
559
+ m.export_function("mock_elapsed_time", mock_elapsed_time)?;
560
+ m.export_function("singleshot_timer", singleshot_timer)?;
561
+ Ok(())
562
+ });
563
+
564
+ /// let some time elapse for testing purposes
565
+ fn mock_elapsed_time(mut cx: FunctionContext) -> JsResult<JsValue> {
566
+ let ms = cx.argument::<JsNumber>(0)?.value();
567
+ i_slint_core::tests::slint_mock_elapsed_time(ms as _);
568
+ Ok(JsUndefined::new().as_value(&mut cx))
569
+ }
@@ -0,0 +1,37 @@
1
+ // Copyright © SixtyFPS GmbH <info@slint-ui.com>
2
+ // SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-commercial
3
+
4
+ /*!
5
+ Since neon does not allow to have a persistent handle, use this hack.
6
+ */
7
+
8
+ use neon::prelude::*;
9
+ pub struct PersistentContext<'a>(Handle<'a, JsArray>);
10
+
11
+ const KEY: &str = "$__persistent_context";
12
+
13
+ /// Since neon does not allow to have a persistent handle, this allocates property in an array.
14
+ /// This array is gonna be kept as a property somewhere.
15
+ impl<'a> PersistentContext<'a> {
16
+ pub fn new(cx: &mut impl Context<'a>) -> Self {
17
+ PersistentContext(JsArray::new(cx, 0))
18
+ }
19
+
20
+ pub fn allocate(&self, cx: &mut impl Context<'a>, value: Handle<'a, JsValue>) -> u32 {
21
+ let idx = self.0.len();
22
+ self.0.set(cx, idx, value).unwrap();
23
+ idx
24
+ }
25
+
26
+ pub fn get(&self, cx: &mut impl Context<'a>, idx: u32) -> JsResult<'a, JsValue> {
27
+ self.0.get(cx, idx)
28
+ }
29
+
30
+ pub fn save_to_object(&self, cx: &mut impl Context<'a>, o: Handle<'a, JsObject>) {
31
+ o.set(cx, KEY, self.0).unwrap();
32
+ }
33
+
34
+ pub fn from_object(cx: &mut impl Context<'a>, o: Handle<'a, JsObject>) -> NeonResult<Self> {
35
+ Ok(PersistentContext(o.get(cx, KEY)?.downcast_or_throw(cx)?))
36
+ }
37
+ }
package/package.json ADDED
@@ -0,0 +1,25 @@
1
+ {
2
+ "name": "slint-ui",
3
+ "version": "0.2.0",
4
+ "homepage": "https://github.com/slint-ui/slint",
5
+ "license": "SEE LICENSE IN LICENSE.md",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/slint-ui/slint"
9
+ },
10
+ "main": "dist/index.js",
11
+ "types": "dist/index.d.ts",
12
+ "dependencies": {
13
+ "@types/node": "^14.11.11",
14
+ "neon-cli": "^0.4",
15
+ "typescript": "^4.0.3"
16
+ },
17
+ "scripts": {
18
+ "install": "neon build --release && tsc",
19
+ "build": "tsc",
20
+ "docs": "typedoc lib/index.ts"
21
+ },
22
+ "devDependencies": {
23
+ "typedoc": "^0.19.2"
24
+ }
25
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,71 @@
1
+ {
2
+ "compilerOptions": {
3
+ /* Visit https://aka.ms/tsconfig.json to read more about this file */
4
+ /* Basic Options */
5
+ // "incremental": true, /* Enable incremental compilation */
6
+ "target": "es2015", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
7
+ "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
8
+ // "lib": [], /* Specify library files to be included in the compilation. */
9
+ // "allowJs": true, /* Allow javascript files to be compiled. */
10
+ // "checkJs": true, /* Report errors in .js files. */
11
+ // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
12
+ "declaration": true, /* Generates corresponding '.d.ts' file. */
13
+ // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
14
+ // "sourceMap": true, /* Generates corresponding '.map' file. */
15
+ // "outFile": "./", /* Concatenate and emit output to single file. */
16
+ "outDir": "./dist", /* Redirect output structure to the directory. */
17
+ // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
18
+ // "composite": true, /* Enable project compilation */
19
+ // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
20
+ // "removeComments": true, /* Do not emit comments to output. */
21
+ // "noEmit": true, /* Do not emit outputs. */
22
+ // "importHelpers": true, /* Import emit helpers from 'tslib'. */
23
+ // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
24
+ // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
25
+ /* Strict Type-Checking Options */
26
+ "strict": true, /* Enable all strict type-checking options. */
27
+ // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
28
+ // "strictNullChecks": true, /* Enable strict null checks. */
29
+ // "strictFunctionTypes": true, /* Enable strict checking of function types. */
30
+ // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
31
+ // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
32
+ // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
33
+ // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
34
+ /* Additional Checks */
35
+ // "noUnusedLocals": true, /* Report errors on unused locals. */
36
+ // "noUnusedParameters": true, /* Report errors on unused parameters. */
37
+ // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
38
+ // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
39
+ /* Module Resolution Options */
40
+ // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
41
+ // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
42
+ // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
43
+ // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
44
+ // "typeRoots": [], /* List of folders to include type definitions from. */
45
+ // "types": [], /* Type declaration files to be included in compilation. */
46
+ // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
47
+ "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
48
+ // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
49
+ // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
50
+ /* Source Map Options */
51
+ // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
52
+ // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
53
+ // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
54
+ // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
55
+ /* Experimental Options */
56
+ // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
57
+ // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
58
+ /* Advanced Options */
59
+ "skipLibCheck": true, /* Skip type checking of declaration files. */
60
+ "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
61
+ },
62
+ "typedocOptions": {
63
+ "mode": "file",
64
+ "out": "docs",
65
+ "readme": "README.md",
66
+ "disableSources": true,
67
+ "theme": "minimal",
68
+ "hideGenerator": true,
69
+ "name": "Slint Node"
70
+ }
71
+ }