forked from slint-ui/slint
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.ts
985 lines (883 loc) · 29 KB
/
index.ts
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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
// Copyright © SixtyFPS GmbH <[email protected]>
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-1.1 OR LicenseRef-Slint-commercial
import * as napi from "./rust-module.cjs";
const {
Diagnostic,
DiagnosticLevel,
RgbaColor,
Brush
} = napi;
export {
Diagnostic,
DiagnosticLevel,
RgbaColor,
Brush
};
/**
* Represents a two-dimensional point.
*/
export interface Point {
/**
* Defines the x coordinate of the point.
*/
x: number;
/**
* Defines the y coordinate of the point.
*/
y: number;
}
/**
* Represents a two-dimensional size.
*/
export interface Size {
/**
* Defines the width length of the size.
*/
width: number;
/**
* Defines the height length of the size.
*/
height: number;
}
/**
* This type represents a window towards the windowing system, that's used to render the
* scene of a component. It provides API to control windowing system specific aspects such
* as the position on the screen.
*/
export interface Window {
/** Gets or sets the logical position of the window on the screen. */
logicalPosition: Point;
/** Gets or sets the physical position of the window on the screen. */
physicalPosition: Point;
/** Gets or sets the logical size of the window on the screen, */
logicalSize: Size;
/** Gets or sets the physical size of the window on the screen, */
physicalSize: Size;
/**
* Returns the visibility state of the window. This function can return false even if you previously called show()
* on it, for example if the user minimized the window.
*/
get visible(): boolean;
/**
* Shows the window on the screen. An additional strong reference on the
* associated component is maintained while the window is visible.
*/
show(): void;
/** Hides the window, so that it is not visible anymore. */
hide(): void;
/** Issues a request to the windowing system to re-render the contents of the window. */
requestRedraw(): void;
}
/**
* An image data type that can be displayed by the Image element.
*
* This interface is inspired by the web [ImageData](https://developer.mozilla.org/en-US/docs/Web/API/ImageData) interface.
*/
export interface ImageData {
/**
* Returns the path of the image, if it was loaded from disk. Otherwise
* the property is undefined.
*/
readonly path?: string;
/**
* Returns the image as buffer.
*/
get data(): Uint8Array;
/**
* Returns the width of the image in pixels.
*/
get width(): number;
/**
* Returns the height of the image in pixels.
*/
get height(): number;
}
/**
* Model<T> is the interface for feeding dynamic data into
* `.slint` views.
*
* A model is organized like a table with rows of data. The
* fields of the data type T behave like columns.
*
* @template T the type of the model's items.
*
* ### Example
* As an example let's see the implementation of {@link ArrayModel}
*
* ```js
* export class ArrayModel<T> extends Model<T> {
* private a: Array<T>
*
* constructor(arr: Array<T>) {
* super();
* this.a = arr;
* }
*
* rowCount() {
* return this.a.length;
* }
*
* rowData(row: number) {
* return this.a[row];
* }
*
* setRowData(row: number, data: T) {
* this.a[row] = data;
* this.notifyRowDataChanged(row);
* }
*
* push(...values: T[]) {
* let size = this.a.length;
* Array.prototype.push.apply(this.a, values);
* this.notifyRowAdded(size, arguments.length);
* }
*
* remove(index: number, size: number) {
* let r = this.a.splice(index, size);
* this.notifyRowRemoved(index, size);
* }
*
* get length(): number {
* return this.a.length;
* }
*
* values(): IterableIterator<T> {
* return this.a.values();
* }
*
* entries(): IterableIterator<[number, T]> {
* return this.a.entries()
* }
*}
* ```
*/
export abstract class Model<T> {
/**
* @hidden
*/
notify: NullPeer;
constructor() {
this.notify = new NullPeer();
}
// /**
// * Returns a new Model where all elements are mapped by the function `mapFunction`.
// * @template T the type of the source model's items.
// * @param mapFunction functions that maps
// * @returns a new {@link MapModel} that wraps the current model.
// */
// map<U>(
// mapFunction: (data: T) => U
// ): MapModel<T, U> {
// return new MapModel(this, mapFunction);
// }
/**
* Implementations of this function must return the current number of rows.
*/
abstract rowCount(): number;
/**
* Implementations of this function must return the data at the specified row.
* @param row index in range 0..(rowCount() - 1).
* @returns undefined if row is out of range otherwise the data.
*/
abstract rowData(row: number): T | undefined;
/**
* Implementations of this function must store the provided data parameter
* in the model at the specified row.
* @param row index in range 0..(rowCount() - 1).
* @param data new data item to store on the given row index
*/
setRowData(_row: number, _data: T): void {
console.log(
"setRowData called on a model which does not re-implement this method. This happens when trying to modify a read-only model"
);
}
/**
* Notifies the view that the data of the current row is changed.
* @param row index of the changed row.
*/
protected notifyRowDataChanged(row: number): void {
this.notify.rowDataChanged(row);
}
/**
* Notifies the view that multiple rows are added to the model.
* @param row index of the first added row.
* @param count the number of added items.
*/
protected notifyRowAdded(row: number, count: number): void {
this.notify.rowAdded(row, count);
}
/**
* Notifies the view that multiple rows are removed to the model.
* @param row index of the first removed row.
* @param count the number of removed items.
*/
protected notifyRowRemoved(row: number, count: number): void {
this.notify.rowRemoved(row, count);
}
/**
* Notifies the view that the complete data must be reload.
*/
protected notifyReset(): void {
this.notify.reset();
}
}
/**
* @hidden
*/
class NullPeer {
rowDataChanged(row: number): void {}
rowAdded(row: number, count: number): void {}
rowRemoved(row: number, count: number): void {}
reset(): void {}
}
/**
* ArrayModel wraps a JavaScript array for use in `.slint` views. The underlying
* array can be modified with the [[ArrayModel.push]] and [[ArrayModel.remove]] methods.
*/
export class ArrayModel<T> extends Model<T> {
/**
* @hidden
*/
#array: Array<T>;
/**
* Creates a new ArrayModel.
*
* @param arr
*/
constructor(arr: Array<T>) {
super();
this.#array = arr;
}
/**
* Returns the number of entries in the array model.
*/
get length(): number {
return this.#array.length;
}
/**
* Returns the number of entries in the array model.
*/
rowCount() {
return this.#array.length;
}
/**
* Returns the data at the specified row.
* @param row index in range 0..(rowCount() - 1).
* @returns undefined if row is out of range otherwise the data.
*/
rowData(row: number) {
return this.#array[row];
}
/**
* Stores the given data on the given row index and notifies run-time about the changed row.
* @param row index in range 0..(rowCount() - 1).
* @param data new data item to store on the given row index
*/
setRowData(row: number, data: T) {
this.#array[row] = data;
this.notifyRowDataChanged(row);
}
/**
* Pushes new values to the array that's backing the model and notifies
* the run-time about the added rows.
* @param values list of values that will be pushed to the array.
*/
push(...values: T[]) {
let size = this.#array.length;
Array.prototype.push.apply(this.#array, values);
this.notifyRowAdded(size, arguments.length);
}
// FIXME: should this be named splice and have the splice api?
/**
* Removes the specified number of element from the array that's backing
* the model, starting at the specified index.
* @param index index of first row to remove.
* @param size number of rows to remove.
*/
remove(index: number, size: number) {
let r = this.#array.splice(index, size);
this.notifyRowRemoved(index, size);
}
/**
* Returns an iterable of values in the array.
*/
values(): IterableIterator<T> {
return this.#array.values();
}
/**
* Returns an iterable of key, value pairs for every entry in the array.
*/
entries(): IterableIterator<[number, T]> {
return this.#array.entries();
}
}
export namespace private_api {
/**
* Provides rows that are generated by a map function based on the rows of another Model.
*
* @template T item type of source model that is mapped to U.
* @template U the type of the mapped items
*
* ## Example
*
* Here we have a {@link ArrayModel} holding rows of a custom interface `Name` and a {@link MapModel} that maps the name rows
* to single string rows.
*
* ```ts
* import { Model, ArrayModel, MapModel } from "./index";
*
* interface Name {
* first: string;
* last: string;
* }
*
* const model = new ArrayModel<Name>([
* {
* first: "Hans",
* last: "Emil",
* },
* {
* first: "Max",
* last: "Mustermann",
* },
* {
* first: "Roman",
* last: "Tisch",
* },
* ]);
*
* const mappedModel = new MapModel(
* model,
* (data) => {
* return data.last + ", " + data.first;
* }
* );
*
* // prints "Emil, Hans"
* console.log(mappedModel.rowData(0));
*
* // prints "Mustermann, Max"
* console.log(mappedModel.rowData(1));
*
* // prints "Tisch, Roman"
* console.log(mappedModel.rowData(2));
*
* // Alternatively you can use the shortcut {@link MapModel.map}.
*
* const model = new ArrayModel<Name>([
* {
* first: "Hans",
* last: "Emil",
* },
* {
* first: "Max",
* last: "Mustermann",
* },
* {
* first: "Roman",
* last: "Tisch",
* },
* ]);
*
* const mappedModel = model.map(
* (data) => {
* return data.last + ", " + data.first;
* }
* );
*
*
* // prints "Emil, Hans"
* console.log(mappedModel.rowData(0));
*
* // prints "Mustermann, Max"
* console.log(mappedModel.rowData(1));
*
* // prints "Tisch, Roman"
* console.log(mappedModel.rowData(2));
*
* // You can modifying the underlying {@link ArrayModel}:
*
* const model = new ArrayModel<Name>([
* {
* first: "Hans",
* last: "Emil",
* },
* {
* first: "Max",
* last: "Mustermann",
* },
* {
* first: "Roman",
* last: "Tisch",
* },
* ]);
*
* const mappedModel = model.map(
* (data) => {
* return data.last + ", " + data.first;
* }
* );
*
* model.setRowData(1, { first: "Minnie", last: "Musterfrau" } );
*
* // prints "Emil, Hans"
* console.log(mappedModel.rowData(0));
*
* // prints "Musterfrau, Minnie"
* console.log(mappedModel.rowData(1));
*
* // prints "Tisch, Roman"
* console.log(mappedModel.rowData(2));
* ```
*/
export class MapModel<T, U> extends Model<U> {
readonly sourceModel: Model<T>;
#mapFunction: (data: T) => U
/**
* Constructs the MapModel with a source model and map functions.
* @template T item type of source model that is mapped to U.
* @template U the type of the mapped items.
* @param sourceModel the wrapped model.
* @param mapFunction maps the data from T to U.
*/
constructor(
sourceModel: Model<T>,
mapFunction: (data: T) => U
) {
super();
this.sourceModel = sourceModel;
this.#mapFunction = mapFunction;
this.notify = this.sourceModel.notify;
}
/**
* Returns the number of entries in the model.
*/
rowCount(): number {
return this.sourceModel.rowCount();
}
/**
* Returns the data at the specified row.
* @param row index in range 0..(rowCount() - 1).
* @returns undefined if row is out of range otherwise the data.
*/
rowData(row: number): U {
return this.#mapFunction(this.sourceModel.rowData(row));
}
}
}
/**
* This interface describes the public API of a Slint component that is common to all instances. Use this to
* show() the window on the screen, access the window and subsequent window properties, or start the
* Slint event loop with run().
*/
export interface ComponentHandle {
/**
* Shows the window and runs the event loop. The returned promise is resolved when the event loop
* is terminated, for example when the last window was closed, or {@link quitEventLoop} was called.
*
* This function is a convenience for calling {@link show}, followed by {@link runEventLoop}, and
* {@link hide} when the event loop's promise is resolved.
*/
run(): Promise<unknown>;
/**
* Shows the component's window on the screen.
*/
show();
/**
* Hides the component's window, so that it is not visible anymore.
*/
hide();
/**
* Returns the {@link Window} associated with this component instance.
* The window API can be used to control different aspects of the integration into the windowing system, such as the position on the screen.
*/
get window(): Window;
}
/**
* @hidden
*/
class Component implements ComponentHandle {
#instance: napi.ComponentInstance;
/**
* @hidden
*/
constructor(instance: napi.ComponentInstance) {
this.#instance = instance;
}
get window(): Window {
return this.#instance.window();
}
/**
* @hidden
*/
get component_instance(): napi.ComponentInstance {
return this.#instance;
}
async run() {
this.show();
await runEventLoop();
this.hide();
}
show() {
this.#instance.window().show();
}
hide() {
this.#instance.window().hide();
}
}
/**
* Represents an errors that can be emitted by the compiler.
*/
export class CompileError extends Error {
/**
* List of {@link Diagnostic} items emitted while compiling .slint code.
*/
diagnostics: napi.Diagnostic[];
/**
* Creates a new CompileError.
*
* @param message human-readable description of the error.
* @param diagnostics represent a list of diagnostic items emitted while compiling .slint code.
*/
constructor(message: string, diagnostics: napi.Diagnostic[]) {
super(message);
this.diagnostics = diagnostics;
}
}
/**
* LoadFileOptions are used to defines different optional parameters that can be used to configure the compiler.
*/
export interface LoadFileOptions {
/**
* If set to true warnings from the compiler will not be printed to the console.
*/
quiet?: boolean;
/**
* Sets the widget style the compiler is currently using when compiling .slint files.
*/
style?: string;
/**
* Sets the include paths used for looking up `.slint` imports to the specified vector of paths.
*/
includePaths?: Array<string>;
/**
* Sets library paths used for looking up `@library` imports to the specified map of library names to paths.
*/
libraryPaths?: Record<string, string>;
}
type LoadData = {
fileData: {
filePath: string,
options?: LoadFileOptions
},
from: 'file'
} | {
fileData: {
source: string,
filePath: string,
options?: LoadFileOptions
},
from: 'source'
}
function loadSlint(loadData: LoadData): Object {
const {filePath ,options} = loadData.fileData
let compiler = new napi.ComponentCompiler();
if (typeof options !== "undefined") {
if (typeof options.style !== "undefined") {
compiler.style = options.style;
}
if (typeof options.includePaths !== "undefined") {
compiler.includePaths = options.includePaths;
}
if (typeof options.libraryPaths !== "undefined") {
compiler.libraryPaths = options.libraryPaths;
}
}
let definition = loadData.from === 'file' ? compiler.buildFromPath(filePath) : compiler.buildFromSource(loadData.fileData.source, filePath);
let diagnostics = compiler.diagnostics;
if (diagnostics.length > 0) {
let warnings = diagnostics.filter(
(d) => d.level == napi.DiagnosticLevel.Warning
);
if (typeof options !== "undefined" && options.quiet !== true) {
warnings.forEach((w) => console.warn("Warning: " + w));
}
let errors = diagnostics.filter(
(d) => d.level == napi.DiagnosticLevel.Error
);
if (errors.length > 0) {
throw new CompileError("Could not compile " + filePath, errors);
}
}
let slint_module = Object.create({});
Object.defineProperty(slint_module, definition!.name.replace(/-/g, "_"), {
value: function (properties: any) {
let instance = definition!.create();
if (instance == null) {
throw Error(
"Could not create a component handle for" + filePath
);
}
for (var key in properties) {
let value = properties[key];
if (value instanceof Function) {
instance.setCallback(key, value);
} else {
instance.setProperty(key, properties[key]);
}
}
let componentHandle = new Component(instance!);
instance!.definition().properties.forEach((prop) => {
let propName = prop.name.replace(/-/g, "_");
if (componentHandle[propName] !== undefined) {
console.warn("Duplicated property name " + propName);
} else {
Object.defineProperty(componentHandle, propName, {
get() {
return instance!.getProperty(prop.name);
},
set(value) {
instance!.setProperty(prop.name, value);
},
enumerable: true,
});
}
});
instance!.definition().callbacks.forEach((cb) => {
let callbackName = cb.replace(/-/g, "_");
if (componentHandle[callbackName] !== undefined) {
console.warn("Duplicated callback name " + callbackName);
} else {
Object.defineProperty(componentHandle, cb.replace(/-/g, "_"), {
get() {
return function () {
return instance!.invoke(cb, Array.from(arguments));
};
},
set(callback) {
instance!.setCallback(cb, callback);
},
enumerable: true,
});
}
});
// globals
instance!.definition().globals.forEach((globalName) => {
if (componentHandle[globalName] !== undefined) {
console.warn("Duplicated property name " + globalName);
} else {
let globalObject = Object.create({});
instance!.definition().globalProperties(globalName).forEach((prop) => {
let propName = prop.name.replace(/-/g, "_");
if (globalObject[propName] !== undefined) {
console.warn("Duplicated property name " + propName + " on global " + global);
} else {
Object.defineProperty(globalObject, propName, {
get() {
return instance!.getGlobalProperty(globalName, prop.name);
},
set(value) {
instance!.setGlobalProperty(globalName, prop.name, value);
},
enumerable: true,
});
}
});
instance!.definition().globalCallbacks(globalName).forEach((cb) => {
let callbackName = cb.replace(/-/g, "_");
if (globalObject[callbackName] !== undefined) {
console.warn("Duplicated property name " + cb + " on global " + global);
} else {
Object.defineProperty(globalObject, cb.replace(/-/g, "_"), {
get() {
return function () {
return instance!.invokeGlobal(globalName, cb, Array.from(arguments));
};
},
set(callback) {
instance!.setGlobalCallback(globalName, cb, callback);
},
enumerable: true,
});
}
});
Object.defineProperty(componentHandle, globalName, {
get() {
return globalObject;
},
enumerable: true,
});
}
});
return Object.seal(componentHandle);
},
});
return Object.seal(slint_module);
}
/**
* Loads the given Slint file and returns an objects that contains a functions to construct the exported
* component of the slint file.
*
* The following example loads a "Hello World" style Slint file and changes the Text label to a new greeting:
* `main.slint`:
* ```
* export component Main {
* in-out property <string> greeting <=> label.text;
* label := Text {
* text: "Hello World";
* }
* }
* ```
*
* ```js
* import * as slint from "slint-ui";
* let ui = slint.loadFile("main.slint");
* let main = new ui.Main();
* main.greeting = "Hello friends";
* ```
*
* @param filePath A path to the file to load. If the path is a relative path, then it is resolved
* against the process' working directory.
* @param options Use {@link LoadFileOptions} to configure additional Slint compilation aspects,
* such as include search paths, library imports, or the widget style.
* @returns The returned object is sealed and provides a property by the name of the component exported
* in the `.slint` file. In the above example the name of the property is `Main`. The property
* is a constructor function. Use it with the new operator to instantiate the component.
* The instantiated object exposes properties and callbacks, and implements the {@link ComponentHandle} interface.
* For more details about the exposed properties, see [Instantiating A Component](../index.html#md:instantiating-a-component).
* @throws {@link CompileError} if errors occur during compilation.
*/
export function loadFile(filePath: string, options?: LoadFileOptions): Object {
return loadSlint({
fileData:{ filePath, options },
from:'file',
})
}
/**
* Loads the given Slint source code and returns an object that contains a function to construct the exported
* component of the Slint source code.
*
* The following example loads a "Hello World" style Slint source code and changes the Text label to a new greeting:
* ```js
* import * as slint from "slint-ui";
* const source = `export component Main {
* in-out property <string> greeting <=> label.text;
* label := Text {
* text: "Hello World";
* }
* }`; // The content of main.slint
* let ui = slint.loadSource(source, "main.js");
* let main = new ui.Main();
* main.greeting = "Hello friends";
* ```
* @param source The Slint source code to load.
* @param filePath A path to the file to show log. If the path is a relative path, then it is resolved
* against the process' working directory.
* @param options Use {@link LoadFileOptions} to configure additional Slint compilation aspects,
* such as include search paths, library imports, or the widget style.
* @returns The returned object is sealed and provides a property by the name of the component exported
* in the `.slint` file. In the above example the name of the property is `Main`. The property
* is a constructor function. Use it with the new operator to instantiate the component.
* The instantiated object exposes properties and callbacks, and implements the {@link ComponentHandle} interface.
* For more details about the exposed properties, see [Instantiating A Component](../index.html#md:instantiating-a-component).
* @throws {@link CompileError} if errors occur during compilation.
*/
export function loadSource(source: string, filePath: string, options?: LoadFileOptions): Object {
return loadSlint({
fileData:{ filePath, options, source },
from:'source',
})
}
class EventLoop {
#quit_loop: boolean = false;
#terminationPromise: Promise<unknown> | null = null;
#terminateResolveFn: ((_value: unknown) => void) | null;
constructor() {
}
start(running_callback?: Function): Promise<unknown> {
if (this.#terminationPromise != null) {
return this.#terminationPromise;
}
this.#terminationPromise = new Promise((resolve) => {
this.#terminateResolveFn = resolve;
});
this.#quit_loop = false;
if (running_callback != undefined) {
napi.invokeFromEventLoop(() => {
running_callback();
running_callback = undefined;
});
}
// Give the nodejs event loop 16 ms to tick. This polling is sub-optimal, but it's the best we
// can do right now.
const nodejsPollInterval = 16;
let id = setInterval(() => {
if (napi.processEvents() == napi.ProcessEventsResult.Exited || this.#quit_loop) {
clearInterval(id);
this.#terminateResolveFn!(undefined);
this.#terminateResolveFn = null;
this.#terminationPromise = null;
return;
}
}, nodejsPollInterval);
return this.#terminationPromise;
}
quit() {
this.#quit_loop = true;
}
}
var globalEventLoop: EventLoop = new EventLoop;
/**
* Spins the Slint event loop and returns a promise that resolves when the loop terminates.
*
* If the event loop is already running, then this function returns the same promise as from
* the earlier invocation.
*
* @param runningCallback Optional callback that's invoked once when the event loop is running.
* The function's return value is ignored.
*
* Note that the event loop integration with Node.js is slightly imperfect. Due to conflicting
* implementation details between Slint's and Node.js' event loop, the two loops are merged
* by spinning one after the other, at 16 millisecond intervals. This means that when the
* application is idle, it continues to consume a low amount of CPU cycles, checking if either
* event loop has any pending events.
*/
export function runEventLoop(runningCallback?: Function): Promise<unknown> {
return globalEventLoop.start(runningCallback)
}
/**
* Stops a spinning event loop. This function returns immediately, and the promise returned
from run_event_loop() will resolve in a later tick of the nodejs event loop.
*/
export function quitEventLoop() {
globalEventLoop.quit()
}
/**
* @hidden
*/
export namespace private_api {
export import mock_elapsed_time = napi.mockElapsedTime;
export import ComponentCompiler = napi.ComponentCompiler;
export import ComponentDefinition = napi.ComponentDefinition;
export import ComponentInstance = napi.ComponentInstance;
export import ValueType = napi.ValueType;
export import Window = napi.Window;
export import SlintBrush = napi.SlintBrush;
export import SlintRgbaColor = napi.SlintRgbaColor;
export import SlintSize = napi.SlintSize;
export import SlintPoint = napi.SlintPoint;
export import SlintImageData = napi.SlintImageData;
export function send_mouse_click(
component: Component,
x: number,
y: number
) {
component.component_instance.sendMouseClick(x, y);
}
export function send_keyboard_string_sequence(
component: Component,
s: string
) {
component.component_instance.sendKeyboardStringSequence(s);
}
}