qmlbox 0.0.0-stage → 0.1.1

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.
Binary file
@@ -0,0 +1,309 @@
1
+ // Copyright (C) 2023 The Qt Company Ltd.
2
+ // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
3
+
4
+ /**
5
+ * Loads the instance of a WASM module.
6
+ *
7
+ * @param config May contain any key normally accepted by emscripten and the 'qt' extra key, with
8
+ * the following sub-keys:
9
+ * - environment: { [name:string] : string }
10
+ * environment variables set on the instance
11
+ * - onExit: (exitStatus: { text: string, code?: number, crashed: bool }) => void
12
+ * called when the application has exited for any reason. There are two cases:
13
+ * aborted: crashed is true, text contains an error message.
14
+ * exited: crashed is false, code contians the exit code.
15
+ *
16
+ * Note that by default Emscripten does not exit when main() returns. This behavior
17
+ * is controlled by the EXIT_RUNTIME linker flag; set "-s EXIT_RUNTIME=1" to make
18
+ * Emscripten tear down the runtime and exit when main() returns.
19
+ *
20
+ * - containerElements: HTMLDivElement[]
21
+ * Array of host elements for Qt screens. Each of these elements is mapped to a QScreen on
22
+ * launch.
23
+ * - fontDpi: number
24
+ * Specifies font DPI for the instance
25
+ * - onLoaded: () => void
26
+ * Called when the module has loaded, at the point in time where any loading placeholder
27
+ * should be hidden and the application window should be shown.
28
+ * - entryFunction: (emscriptenConfig: object) => Promise<EmscriptenModule>
29
+ * Qt always uses emscripten's MODULARIZE option. This is the MODULARIZE entry function.
30
+ * - module: Promise<WebAssembly.Module>
31
+ * The module to create the instance from (optional). Specifying the module allows optimizing
32
+ * use cases where several instances are created from a single WebAssembly source.
33
+ * - qtdir: string
34
+ * Path to Qt installation. This path will be used for loading Qt shared libraries and plugins.
35
+ * The path is set to 'qt' by default, and is relative to the path of the web page's html file.
36
+ * This property is not in use when static linking is used, since this build mode includes all
37
+ * libraries and plugins in the wasm file.
38
+ * - preload: [string]: Array of file paths to json-encoded files which specifying which files to preload.
39
+ * The preloaded files will be downloaded at application startup and copied to the in-memory file
40
+ * system provided by Emscripten.
41
+ *
42
+ * Each json file must contain an array of source, destination objects:
43
+ * [
44
+ * {
45
+ * "source": "path/to/source",
46
+ * "destination": "/path/to/destination"
47
+ * },
48
+ * ...
49
+ * ]
50
+ * The source path is relative to the html file path. The destination path must be
51
+ * an absolute path.
52
+ *
53
+ * $QTDIR may be used as a placeholder for the "qtdir" configuration property (see @qtdir), for instance:
54
+ * "source": "$QTDIR/plugins/imageformats/libqjpeg.so"
55
+ * - localFonts.requestPermission: bool
56
+ * Whether Qt should request for local fonts access permission on startup (default false).
57
+ * - localFonts.familiesCollection string
58
+ * Specifies a collection of local fonts to load. Possible values are:
59
+ * "NoFontFamilies" : Don't load any font families
60
+ * "DefaultFontFamilies" : A subset of available font families; currently the "web-safe" fonts (default).
61
+ * "AllFontFamilies" : All local font families (not reccomended)
62
+ * - localFonts.extraFamilies: [string]
63
+ * Adds additional font families to be loaded at startup.
64
+ *
65
+ * @return Promise<instance: EmscriptenModule>
66
+ * The promise is resolved when the module has been instantiated and its main function has been
67
+ * called.
68
+ *
69
+ * @see https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/emscripten for
70
+ * EmscriptenModule
71
+ */
72
+ async function qtLoad(config)
73
+ {
74
+ const throwIfEnvUsedButNotExported = (instance, config) =>
75
+ {
76
+ const environment = config.qt.environment;
77
+ if (!environment || Object.keys(environment).length === 0)
78
+ return;
79
+ const descriptor = Object.getOwnPropertyDescriptor(instance, 'ENV');
80
+ const isEnvExported = typeof descriptor.value === 'object';
81
+ if (!isEnvExported) {
82
+ throw new Error('ENV must be exported if environment variables are passed, ' +
83
+ 'add it to the QT_WASM_EXTRA_EXPORTED_METHODS CMake target property');
84
+ }
85
+ };
86
+
87
+ if (typeof config !== 'object')
88
+ throw new Error('config is required, expected an object');
89
+ if (typeof config.qt !== 'object')
90
+ throw new Error('config.qt is required, expected an object');
91
+ if (typeof config.qt.entryFunction !== 'function')
92
+ throw new Error('config.qt.entryFunction is required, expected a function');
93
+
94
+ config.qt.qtdir ??= 'qt';
95
+ config.qt.preload ??= [];
96
+
97
+ config.qtContainerElements = config.qt.containerElements;
98
+ delete config.qt.containerElements;
99
+ config.qtFontDpi = config.qt.fontDpi;
100
+ delete config.qt.fontDpi;
101
+
102
+ // Make Emscripten not call main(); this gives us more control over
103
+ // the startup sequence.
104
+ const originalNoInitialRun = config.noInitialRun;
105
+ const originalArguments = config.arguments;
106
+ config.noInitialRun = true;
107
+
108
+ // Used for rejecting a failed load's promise where emscripten itself does not allow it,
109
+ // like in instantiateWasm below. This allows us to throw in case of a load error instead of
110
+ // hanging on a promise to entry function, which emscripten unfortunately does.
111
+ let circuitBreakerReject;
112
+ const circuitBreaker = new Promise((_, reject) => { circuitBreakerReject = reject; });
113
+
114
+ // If module async getter is present, use it so that module reuse is possible.
115
+ if (config.qt.module) {
116
+ config.instantiateWasm = async (imports, successCallback) =>
117
+ {
118
+ try {
119
+ const module = await config.qt.module;
120
+ successCallback(
121
+ await WebAssembly.instantiate(module, imports), module);
122
+ } catch (e) {
123
+ circuitBreakerReject(e);
124
+ }
125
+ }
126
+ }
127
+ const preloadFetchHelper = async (path) => {
128
+ const response = await fetch(path);
129
+ if (!response.ok)
130
+ throw new Error("Could not fetch preload file: " + path);
131
+ return response.json();
132
+ }
133
+ const filesToPreload = (await Promise.all(config.qt.preload.map(preloadFetchHelper))).flat();
134
+ const qtPreRun = (instance) => {
135
+ // Copy qt.environment to instance.ENV
136
+ throwIfEnvUsedButNotExported(instance, config);
137
+ for (const [name, value] of Object.entries(config.qt.environment ?? {}))
138
+ instance.ENV[name] = value;
139
+
140
+ // Preload files from qt.preload
141
+ const makeDirs = (FS, filePath) => {
142
+ const parts = filePath.split("/");
143
+ let path = "/";
144
+ for (let i = 0; i < parts.length - 1; ++i) {
145
+ const part = parts[i];
146
+ if (part == "")
147
+ continue;
148
+ path += part + "/";
149
+ try {
150
+ FS.mkdir(path);
151
+ } catch (error) {
152
+ const EEXIST = 20;
153
+ if (error.errno != EEXIST)
154
+ throw error;
155
+ }
156
+ }
157
+ }
158
+
159
+ const extractFilenameAndDir = (path) => {
160
+ const parts = path.split('/');
161
+ const filename = parts.pop();
162
+ const dir = parts.join('/');
163
+ return {
164
+ filename: filename,
165
+ dir: dir
166
+ };
167
+ }
168
+ const preloadFile = (file) => {
169
+ makeDirs(instance.FS, file.destination);
170
+ const source = file.source.replace('$QTDIR', config.qt.qtdir);
171
+ const filenameAndDir = extractFilenameAndDir(file.destination);
172
+ instance.FS.createPreloadedFile(filenameAndDir.dir, filenameAndDir.filename, source, true, true);
173
+ }
174
+ const isFsExported = typeof instance.FS === 'object';
175
+ if (!isFsExported)
176
+ throw new Error('FS must be exported if preload is used');
177
+ filesToPreload.forEach(preloadFile);
178
+ }
179
+
180
+ if (!config.preRun)
181
+ config.preRun = [];
182
+ config.preRun.push(qtPreRun);
183
+
184
+ const originalOnRuntimeInitialized = config.onRuntimeInitialized;
185
+ config.onRuntimeInitialized = () => {
186
+ originalOnRuntimeInitialized?.();
187
+ config.qt.onLoaded?.();
188
+ }
189
+
190
+ const originalLocateFile = config.locateFile;
191
+ config.locateFile = filename => {
192
+ const originalLocatedFilename = originalLocateFile ? originalLocateFile(filename) : filename;
193
+ if (originalLocatedFilename.startsWith('libQt6'))
194
+ return `${config.qt.qtdir}/lib/${originalLocatedFilename}`;
195
+ return originalLocatedFilename;
196
+ }
197
+
198
+ let onExitCalled = false;
199
+ const originalOnExit = config.onExit;
200
+ config.onExit = code => {
201
+ originalOnExit?.();
202
+
203
+ if (!onExitCalled) {
204
+ onExitCalled = true;
205
+ config.qt.onExit?.({
206
+ code,
207
+ crashed: false
208
+ });
209
+ }
210
+ }
211
+
212
+ const originalOnAbort = config.onAbort;
213
+ config.onAbort = text =>
214
+ {
215
+ originalOnAbort?.();
216
+
217
+ if (!onExitCalled) {
218
+ onExitCalled = true;
219
+ config.qt.onExit?.({
220
+ text,
221
+ crashed: true
222
+ });
223
+ }
224
+ };
225
+
226
+ // Call app/emscripten module entry function. It may either come from the emscripten
227
+ // runtime script or be customized as needed.
228
+ let instance;
229
+ try {
230
+ instance = await Promise.race(
231
+ [circuitBreaker, config.qt.entryFunction(config)]);
232
+
233
+ // Call main after creating the instance. We've opted into manually
234
+ // calling main() by setting noInitialRun in the config. Thie Works around
235
+ // issue where Emscripten suppresses all exceptions thrown during main.
236
+ if (!originalNoInitialRun)
237
+ instance.callMain(originalArguments);
238
+ } catch (e) {
239
+ // If this is the exception thrown by app.exec() then that is a normal
240
+ // case and we suppress it.
241
+ if (e == "unwind") // not much to go on
242
+ return;
243
+
244
+ if (!onExitCalled) {
245
+ onExitCalled = true;
246
+ config.qt.onExit?.({
247
+ text: e.message,
248
+ crashed: true
249
+ });
250
+ }
251
+ throw e;
252
+ }
253
+
254
+ return instance;
255
+ }
256
+
257
+ // Compatibility API. This API is deprecated,
258
+ // and will be removed in a future version of Qt.
259
+ function QtLoader(qtConfig) {
260
+
261
+ const warning = 'Warning: The QtLoader API is deprecated and will be removed in ' +
262
+ 'a future version of Qt. Please port to the new qtLoad() API.';
263
+ console.warn(warning);
264
+
265
+ let emscriptenConfig = qtConfig.moduleConfig || {}
266
+ qtConfig.moduleConfig = undefined;
267
+ const showLoader = qtConfig.showLoader;
268
+ qtConfig.showLoader = undefined;
269
+ const showError = qtConfig.showError;
270
+ qtConfig.showError = undefined;
271
+ const showExit = qtConfig.showExit;
272
+ qtConfig.showExit = undefined;
273
+ const showCanvas = qtConfig.showCanvas;
274
+ qtConfig.showCanvas = undefined;
275
+ if (qtConfig.canvasElements) {
276
+ qtConfig.containerElements = qtConfig.canvasElements
277
+ qtConfig.canvasElements = undefined;
278
+ } else {
279
+ qtConfig.containerElements = qtConfig.containerElements;
280
+ qtConfig.containerElements = undefined;
281
+ }
282
+ emscriptenConfig.qt = qtConfig;
283
+
284
+ let qtloader = {
285
+ exitCode: undefined,
286
+ exitText: "",
287
+ loadEmscriptenModule: _name => {
288
+ try {
289
+ qtLoad(emscriptenConfig);
290
+ } catch (e) {
291
+ showError?.(e.message);
292
+ }
293
+ }
294
+ }
295
+
296
+ qtConfig.onLoaded = () => {
297
+ showCanvas?.();
298
+ }
299
+
300
+ qtConfig.onExit = exit => {
301
+ qtloader.exitCode = exit.code
302
+ qtloader.exitText = exit.text;
303
+ showExit?.();
304
+ }
305
+
306
+ showLoader?.("Loading");
307
+
308
+ return qtloader;
309
+ };