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.
- package/LICENSE +232 -0
- package/README.md +166 -2
- package/dist/index.cjs +794 -0
- package/dist/index.d.cts +109 -0
- package/dist/index.d.ts +109 -0
- package/dist/index.js +758 -0
- package/package.json +58 -4
- package/wasm/qml_engine.js +18 -0
- package/wasm/qml_engine.wasm +0 -0
- package/wasm/qtloader.js +309 -0
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,794 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
QmlViewer: () => QmlViewer,
|
|
24
|
+
SUPPORTED_QML_VERSIONS: () => SUPPORTED_QML_VERSIONS,
|
|
25
|
+
fromCodeString: () => fromCodeString,
|
|
26
|
+
fromFolderInput: () => fromFolderInput,
|
|
27
|
+
fromGitHubRepo: () => fromGitHubRepo,
|
|
28
|
+
fromSingleFile: () => fromSingleFile,
|
|
29
|
+
fromZipFile: () => fromZipFile,
|
|
30
|
+
parseIni: () => parseIni,
|
|
31
|
+
parseThemeConfig: () => parseThemeConfig,
|
|
32
|
+
transformQmlImports: () => transformQmlImports
|
|
33
|
+
});
|
|
34
|
+
module.exports = __toCommonJS(index_exports);
|
|
35
|
+
|
|
36
|
+
// src/loaders.ts
|
|
37
|
+
var import_fflate = require("fflate");
|
|
38
|
+
var encoder = new TextEncoder();
|
|
39
|
+
var githubApi = "https://api.github.com";
|
|
40
|
+
var maxZipBytes = 128 * 1024 * 1024;
|
|
41
|
+
var maxZipFiles = 4096;
|
|
42
|
+
function normalizePath(path) {
|
|
43
|
+
const relativePath = path.replaceAll("\\", "/");
|
|
44
|
+
const parts = relativePath.split("/");
|
|
45
|
+
if (relativePath.startsWith("/") || /^[A-Za-z]:/.test(relativePath) || parts.includes("..") || /[\u0000-\u001f\u007f]/.test(path)) {
|
|
46
|
+
throw new Error(`Invalid relative theme path: ${path}`);
|
|
47
|
+
}
|
|
48
|
+
const normalized = parts.filter((part) => part && part !== ".").join("/");
|
|
49
|
+
if (!normalized) throw new Error("A theme file needs a relative path.");
|
|
50
|
+
return normalized;
|
|
51
|
+
}
|
|
52
|
+
function insertFile(files, path, bytes) {
|
|
53
|
+
if (Object.hasOwn(files, path)) throw new Error(`Duplicate theme file: ${path}`);
|
|
54
|
+
files[path] = bytes;
|
|
55
|
+
}
|
|
56
|
+
function newFileMap() {
|
|
57
|
+
return /* @__PURE__ */ Object.create(null);
|
|
58
|
+
}
|
|
59
|
+
function fromCodeString(source) {
|
|
60
|
+
const files = newFileMap();
|
|
61
|
+
files["Main.qml"] = encoder.encode(source);
|
|
62
|
+
return files;
|
|
63
|
+
}
|
|
64
|
+
async function fromSingleFile(file) {
|
|
65
|
+
const name = normalizePath(file.name);
|
|
66
|
+
if (!/\.qml$/i.test(name)) throw new Error("Select a .qml file.");
|
|
67
|
+
const files = newFileMap();
|
|
68
|
+
files[name] = new Uint8Array(await file.arrayBuffer());
|
|
69
|
+
return files;
|
|
70
|
+
}
|
|
71
|
+
async function fromFolderInput(input) {
|
|
72
|
+
const uploads = Array.from(input, (file) => ({
|
|
73
|
+
file,
|
|
74
|
+
path: normalizePath(file.webkitRelativePath || file.name)
|
|
75
|
+
}));
|
|
76
|
+
if (!uploads.length) throw new Error("The selected folder contains no files.");
|
|
77
|
+
const root = uploads[0].path.split("/")[0] + "/";
|
|
78
|
+
const stripRoot = uploads.every(({ path }) => path.startsWith(root));
|
|
79
|
+
const files = newFileMap();
|
|
80
|
+
for (const { file, path } of uploads) {
|
|
81
|
+
insertFile(files, stripRoot ? path.slice(root.length) : path, new Uint8Array(await file.arrayBuffer()));
|
|
82
|
+
}
|
|
83
|
+
return files;
|
|
84
|
+
}
|
|
85
|
+
async function fromZipFile(file) {
|
|
86
|
+
if (file.size > maxZipBytes) throw new Error("The ZIP exceeds 128 MiB.");
|
|
87
|
+
let expandedBytes = 0;
|
|
88
|
+
let fileCount = 0;
|
|
89
|
+
const paths = /* @__PURE__ */ new Set();
|
|
90
|
+
const archive = (0, import_fflate.unzipSync)(new Uint8Array(await file.arrayBuffer()), {
|
|
91
|
+
filter({ name, originalSize }) {
|
|
92
|
+
if (name.endsWith("/") || name.endsWith("\\")) return false;
|
|
93
|
+
const path = normalizePath(name);
|
|
94
|
+
if (path === "__proto__" || paths.has(path)) throw new Error(`Invalid or duplicate ZIP entry: ${path}`);
|
|
95
|
+
paths.add(path);
|
|
96
|
+
expandedBytes += originalSize;
|
|
97
|
+
fileCount += 1;
|
|
98
|
+
if (expandedBytes > maxZipBytes || fileCount > maxZipFiles) {
|
|
99
|
+
throw new Error("The ZIP exceeds 128 MiB unpacked or contains more than 4096 files.");
|
|
100
|
+
}
|
|
101
|
+
return true;
|
|
102
|
+
}
|
|
103
|
+
});
|
|
104
|
+
const entries = Object.entries(archive).map(([path, bytes]) => [normalizePath(path), bytes]);
|
|
105
|
+
if (!entries.length) throw new Error("The ZIP contains no files.");
|
|
106
|
+
let prefix = "";
|
|
107
|
+
for (const part of entries[0][0].split("/").slice(0, -1)) {
|
|
108
|
+
const candidate = `${prefix}${part}/`;
|
|
109
|
+
if (!entries.every(([path]) => path.startsWith(candidate))) break;
|
|
110
|
+
prefix = candidate;
|
|
111
|
+
}
|
|
112
|
+
const files = newFileMap();
|
|
113
|
+
for (const [path, bytes] of entries) insertFile(files, path.slice(prefix.length), bytes);
|
|
114
|
+
return files;
|
|
115
|
+
}
|
|
116
|
+
var GitHubRequestError = class extends Error {
|
|
117
|
+
constructor(status, message) {
|
|
118
|
+
super(message);
|
|
119
|
+
this.status = status;
|
|
120
|
+
}
|
|
121
|
+
status;
|
|
122
|
+
};
|
|
123
|
+
async function fromGitHubRepo(url, options = {}) {
|
|
124
|
+
const repoUrl = new URL(url);
|
|
125
|
+
const [owner, repoName, view, ...treePath] = repoUrl.pathname.split("/").filter(Boolean).map(decodeURIComponent);
|
|
126
|
+
const repo = repoName?.replace(/\.git$/, "");
|
|
127
|
+
if (repoUrl.protocol !== "https:" || repoUrl.host !== "github.com" || !owner || !repo || !/^[\w.-]+$/.test(owner) || !/^[\w.-]+$/.test(repo) || view !== void 0 && (view !== "tree" || !treePath.length)) {
|
|
128
|
+
throw new Error("Enter a GitHub repository URL or a URL pointing to a folder in that repository.");
|
|
129
|
+
}
|
|
130
|
+
const repoEndpoint = `${githubApi}/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`;
|
|
131
|
+
const headers = new Headers({ Accept: "application/vnd.github+json" });
|
|
132
|
+
const controller = new AbortController();
|
|
133
|
+
const signal = options.signal ? AbortSignal.any([controller.signal, options.signal]) : controller.signal;
|
|
134
|
+
if (options.token) headers.set("Authorization", `Bearer ${options.token}`);
|
|
135
|
+
async function request(path, raw = false) {
|
|
136
|
+
const requestHeaders = new Headers(headers);
|
|
137
|
+
if (raw) requestHeaders.set("Accept", "application/vnd.github.raw+json");
|
|
138
|
+
const response = await fetch(repoEndpoint + path, {
|
|
139
|
+
headers: requestHeaders,
|
|
140
|
+
signal
|
|
141
|
+
});
|
|
142
|
+
if (!response.ok) {
|
|
143
|
+
const limited = response.status === 429 || response.headers.get("x-ratelimit-remaining") === "0";
|
|
144
|
+
const message = limited ? "The GitHub API rate limit was reached." : `GitHub returned HTTP ${response.status} for ${owner}/${repo}${path}.`;
|
|
145
|
+
throw new GitHubRequestError(response.status, message);
|
|
146
|
+
}
|
|
147
|
+
return response;
|
|
148
|
+
}
|
|
149
|
+
async function readTree(ref2, recursive) {
|
|
150
|
+
const path = `/git/trees/${encodeURIComponent(ref2)}${recursive ? "?recursive=1" : ""}`;
|
|
151
|
+
return (await request(path)).json();
|
|
152
|
+
}
|
|
153
|
+
let ref = options.ref;
|
|
154
|
+
let directory2 = options.subdirectory ?? "";
|
|
155
|
+
let result;
|
|
156
|
+
if (!ref && treePath.length) {
|
|
157
|
+
for (let length = treePath.length; length > 0; length--) {
|
|
158
|
+
const candidate = treePath.slice(0, length).join("/");
|
|
159
|
+
try {
|
|
160
|
+
result = await readTree(candidate, true);
|
|
161
|
+
ref = candidate;
|
|
162
|
+
directory2 = options.subdirectory ?? treePath.slice(length).join("/");
|
|
163
|
+
break;
|
|
164
|
+
} catch (error) {
|
|
165
|
+
if (!(error instanceof GitHubRequestError) || error.status !== 404 || length === 1) throw error;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
} else if (!ref) {
|
|
169
|
+
const info = await (await request("")).json();
|
|
170
|
+
ref = info.default_branch;
|
|
171
|
+
} else if (options.subdirectory === void 0 && treePath.length) {
|
|
172
|
+
const urlPath = treePath.join("/");
|
|
173
|
+
if (urlPath.startsWith(ref + "/")) directory2 = urlPath.slice(ref.length + 1);
|
|
174
|
+
}
|
|
175
|
+
if (!ref) throw new Error("The GitHub repository has no branch to load.");
|
|
176
|
+
const folder = directory2 ? normalizePath(directory2.replace(/\/+$/, "")) : "";
|
|
177
|
+
const prefix = folder ? `${folder}/` : "";
|
|
178
|
+
result ??= await readTree(ref, true);
|
|
179
|
+
async function readSubtrees(treeRef) {
|
|
180
|
+
const files2 = [];
|
|
181
|
+
const pending = [{ ref: treeRef, prefix: "" }];
|
|
182
|
+
while (pending.length) {
|
|
183
|
+
const subtree = pending.pop();
|
|
184
|
+
const listing = await readTree(subtree.ref, false);
|
|
185
|
+
if (listing.truncated) throw new Error("GitHub truncated a non-recursive tree listing.");
|
|
186
|
+
for (const item of listing.tree) {
|
|
187
|
+
const path = subtree.prefix + item.path;
|
|
188
|
+
if (item.type === "tree") pending.push({ ref: item.sha, prefix: `${path}/` });
|
|
189
|
+
else files2.push({ ...item, path });
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
return files2;
|
|
193
|
+
}
|
|
194
|
+
let entries;
|
|
195
|
+
if (!result.truncated) {
|
|
196
|
+
entries = result.tree.filter((item) => item.path.startsWith(prefix)).map((item) => ({ ...item, path: item.path.slice(prefix.length) }));
|
|
197
|
+
} else {
|
|
198
|
+
let subtree = ref;
|
|
199
|
+
for (const part of folder ? folder.split("/") : []) {
|
|
200
|
+
const listing = await readTree(subtree, false);
|
|
201
|
+
const match = listing.tree.find((item) => item.type === "tree" && item.path === part);
|
|
202
|
+
if (!match) throw new Error(`The folder "${folder}" does not exist in the repository.`);
|
|
203
|
+
subtree = match.sha;
|
|
204
|
+
}
|
|
205
|
+
entries = await readSubtrees(subtree);
|
|
206
|
+
}
|
|
207
|
+
const blobs = entries.filter((item) => item.type === "blob" && item.mode !== "120000");
|
|
208
|
+
if (!blobs.length) throw new Error(`GitHub returned no regular files${folder ? ` in "${folder}"` : ""}.`);
|
|
209
|
+
const files = newFileMap();
|
|
210
|
+
const downloads = /* @__PURE__ */ new Map();
|
|
211
|
+
const rawBase = `https://raw.githubusercontent.com/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/${encodeURIComponent(ref)}`;
|
|
212
|
+
let next = 0;
|
|
213
|
+
async function downloadFiles() {
|
|
214
|
+
while (!signal.aborted && next < blobs.length) {
|
|
215
|
+
const { path, sha } = blobs[next++];
|
|
216
|
+
const normalized = normalizePath(path);
|
|
217
|
+
let download = downloads.get(sha);
|
|
218
|
+
if (!download) {
|
|
219
|
+
if (!options.token) {
|
|
220
|
+
const fullRepoPath = prefix ? `${prefix}${normalized}` : normalized;
|
|
221
|
+
const rawUrl = `${rawBase}/${fullRepoPath.split("/").map(encodeURIComponent).join("/")}`;
|
|
222
|
+
download = fetch(rawUrl, { signal }).then(async (response) => {
|
|
223
|
+
if (!response.ok) {
|
|
224
|
+
throw new GitHubRequestError(response.status, `GitHub returned HTTP ${response.status} for ${fullRepoPath}.`);
|
|
225
|
+
}
|
|
226
|
+
return new Uint8Array(await response.arrayBuffer());
|
|
227
|
+
});
|
|
228
|
+
} else {
|
|
229
|
+
download = request(`/git/blobs/${encodeURIComponent(sha)}`, true).then((response) => response.arrayBuffer()).then((buffer) => new Uint8Array(buffer));
|
|
230
|
+
}
|
|
231
|
+
downloads.set(sha, download);
|
|
232
|
+
}
|
|
233
|
+
insertFile(files, normalized, await download);
|
|
234
|
+
}
|
|
235
|
+
signal.throwIfAborted();
|
|
236
|
+
}
|
|
237
|
+
try {
|
|
238
|
+
await Promise.all(Array.from({ length: Math.min(6, blobs.length) }, downloadFiles));
|
|
239
|
+
} catch (error) {
|
|
240
|
+
controller.abort(error);
|
|
241
|
+
throw error;
|
|
242
|
+
}
|
|
243
|
+
return files;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// src/qmlShims.ts
|
|
247
|
+
var FALLBACK_QML_SHIMS = {
|
|
248
|
+
"QtMultimedia/AudioOutput.qml": "import QtQuick\n\nQtObject {\n property real volume: 1.0\n property bool muted: false\n property var device: null\n}\n",
|
|
249
|
+
"QtMultimedia/MediaDevices.qml": "import QtQuick\n\nQtObject {\n readonly property var audioInputs: []\n readonly property var audioOutputs: []\n readonly property var videoInputs: []\n readonly property var defaultAudioInput: null\n readonly property var defaultAudioOutput: null\n readonly property var defaultVideoInput: null\n}\n",
|
|
250
|
+
"QtMultimedia/MediaPlayer.qml": 'import QtQuick\n\nQtObject {\n id: player\n\n enum Loops {\n Once = 1,\n Infinite = -1\n }\n enum PlaybackState {\n StoppedState = 0,\n PlayingState = 1,\n PausedState = 2\n }\n enum MediaStatus {\n NoMedia = 0,\n LoadingMedia = 1,\n LoadedMedia = 2,\n StalledMedia = 3,\n BufferingMedia = 4,\n BufferedMedia = 5,\n EndOfMedia = 6,\n InvalidMedia = 7\n }\n enum Error {\n NoError = 0,\n ResourceError = 1,\n FormatError = 2,\n NetworkError = 3,\n AccessDeniedError = 4\n }\n\n property url source: ""\n property var videoOutput: null\n property var audioOutput: null\n property bool autoPlay: false\n property real playbackRate: 1.0\n property int loops: 1\n property bool muted: false\n property real volume: 1.0\n property int playbackState: 0\n readonly property bool playing: playbackState === 1\n property int mediaStatus: 0\n property int position: 0\n property int duration: 0\n property bool hasVideo: false\n property bool hasAudio: false\n property int error: 0\n property string errorString: ""\n\n onSourceChanged: {\n syncVideoOutput()\n if (autoPlay && source.toString() !== "")\n play()\n }\n\n onVideoOutputChanged: syncVideoOutput()\n\n function syncVideoOutput() {\n if (!videoOutput)\n return\n if ("source" in videoOutput)\n videoOutput.source = source\n }\n\n function play() {\n const uri = source.toString()\n if (uri === "")\n return\n syncVideoOutput()\n const isImage = /\\.(gif|png|jpe?g|webp|svg|bmp)(\\?|#|$)/i.test(uri)\n hasVideo = isImage\n mediaStatus = 2\n playbackState = isImage ? 1 : 0\n }\n\n function pause() {\n if (playbackState === 1)\n playbackState = 2\n }\n\n function stop() {\n playbackState = 0\n position = 0\n }\n\n function setPosition(pos) {\n position = pos\n }\n}\n',
|
|
251
|
+
"QtMultimedia/VideoOutput.qml": 'import QtQuick\n\nItem {\n id: output\n\n enum FillMode {\n Stretch = 0,\n PreserveAspectFit = 1,\n PreserveAspectCrop = 2\n }\n\n property int fillMode: Image.PreserveAspectFit\n property int orientation: 0\n property url source: ""\n property rect contentRect: Qt.rect(0, 0, width, height)\n property rect sourceRect: Qt.rect(0, 0, width, height)\n\n readonly property bool isImageSource: /\\.(gif|png|jpe?g|webp|svg|bmp)(\\?|#|$)/i.test(source.toString())\n\n AnimatedImage {\n id: fallbackImage\n anchors.fill: parent\n source: output.isImageSource ? output.source : ""\n fillMode: output.fillMode\n visible: output.isImageSource && status === AnimatedImage.Ready\n playing: visible\n clip: true\n }\n}\n',
|
|
252
|
+
"QtMultimedia/qmldir": "module QtMultimedia\n\nMediaPlayer 1.0 MediaPlayer.qml\nMediaPlayer 5.0 MediaPlayer.qml\nMediaPlayer 5.12 MediaPlayer.qml\nMediaPlayer 5.15 MediaPlayer.qml\nMediaPlayer 6.0 MediaPlayer.qml\nVideoOutput 1.0 VideoOutput.qml\nVideoOutput 5.0 VideoOutput.qml\nVideoOutput 5.12 VideoOutput.qml\nVideoOutput 5.15 VideoOutput.qml\nVideoOutput 6.0 VideoOutput.qml\nAudioOutput 1.0 AudioOutput.qml\nAudioOutput 6.0 AudioOutput.qml\nMediaDevices 1.0 MediaDevices.qml\nMediaDevices 6.0 MediaDevices.qml\n",
|
|
253
|
+
"Qt5Compat/GraphicalEffects/BrightnessContrast.qml": "import QtQuick\nimport QtQuick.Effects\n\nMultiEffect {\n property bool cached: false\n}\n",
|
|
254
|
+
"Qt5Compat/GraphicalEffects/ColorOverlay.qml": 'import QtQuick\nimport QtQuick.Effects\n\nMultiEffect {\n property color color: "#000000"\n property bool cached: false\n\n colorization: 1.0\n colorizationColor: color\n}\n',
|
|
255
|
+
"Qt5Compat/GraphicalEffects/Colorize.qml": "import QtQuick\nimport QtQuick.Effects\n\nMultiEffect {\n property real hue: 0.0\n property real saturation: 0.5\n property real lightness: 0.0\n property bool cached: false\n\n colorization: 1.0\n colorizationColor: Qt.hsla(hue, saturation, Math.max(0.0, Math.min(1.0, 0.5 + lightness * 0.5)), 1.0)\n}\n",
|
|
256
|
+
"Qt5Compat/GraphicalEffects/Desaturate.qml": "import QtQuick\nimport QtQuick.Effects\n\nMultiEffect {\n property real desaturation: 0.0\n property bool cached: false\n\n saturation: -Math.max(0.0, Math.min(1.0, desaturation))\n}\n",
|
|
257
|
+
"Qt5Compat/GraphicalEffects/DropShadow.qml": 'import QtQuick\nimport QtQuick.Effects\n\nMultiEffect {\n property color color: "#80000000"\n property real horizontalOffset: 0\n property real verticalOffset: 0\n property real radius: 0\n property int samples: 9\n property real spread: 0\n property bool fast: false\n property bool transparentBorder: true\n property bool cached: false\n\n shadowEnabled: true\n shadowColor: color\n shadowHorizontalOffset: horizontalOffset\n shadowVerticalOffset: verticalOffset\n shadowBlur: Math.min(1.0, Math.max(0.0, radius / 32.0))\n shadowScale: 1.0 + Math.max(0.0, spread) * 0.2\n autoPaddingEnabled: transparentBorder\n}\n',
|
|
258
|
+
"Qt5Compat/GraphicalEffects/FastBlur.qml": "import QtQuick\nimport QtQuick.Effects\n\nMultiEffect {\n property real radius: 0\n property bool transparentBorder: false\n property bool cached: false\n\n blurEnabled: radius > 0\n blurMax: 64\n blur: Math.min(1.0, Math.max(0.0, radius / 64.0))\n autoPaddingEnabled: transparentBorder\n}\n",
|
|
259
|
+
"Qt5Compat/GraphicalEffects/GaussianBlur.qml": "import QtQuick\nimport QtQuick.Effects\n\nMultiEffect {\n property real radius: 0\n property int samples: 9\n property real deviation: 0\n property bool transparentBorder: false\n property bool cached: false\n\n blurEnabled: radius > 0\n blurMax: 64\n blur: Math.min(1.0, Math.max(0.0, radius / 64.0))\n autoPaddingEnabled: transparentBorder\n}\n",
|
|
260
|
+
"Qt5Compat/GraphicalEffects/Glow.qml": 'import QtQuick\nimport QtQuick.Effects\n\nMultiEffect {\n property color color: "#ffffff"\n property real radius: 0\n property int samples: 9\n property real spread: 0\n property bool fast: false\n property bool transparentBorder: true\n property bool cached: false\n\n shadowEnabled: true\n shadowColor: color\n shadowHorizontalOffset: 0\n shadowVerticalOffset: 0\n shadowBlur: Math.min(1.0, Math.max(0.0, radius / 32.0))\n shadowScale: 1.0 + Math.max(0.0, spread) * 0.2\n autoPaddingEnabled: transparentBorder\n}\n',
|
|
261
|
+
"Qt5Compat/GraphicalEffects/HueSaturation.qml": "import QtQuick\nimport QtQuick.Effects\n\nMultiEffect {\n property real hue: 0.0\n property bool cached: false\n}\n",
|
|
262
|
+
"Qt5Compat/GraphicalEffects/LinearGradient.qml": 'import QtQuick\n\nItem {\n id: root\n property point start: Qt.point(0, 0)\n property point end: Qt.point(0, height)\n property var source: null\n property bool cached: false\n default property list<GradientStop> stops\n\n Canvas {\n anchors.fill: parent\n onPaint: {\n const ctx = getContext("2d")\n ctx.clearRect(0, 0, width, height)\n const g = ctx.createLinearGradient(root.start.x, root.start.y, root.end.x, root.end.y)\n for (let i = 0; i < root.stops.length; i++) {\n const s = root.stops[i]\n g.addColorStop(Math.max(0, Math.min(1, s.position)), s.color.toString())\n }\n ctx.fillStyle = g\n ctx.fillRect(0, 0, width, height)\n }\n onWidthChanged: requestPaint()\n onHeightChanged: requestPaint()\n }\n}\n',
|
|
263
|
+
"Qt5Compat/GraphicalEffects/OpacityMask.qml": "import QtQuick\nimport QtQuick.Effects\n\nMultiEffect {\n property bool invert: false\n property bool cached: false\n\n maskEnabled: true\n maskInverted: invert\n}\n",
|
|
264
|
+
"Qt5Compat/GraphicalEffects/RadialGradient.qml": 'import QtQuick\n\nItem {\n id: root\n property real horizontalOffset: 0\n property real verticalOffset: 0\n property real horizontalRadius: width / 2\n property real verticalRadius: height / 2\n property real angle: 0\n property var source: null\n property bool cached: false\n default property list<GradientStop> stops\n\n Canvas {\n anchors.fill: parent\n onPaint: {\n const ctx = getContext("2d")\n ctx.clearRect(0, 0, width, height)\n const cx = width / 2 + root.horizontalOffset\n const cy = height / 2 + root.verticalOffset\n const r = Math.max(1, Math.max(root.horizontalRadius, root.verticalRadius))\n const g = ctx.createRadialGradient(cx, cy, 0, cx, cy, r)\n for (let i = 0; i < root.stops.length; i++) {\n const s = root.stops[i]\n g.addColorStop(Math.max(0, Math.min(1, s.position)), s.color.toString())\n }\n ctx.fillStyle = g\n ctx.fillRect(0, 0, width, height)\n }\n onWidthChanged: requestPaint()\n onHeightChanged: requestPaint()\n }\n}\n',
|
|
265
|
+
"Qt5Compat/GraphicalEffects/RectangularGlow.qml": "import QtQuick\n\nRectangle {\n property real glowRadius: 0\n property real spread: 0\n property real cornerRadius: 0\n property bool cached: false\n\n radius: cornerRadius + glowRadius * 0.5\n opacity: 0.45\n}\n",
|
|
266
|
+
"Qt5Compat/GraphicalEffects/ThresholdMask.qml": "import QtQuick\nimport QtQuick.Effects\n\nMultiEffect {\n property real threshold: 0.5\n property real spread: 0.0\n property bool cached: false\n\n maskEnabled: true\n maskThresholdMin: Math.max(0.0, threshold - spread)\n maskSpreadAtMin: Math.max(0.0, spread)\n}\n",
|
|
267
|
+
"Qt5Compat/GraphicalEffects/qmldir": "module Qt5Compat.GraphicalEffects\n\nBrightnessContrast 1.0 BrightnessContrast.qml\nBrightnessContrast 1.15 BrightnessContrast.qml\nBrightnessContrast 6.0 BrightnessContrast.qml\nColorize 1.0 Colorize.qml\nColorize 1.15 Colorize.qml\nColorize 6.0 Colorize.qml\nColorOverlay 1.0 ColorOverlay.qml\nColorOverlay 1.15 ColorOverlay.qml\nColorOverlay 6.0 ColorOverlay.qml\nDesaturate 1.0 Desaturate.qml\nDesaturate 1.15 Desaturate.qml\nDesaturate 6.0 Desaturate.qml\nDropShadow 1.0 DropShadow.qml\nDropShadow 1.15 DropShadow.qml\nDropShadow 6.0 DropShadow.qml\nFastBlur 1.0 FastBlur.qml\nFastBlur 1.15 FastBlur.qml\nFastBlur 6.0 FastBlur.qml\nGaussianBlur 1.0 GaussianBlur.qml\nGaussianBlur 1.15 GaussianBlur.qml\nGaussianBlur 6.0 GaussianBlur.qml\nGlow 1.0 Glow.qml\nGlow 1.15 Glow.qml\nGlow 6.0 Glow.qml\nHueSaturation 1.0 HueSaturation.qml\nHueSaturation 1.15 HueSaturation.qml\nHueSaturation 6.0 HueSaturation.qml\nLinearGradient 1.0 LinearGradient.qml\nLinearGradient 1.15 LinearGradient.qml\nLinearGradient 6.0 LinearGradient.qml\nOpacityMask 1.0 OpacityMask.qml\nOpacityMask 1.15 OpacityMask.qml\nOpacityMask 6.0 OpacityMask.qml\nRadialGradient 1.0 RadialGradient.qml\nRadialGradient 1.15 RadialGradient.qml\nRadialGradient 6.0 RadialGradient.qml\nRectangularGlow 1.0 RectangularGlow.qml\nRectangularGlow 1.15 RectangularGlow.qml\nRectangularGlow 6.0 RectangularGlow.qml\nThresholdMask 1.0 ThresholdMask.qml\nThresholdMask 1.15 ThresholdMask.qml\nThresholdMask 6.0 ThresholdMask.qml\n",
|
|
268
|
+
"QtGraphicalEffects/qmldir": "module QtGraphicalEffects\n\nBrightnessContrast 1.0 ../Qt5Compat/GraphicalEffects/BrightnessContrast.qml\nBrightnessContrast 1.15 ../Qt5Compat/GraphicalEffects/BrightnessContrast.qml\nColorize 1.0 ../Qt5Compat/GraphicalEffects/Colorize.qml\nColorize 1.15 ../Qt5Compat/GraphicalEffects/Colorize.qml\nColorOverlay 1.0 ../Qt5Compat/GraphicalEffects/ColorOverlay.qml\nColorOverlay 1.15 ../Qt5Compat/GraphicalEffects/ColorOverlay.qml\nDesaturate 1.0 ../Qt5Compat/GraphicalEffects/Desaturate.qml\nDesaturate 1.15 ../Qt5Compat/GraphicalEffects/Desaturate.qml\nDropShadow 1.0 ../Qt5Compat/GraphicalEffects/DropShadow.qml\nDropShadow 1.15 ../Qt5Compat/GraphicalEffects/DropShadow.qml\nFastBlur 1.0 ../Qt5Compat/GraphicalEffects/FastBlur.qml\nFastBlur 1.15 ../Qt5Compat/GraphicalEffects/FastBlur.qml\nGaussianBlur 1.0 ../Qt5Compat/GraphicalEffects/GaussianBlur.qml\nGaussianBlur 1.15 ../Qt5Compat/GraphicalEffects/GaussianBlur.qml\nGlow 1.0 ../Qt5Compat/GraphicalEffects/Glow.qml\nGlow 1.15 ../Qt5Compat/GraphicalEffects/Glow.qml\nHueSaturation 1.0 ../Qt5Compat/GraphicalEffects/HueSaturation.qml\nHueSaturation 1.15 ../Qt5Compat/GraphicalEffects/HueSaturation.qml\nLinearGradient 1.0 ../Qt5Compat/GraphicalEffects/LinearGradient.qml\nLinearGradient 1.15 ../Qt5Compat/GraphicalEffects/LinearGradient.qml\nOpacityMask 1.0 ../Qt5Compat/GraphicalEffects/OpacityMask.qml\nOpacityMask 1.15 ../Qt5Compat/GraphicalEffects/OpacityMask.qml\nRadialGradient 1.0 ../Qt5Compat/GraphicalEffects/RadialGradient.qml\nRadialGradient 1.15 ../Qt5Compat/GraphicalEffects/RadialGradient.qml\nRectangularGlow 1.0 ../Qt5Compat/GraphicalEffects/RectangularGlow.qml\nRectangularGlow 1.15 ../Qt5Compat/GraphicalEffects/RectangularGlow.qml\nThresholdMask 1.0 ../Qt5Compat/GraphicalEffects/ThresholdMask.qml\nThresholdMask 1.15 ../Qt5Compat/GraphicalEffects/ThresholdMask.qml\n",
|
|
269
|
+
"QtQuick/VirtualKeyboard/InputPanel.qml": 'import QtQuick\nimport QtQuick.Controls\nimport QtQuick.Layouts\n\nItem {\n id: panel\n property bool active: false\n property bool externalLanguageSwitchEnabled: false\n signal externalLanguageSwitchRequested(var localeList, int currentIndex)\n\n implicitWidth: 640\n implicitHeight: 210\n visible: active\n\n readonly property var rows: [\n ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "\u232B"],\n ["q", "w", "e", "r", "t", "y", "u", "i", "o", "p"],\n ["a", "s", "d", "f", "g", "h", "j", "k", "l", "\u21B5"],\n ["\u21E7", "z", "x", "c", "v", "b", "n", "m", "Space"]\n ]\n property bool shifted: false\n\n function dispatchKey(label) {\n if (label === "\u21E7") {\n shifted = !shifted\n return\n }\n if (label === "\u232B") {\n const target = panel.Window.activeFocusItem\n if (target && typeof target.text === "string" && typeof target.cursorPosition === "number") {\n const pos = target.cursorPosition\n if (pos > 0) {\n target.text = target.text.slice(0, pos - 1) + target.text.slice(pos)\n target.cursorPosition = pos - 1\n }\n }\n return\n }\n if (label === "\u21B5") {\n const target = panel.Window.activeFocusItem\n if (target && typeof target.accepted === "function")\n target.accepted()\n return\n }\n const ch = label === "Space" ? " " : (shifted ? label.toUpperCase() : label)\n const target = panel.Window.activeFocusItem\n if (target && typeof target.text === "string" && typeof target.cursorPosition === "number") {\n const pos = target.cursorPosition\n target.text = target.text.slice(0, pos) + ch + target.text.slice(pos)\n target.cursorPosition = pos + ch.length\n }\n }\n\n Rectangle {\n anchors.fill: parent\n radius: 10\n color: "#e6181d25"\n border.color: "#384454"\n border.width: 1\n\n ColumnLayout {\n anchors.fill: parent\n anchors.margins: 10\n spacing: 6\n\n Repeater {\n model: panel.rows\n RowLayout {\n Layout.fillWidth: true\n Layout.fillHeight: true\n spacing: 6\n\n Repeater {\n model: modelData\n Button {\n Layout.fillWidth: true\n Layout.fillHeight: true\n Layout.preferredWidth: modelData === "Space" ? 160 : 40\n text: (modelData.length === 1 && panel.shifted) ? modelData.toUpperCase() : modelData\n focusPolicy: Qt.NoFocus\n onClicked: panel.dispatchKey(modelData)\n }\n }\n }\n }\n }\n }\n}\n',
|
|
270
|
+
"QtQuick/VirtualKeyboard/qmldir": "module QtQuick.VirtualKeyboard\n\nInputPanel 2.0 InputPanel.qml\nInputPanel 2.12 InputPanel.qml\nInputPanel 2.15 InputPanel.qml\nInputPanel 6.0 InputPanel.qml\n"
|
|
271
|
+
};
|
|
272
|
+
|
|
273
|
+
// src/qmlVersion.ts
|
|
274
|
+
var SUPPORTED_QML_VERSIONS = ["auto", "6.8", "2.15", "2.12", "2.0"];
|
|
275
|
+
var QT_QUICK_2_MODULES = /* @__PURE__ */ new Set([
|
|
276
|
+
"QtQuick",
|
|
277
|
+
"QtQuick.Window",
|
|
278
|
+
"QtQuick.Controls",
|
|
279
|
+
"QtQuick.Controls.Basic",
|
|
280
|
+
"QtQuick.VirtualKeyboard",
|
|
281
|
+
"QtQml",
|
|
282
|
+
"QtQml.Models",
|
|
283
|
+
"QtQml.WorkerScript"
|
|
284
|
+
]);
|
|
285
|
+
var QT_LAYOUT_MODULES = /* @__PURE__ */ new Set([
|
|
286
|
+
"QtQuick.Layouts",
|
|
287
|
+
"QtQuick.Shapes"
|
|
288
|
+
]);
|
|
289
|
+
var QT6_ONLY_OR_UNVERSIONED_MODULES = /* @__PURE__ */ new Set([
|
|
290
|
+
"QtQuick.Effects"
|
|
291
|
+
]);
|
|
292
|
+
var GRAPHICAL_EFFECT_MODULES = /* @__PURE__ */ new Set([
|
|
293
|
+
"QtGraphicalEffects",
|
|
294
|
+
"Qt5Compat.GraphicalEffects"
|
|
295
|
+
]);
|
|
296
|
+
var MULTIMEDIA_MODULES = /* @__PURE__ */ new Set([
|
|
297
|
+
"QtMultimedia"
|
|
298
|
+
]);
|
|
299
|
+
var IMPORT_LINE = /^(\s*import\s+)([A-Za-z_][\w.]*)(?:\s+(\d+(?:\.\d+)?))?(\s+as\s+[A-Za-z_]\w*)?(\s*;?\s*(?:\/\/.*)?)$/;
|
|
300
|
+
function parseTargetVersion(version) {
|
|
301
|
+
const trimmed = version.trim();
|
|
302
|
+
if (!trimmed || trimmed.toLowerCase() === "auto") return { mode: "auto" };
|
|
303
|
+
if (trimmed === "6" || /^6\.\d+$/.test(trimmed)) return { mode: "qt6" };
|
|
304
|
+
if (trimmed === "5" || /^5\.\d+$/.test(trimmed)) {
|
|
305
|
+
const minor = trimmed === "5" ? 15 : Number(trimmed.split(".")[1]);
|
|
306
|
+
const clamped = Math.max(0, Math.min(15, Number.isFinite(minor) ? minor : 15));
|
|
307
|
+
return { mode: "qtquick2", version: `2.${clamped}`, minor: clamped };
|
|
308
|
+
}
|
|
309
|
+
const qtQuickMatch = /^2\.(\d+)$/.exec(trimmed);
|
|
310
|
+
if (qtQuickMatch) {
|
|
311
|
+
const minor = Number(qtQuickMatch[1]);
|
|
312
|
+
return { mode: "qtquick2", version: trimmed, minor };
|
|
313
|
+
}
|
|
314
|
+
throw new RangeError(`Unsupported QML version "${version}". Use "auto", "6.8", "2.15", "2.12", or "2.0".`);
|
|
315
|
+
}
|
|
316
|
+
function normalizeQmlVersion(version) {
|
|
317
|
+
if (!version) return "auto";
|
|
318
|
+
const parsed = parseTargetVersion(version);
|
|
319
|
+
if (parsed.mode === "auto") return "auto";
|
|
320
|
+
if (parsed.mode === "qt6") return version.trim() === "6" ? "6" : version.trim();
|
|
321
|
+
return parsed.version;
|
|
322
|
+
}
|
|
323
|
+
function transformQmlImports(source, version) {
|
|
324
|
+
const target = parseTargetVersion(version);
|
|
325
|
+
if (target.mode === "auto") return source;
|
|
326
|
+
return source.split(/\r?\n/).map((line) => {
|
|
327
|
+
const match = IMPORT_LINE.exec(line);
|
|
328
|
+
if (!match) return line;
|
|
329
|
+
const [, prefix, moduleName, , alias = "", suffix = ""] = match;
|
|
330
|
+
if (!prefix || !moduleName) return line;
|
|
331
|
+
if (target.mode === "qt6") {
|
|
332
|
+
if (GRAPHICAL_EFFECT_MODULES.has(moduleName)) {
|
|
333
|
+
return `${prefix}Qt5Compat.GraphicalEffects${alias}${suffix}`;
|
|
334
|
+
}
|
|
335
|
+
if (QT_QUICK_2_MODULES.has(moduleName) || QT_LAYOUT_MODULES.has(moduleName) || QT6_ONLY_OR_UNVERSIONED_MODULES.has(moduleName) || MULTIMEDIA_MODULES.has(moduleName)) {
|
|
336
|
+
return `${prefix}${moduleName}${alias}${suffix}`;
|
|
337
|
+
}
|
|
338
|
+
return line;
|
|
339
|
+
}
|
|
340
|
+
if (QT_QUICK_2_MODULES.has(moduleName)) {
|
|
341
|
+
return `${prefix}${moduleName} ${target.version}${alias}${suffix}`;
|
|
342
|
+
}
|
|
343
|
+
if (QT_LAYOUT_MODULES.has(moduleName)) {
|
|
344
|
+
const layoutMinor = Math.min(target.minor, 15);
|
|
345
|
+
return `${prefix}${moduleName} 1.${layoutMinor}${alias}${suffix}`;
|
|
346
|
+
}
|
|
347
|
+
if (GRAPHICAL_EFFECT_MODULES.has(moduleName)) {
|
|
348
|
+
const effectMinor = target.minor >= 15 ? "1.15" : "1.0";
|
|
349
|
+
return `${prefix}${moduleName} ${effectMinor}${alias}${suffix}`;
|
|
350
|
+
}
|
|
351
|
+
if (MULTIMEDIA_MODULES.has(moduleName)) {
|
|
352
|
+
const mediaVersion = target.minor >= 15 ? "5.15" : target.minor >= 12 ? "5.12" : "5.0";
|
|
353
|
+
return `${prefix}${moduleName} ${mediaVersion}${alias}${suffix}`;
|
|
354
|
+
}
|
|
355
|
+
return line;
|
|
356
|
+
}).join("\n");
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
// src/sddmParser.ts
|
|
360
|
+
var decoder = new TextDecoder();
|
|
361
|
+
function parseIni(source) {
|
|
362
|
+
const sections = /* @__PURE__ */ Object.create(null);
|
|
363
|
+
let section = sections[""] = /* @__PURE__ */ Object.create(null);
|
|
364
|
+
for (const rawLine of source.replace(/^\uFEFF/, "").split(/\r\n?|\n/)) {
|
|
365
|
+
const line = rawLine.trim();
|
|
366
|
+
if (!line || line.startsWith("#") || line.startsWith(";")) continue;
|
|
367
|
+
const header = /^\[([^\]]+)\]\s*(?:[;#].*)?$/.exec(line);
|
|
368
|
+
if (header) {
|
|
369
|
+
const name = header[1].trim();
|
|
370
|
+
section = sections[name] ??= /* @__PURE__ */ Object.create(null);
|
|
371
|
+
continue;
|
|
372
|
+
}
|
|
373
|
+
const delimiter = line.indexOf("=");
|
|
374
|
+
if (delimiter < 1) continue;
|
|
375
|
+
const key = line.slice(0, delimiter).trim();
|
|
376
|
+
const value = line.slice(delimiter + 1).trim();
|
|
377
|
+
const quoted = /^(["'])(.*)\1\s*(?:[;#].*)?$/.exec(value);
|
|
378
|
+
section[key] = quoted ? quoted[2].replace(/\\([nrt\\'"])/g, (_, character) => ({ n: "\n", r: "\r", t: " " })[character] ?? character) : value;
|
|
379
|
+
}
|
|
380
|
+
return sections;
|
|
381
|
+
}
|
|
382
|
+
function parseThemeConfig(source) {
|
|
383
|
+
const ini = parseIni(source);
|
|
384
|
+
const config = Object.assign(/* @__PURE__ */ Object.create(null), ini[""]);
|
|
385
|
+
for (const [group, values] of Object.entries(ini)) {
|
|
386
|
+
if (!group) continue;
|
|
387
|
+
if (group.toLowerCase() === "general") Object.assign(config, values);
|
|
388
|
+
else for (const [key, value] of Object.entries(values)) config[`${group}/${key}`] = value;
|
|
389
|
+
}
|
|
390
|
+
return config;
|
|
391
|
+
}
|
|
392
|
+
function parseMetadata(source) {
|
|
393
|
+
const sections = parseIni(source);
|
|
394
|
+
const properties = Object.assign(
|
|
395
|
+
/* @__PURE__ */ Object.create(null),
|
|
396
|
+
sections[""],
|
|
397
|
+
...Object.entries(sections).filter(([group]) => group.toLowerCase() === "sddmgreetertheme").map(([, values]) => values)
|
|
398
|
+
);
|
|
399
|
+
const keys = Object.fromEntries(
|
|
400
|
+
Object.entries(properties).map(([key, value]) => [key.toLowerCase(), value])
|
|
401
|
+
);
|
|
402
|
+
return { mainScript: keys["mainscript"], configFile: keys["configfile"] };
|
|
403
|
+
}
|
|
404
|
+
function readText(files, path) {
|
|
405
|
+
const file = files[path];
|
|
406
|
+
return typeof file === "string" ? file : file ? decoder.decode(file) : "";
|
|
407
|
+
}
|
|
408
|
+
function directory(path) {
|
|
409
|
+
return path.slice(0, path.lastIndexOf("/") + 1);
|
|
410
|
+
}
|
|
411
|
+
function resolveTheme(files, entryFile) {
|
|
412
|
+
const paths = Object.keys(files);
|
|
413
|
+
const qmlFiles = paths.filter((path) => /\.qml$/i.test(path));
|
|
414
|
+
const metadataPaths = paths.filter((path) => path.split("/").at(-1) === "metadata.desktop");
|
|
415
|
+
let metadataPath;
|
|
416
|
+
let entry = entryFile === void 0 ? void 0 : normalizePath(entryFile);
|
|
417
|
+
if (entry !== void 0) {
|
|
418
|
+
metadataPath = metadataPaths.filter((path) => entry.startsWith(directory(path))).sort((a, b) => b.length - a.length)[0];
|
|
419
|
+
} else if (Object.hasOwn(files, "metadata.desktop")) {
|
|
420
|
+
metadataPath = "metadata.desktop";
|
|
421
|
+
} else if (Object.hasOwn(files, "Main.qml") || Object.hasOwn(files, "main.qml")) {
|
|
422
|
+
entry = Object.hasOwn(files, "Main.qml") ? "Main.qml" : "main.qml";
|
|
423
|
+
} else if (metadataPaths.length === 1) {
|
|
424
|
+
metadataPath = metadataPaths[0];
|
|
425
|
+
} else if (metadataPaths.length > 1) {
|
|
426
|
+
throw new Error("This input contains several themes. Select one theme folder or specify the entry file.");
|
|
427
|
+
}
|
|
428
|
+
const metadata = metadataPath ? parseMetadata(readText(files, metadataPath)) : {};
|
|
429
|
+
const metadataRoot = metadataPath ? directory(metadataPath) : "";
|
|
430
|
+
if (!entry && metadata.mainScript) entry = metadataRoot + normalizePath(metadata.mainScript);
|
|
431
|
+
if (!entry) {
|
|
432
|
+
const candidates = qmlFiles.filter((path) => path.startsWith(metadataRoot));
|
|
433
|
+
const mainFiles = candidates.filter((path) => path.split("/").at(-1)?.toLowerCase() === "main.qml");
|
|
434
|
+
entry = mainFiles.find((path) => directory(path) === metadataRoot) ?? (mainFiles.length === 1 ? mainFiles[0] : void 0) ?? (candidates.length === 1 ? candidates[0] : void 0);
|
|
435
|
+
}
|
|
436
|
+
if (!entry) throw new Error("Could not select a QML entry file. Include Main.qml or specify the entry file.");
|
|
437
|
+
if (!Object.hasOwn(files, entry) || !/\.qml$/i.test(entry)) {
|
|
438
|
+
throw new Error(`QML entry file "${entry}" was not found.`);
|
|
439
|
+
}
|
|
440
|
+
const root = metadataPath ? metadataRoot : directory(entry);
|
|
441
|
+
const declaredConfigPath = root + normalizePath(metadata.configFile || "theme.conf");
|
|
442
|
+
const configPath = Object.hasOwn(files, declaredConfigPath) ? declaredConfigPath : Object.hasOwn(files, `${root}theme.conf`) ? `${root}theme.conf` : paths.filter((path) => path.startsWith(root) && /\.conf$/i.test(path)).sort()[0] ?? declaredConfigPath;
|
|
443
|
+
const config = Object.assign(
|
|
444
|
+
parseThemeConfig(readText(files, configPath)),
|
|
445
|
+
parseThemeConfig(readText(files, `${configPath}.user`))
|
|
446
|
+
);
|
|
447
|
+
return { entryFile: entry, root, config };
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
// src/wasmLoader.ts
|
|
451
|
+
function loadScript(doc, url, signal) {
|
|
452
|
+
signal.throwIfAborted();
|
|
453
|
+
const script = doc.createElement("script");
|
|
454
|
+
script.src = url;
|
|
455
|
+
return new Promise((resolve, reject) => {
|
|
456
|
+
function finish(error) {
|
|
457
|
+
script.onload = null;
|
|
458
|
+
script.onerror = null;
|
|
459
|
+
signal.removeEventListener("abort", abort);
|
|
460
|
+
if (error === void 0) resolve();
|
|
461
|
+
else {
|
|
462
|
+
script.remove();
|
|
463
|
+
reject(error);
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
function abort() {
|
|
467
|
+
finish(signal.reason);
|
|
468
|
+
}
|
|
469
|
+
script.onload = () => finish();
|
|
470
|
+
script.onerror = () => finish(new Error(`Could not load Qt runtime script ${url}.`));
|
|
471
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
472
|
+
doc.head.append(script);
|
|
473
|
+
});
|
|
474
|
+
}
|
|
475
|
+
async function compileWasm(url, signal, progress) {
|
|
476
|
+
const response = await fetch(url, { signal });
|
|
477
|
+
if (!response.ok) throw new Error(`Could not download ${url} (HTTP ${response.status}).`);
|
|
478
|
+
if (!response.body) throw new Error(`The WebAssembly response for ${url} was empty.`);
|
|
479
|
+
const expected = Number(response.headers.get("content-length"));
|
|
480
|
+
let received = 0;
|
|
481
|
+
let lastPercent = 0;
|
|
482
|
+
const counted = response.body.pipeThrough(new TransformStream({
|
|
483
|
+
transform(chunk, controller) {
|
|
484
|
+
received += chunk.length;
|
|
485
|
+
if (expected > 0) {
|
|
486
|
+
const percent = Math.min(90, Math.floor(received / expected * 90));
|
|
487
|
+
if (percent > lastPercent) {
|
|
488
|
+
lastPercent = percent;
|
|
489
|
+
progress(percent);
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
controller.enqueue(chunk);
|
|
493
|
+
}
|
|
494
|
+
}));
|
|
495
|
+
const wasm = await WebAssembly.compileStreaming(new Response(counted, {
|
|
496
|
+
headers: { "Content-Type": "application/wasm" }
|
|
497
|
+
}));
|
|
498
|
+
if (lastPercent < 90) progress(90);
|
|
499
|
+
return wasm;
|
|
500
|
+
}
|
|
501
|
+
function untilAborted(promise, signal) {
|
|
502
|
+
return new Promise((resolve, reject) => {
|
|
503
|
+
const abort = () => reject(signal.reason);
|
|
504
|
+
promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
|
|
505
|
+
if (signal.aborted) abort();
|
|
506
|
+
else signal.addEventListener("abort", abort, { once: true });
|
|
507
|
+
});
|
|
508
|
+
}
|
|
509
|
+
async function loadWasmRuntime(frame, baseUrl, maxPixelRatio, signal, progress, onError) {
|
|
510
|
+
const doc = frame.contentDocument;
|
|
511
|
+
const win = frame.contentWindow;
|
|
512
|
+
const parentWindow = frame.ownerDocument.defaultView;
|
|
513
|
+
if (!doc || !win || !parentWindow) throw new Error("Could not open the Qt viewer frame.");
|
|
514
|
+
Object.defineProperty(win, "devicePixelRatio", {
|
|
515
|
+
configurable: true,
|
|
516
|
+
get: () => Math.min(parentWindow.devicePixelRatio || 1, maxPixelRatio)
|
|
517
|
+
});
|
|
518
|
+
const viewport = doc.createElement("meta");
|
|
519
|
+
viewport.name = "viewport";
|
|
520
|
+
viewport.content = "width=device-width, initial-scale=1";
|
|
521
|
+
doc.head.append(viewport);
|
|
522
|
+
const screen = doc.createElement("div");
|
|
523
|
+
Object.assign(doc.body.style, { margin: "0", overflow: "hidden", background: "#161b22" });
|
|
524
|
+
Object.assign(screen.style, { width: "100vw", height: "100vh", overflow: "hidden" });
|
|
525
|
+
doc.body.append(screen);
|
|
526
|
+
const base = new URL(baseUrl, frame.ownerDocument.baseURI);
|
|
527
|
+
if (!base.pathname.endsWith("/")) base.pathname += "/";
|
|
528
|
+
const locate = (name) => new URL(name, base).href;
|
|
529
|
+
progress(0);
|
|
530
|
+
const [wasm] = await Promise.all([
|
|
531
|
+
compileWasm(locate("qml_engine.wasm"), signal, progress),
|
|
532
|
+
loadScript(doc, locate("qtloader.js"), signal),
|
|
533
|
+
loadScript(doc, locate("qml_engine.js"), signal)
|
|
534
|
+
]);
|
|
535
|
+
signal.throwIfAborted();
|
|
536
|
+
const entryFunction = win.qml_engine_entry ?? win.createQtAppInstance;
|
|
537
|
+
if (typeof win.qtLoad !== "function" || typeof entryFunction !== "function") {
|
|
538
|
+
throw new Error(
|
|
539
|
+
`The Qt scripts did not expose the expected WebAssembly entry points (qtLoad=${typeof win.qtLoad}, qml_engine_entry=${typeof win.qml_engine_entry}, createQtAppInstance=${typeof win.createQtAppInstance}).`
|
|
540
|
+
);
|
|
541
|
+
}
|
|
542
|
+
progress(95);
|
|
543
|
+
signal.throwIfAborted();
|
|
544
|
+
const runtime = await untilAborted(win.qtLoad({
|
|
545
|
+
locateFile: locate,
|
|
546
|
+
qmlViewerWarning: (message) => queueMicrotask(() => {
|
|
547
|
+
if (!signal.aborted) onError(message);
|
|
548
|
+
}),
|
|
549
|
+
qt: {
|
|
550
|
+
// Emscripten val::isArray() checks `instanceof global("Array")` in the iframe's realm.
|
|
551
|
+
containerElements: win.Array.of(screen),
|
|
552
|
+
entryFunction,
|
|
553
|
+
module: win.Promise.resolve(wasm),
|
|
554
|
+
onExit: ({ crashed, code, text }) => {
|
|
555
|
+
if (!signal.aborted && (crashed || code)) onError(text || `The Qt runtime exited (${code ?? "unknown error"}).`);
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
}), signal);
|
|
559
|
+
if (!runtime.FS || typeof runtime.loadMainQml !== "function" || typeof runtime.updateSddmConfig !== "function" || typeof runtime.clearWorkspace !== "function" || typeof runtime.setRenderingEnabled !== "function" || typeof runtime.shutdown !== "function") {
|
|
560
|
+
throw new Error("The Qt runtime is missing the qml-web-viewer exports.");
|
|
561
|
+
}
|
|
562
|
+
return runtime;
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
// src/index.ts
|
|
566
|
+
var decoder2 = new TextDecoder();
|
|
567
|
+
var encoder2 = new TextEncoder();
|
|
568
|
+
var workspace = "/workspace";
|
|
569
|
+
var defaults = {
|
|
570
|
+
hostName: "qml-preview",
|
|
571
|
+
canPowerOff: true,
|
|
572
|
+
canReboot: true,
|
|
573
|
+
canSuspend: true,
|
|
574
|
+
canHibernate: false,
|
|
575
|
+
canHybridSleep: false,
|
|
576
|
+
canSwitchUser: false,
|
|
577
|
+
loginSucceeds: false,
|
|
578
|
+
users: [{ name: "demo", realName: "Demo User", homeDir: "/home/demo", uid: 1e3 }],
|
|
579
|
+
sessions: [
|
|
580
|
+
{ name: "Wayland", file: "wayland.desktop", type: "wayland" },
|
|
581
|
+
{ name: "X11", file: "x11.desktop", type: "x11" }
|
|
582
|
+
]
|
|
583
|
+
};
|
|
584
|
+
function messageOf(error) {
|
|
585
|
+
return error instanceof Error ? error.message : String(error);
|
|
586
|
+
}
|
|
587
|
+
function prepareFiles(files) {
|
|
588
|
+
const normalized = /* @__PURE__ */ Object.create(null);
|
|
589
|
+
const directories = /* @__PURE__ */ new Set();
|
|
590
|
+
for (const [name, data] of Object.entries(files)) {
|
|
591
|
+
const path = normalizePath(name);
|
|
592
|
+
if (Object.hasOwn(normalized, path)) throw new Error(`Duplicate theme file: ${path}`);
|
|
593
|
+
normalized[path] = data;
|
|
594
|
+
for (let slash = path.indexOf("/"); slash >= 0; slash = path.indexOf("/", slash + 1)) {
|
|
595
|
+
directories.add(path.slice(0, slash));
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
for (const directory2 of directories) {
|
|
599
|
+
if (Object.hasOwn(normalized, directory2)) throw new Error(`A theme path is both a file and a directory: ${directory2}`);
|
|
600
|
+
}
|
|
601
|
+
return { files: normalized, directories };
|
|
602
|
+
}
|
|
603
|
+
var QmlViewer = class {
|
|
604
|
+
constructor(options) {
|
|
605
|
+
this.options = options;
|
|
606
|
+
this.document = options.container.ownerDocument;
|
|
607
|
+
this.sddmConfig = options.sddmConfig;
|
|
608
|
+
this.qmlVersion = normalizeQmlVersion(options.qmlVersion);
|
|
609
|
+
this.maxPixelRatio = options.maxPixelRatio ?? 2;
|
|
610
|
+
if (!Number.isFinite(this.maxPixelRatio) || this.maxPixelRatio <= 0) {
|
|
611
|
+
throw new RangeError("maxPixelRatio must be a positive finite number.");
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
options;
|
|
615
|
+
maxPixelRatio;
|
|
616
|
+
document;
|
|
617
|
+
frame;
|
|
618
|
+
runtime;
|
|
619
|
+
initializing;
|
|
620
|
+
controller;
|
|
621
|
+
observer;
|
|
622
|
+
sddmConfig;
|
|
623
|
+
themeConfig;
|
|
624
|
+
qmlVersion;
|
|
625
|
+
generation = 0;
|
|
626
|
+
destroyed = false;
|
|
627
|
+
inViewport = true;
|
|
628
|
+
init() {
|
|
629
|
+
if (this.destroyed) return Promise.reject(new Error("This QmlViewer has been destroyed."));
|
|
630
|
+
return this.initializing ??= this.start();
|
|
631
|
+
}
|
|
632
|
+
async start() {
|
|
633
|
+
await Promise.resolve();
|
|
634
|
+
if (this.destroyed) throw new Error("This QmlViewer has been destroyed.");
|
|
635
|
+
const { container, wasmBaseUrl = "./wasm/" } = this.options;
|
|
636
|
+
const controller = this.controller = new AbortController();
|
|
637
|
+
const frame = this.frame = this.document.createElement("iframe");
|
|
638
|
+
frame.title = "Interactive QML preview";
|
|
639
|
+
Object.assign(frame.style, { display: "block", width: "100%", height: "100%", border: "0" });
|
|
640
|
+
try {
|
|
641
|
+
container.append(frame);
|
|
642
|
+
this.document.addEventListener("visibilitychange", this.syncVisibility);
|
|
643
|
+
const Observer = this.document.defaultView?.IntersectionObserver;
|
|
644
|
+
if (Observer) {
|
|
645
|
+
this.observer = new Observer(([entry]) => {
|
|
646
|
+
if (entry) this.inViewport = entry.isIntersecting && entry.intersectionRatio > 0;
|
|
647
|
+
this.syncVisibility();
|
|
648
|
+
});
|
|
649
|
+
this.observer.observe(frame);
|
|
650
|
+
}
|
|
651
|
+
const runtime = await loadWasmRuntime(
|
|
652
|
+
frame,
|
|
653
|
+
wasmBaseUrl,
|
|
654
|
+
this.maxPixelRatio,
|
|
655
|
+
controller.signal,
|
|
656
|
+
(percent) => this.options.onProgress?.(percent),
|
|
657
|
+
this.reportError
|
|
658
|
+
);
|
|
659
|
+
if (controller.signal.aborted) {
|
|
660
|
+
runtime.shutdown();
|
|
661
|
+
controller.signal.throwIfAborted();
|
|
662
|
+
}
|
|
663
|
+
this.runtime = runtime;
|
|
664
|
+
runtime.FS.mkdirTree(workspace);
|
|
665
|
+
runtime.updateSddmConfig(this.mockJson());
|
|
666
|
+
this.syncVisibility();
|
|
667
|
+
this.options.onProgress?.(100);
|
|
668
|
+
} catch (error) {
|
|
669
|
+
this.stop();
|
|
670
|
+
if (!this.destroyed) this.reportError(messageOf(error));
|
|
671
|
+
throw error;
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
async renderThemeFiles(input, entryOrOptions) {
|
|
675
|
+
const options = typeof entryOrOptions === "string" ? { entryFile: entryOrOptions } : entryOrOptions ?? {};
|
|
676
|
+
let targetVersion;
|
|
677
|
+
let prepared;
|
|
678
|
+
let theme;
|
|
679
|
+
try {
|
|
680
|
+
targetVersion = normalizeQmlVersion(options.qmlVersion ?? this.qmlVersion);
|
|
681
|
+
prepared = prepareFiles(input);
|
|
682
|
+
theme = resolveTheme(prepared.files, options.entryFile);
|
|
683
|
+
} catch (error2) {
|
|
684
|
+
this.reportError(messageOf(error2));
|
|
685
|
+
throw error2;
|
|
686
|
+
}
|
|
687
|
+
await this.init();
|
|
688
|
+
const runtime = this.runtime;
|
|
689
|
+
if (!runtime) throw new Error("This QmlViewer has been destroyed.");
|
|
690
|
+
const root = `${workspace}/theme-${++this.generation}`;
|
|
691
|
+
try {
|
|
692
|
+
const config = this.mockJson(theme.config);
|
|
693
|
+
if (!runtime.clearWorkspace()) throw new Error("Could not clear the Qt workspace.");
|
|
694
|
+
runtime.FS.mkdirTree(root);
|
|
695
|
+
for (const dir of prepared.directories) runtime.FS.mkdirTree(`${root}/${dir}`);
|
|
696
|
+
for (const [path, data] of Object.entries(prepared.files)) {
|
|
697
|
+
const content = targetVersion !== "auto" && /\.qml$/i.test(path) ? encoder2.encode(transformQmlImports(typeof data === "string" ? data : decoder2.decode(data), targetVersion)) : data;
|
|
698
|
+
runtime.FS.writeFile(`${root}/${path}`, content);
|
|
699
|
+
}
|
|
700
|
+
const importRoot = theme.root ? `${root}/${theme.root.slice(0, -1)}` : root;
|
|
701
|
+
const shimDirs = /* @__PURE__ */ new Set();
|
|
702
|
+
for (const [shimPath, shimSource] of Object.entries(FALLBACK_QML_SHIMS)) {
|
|
703
|
+
if (Object.hasOwn(prepared.files, `${theme.root}${shimPath}`)) continue;
|
|
704
|
+
const slash = shimPath.lastIndexOf("/");
|
|
705
|
+
if (slash > 0) {
|
|
706
|
+
const dir = `${importRoot}/${shimPath.slice(0, slash)}`;
|
|
707
|
+
if (!shimDirs.has(dir)) {
|
|
708
|
+
runtime.FS.mkdirTree(dir);
|
|
709
|
+
shimDirs.add(dir);
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
runtime.FS.writeFile(`${importRoot}/${shimPath}`, shimSource);
|
|
713
|
+
}
|
|
714
|
+
runtime.updateSddmConfig(config);
|
|
715
|
+
this.themeConfig = theme.config;
|
|
716
|
+
} catch (error2) {
|
|
717
|
+
runtime.clearWorkspace();
|
|
718
|
+
this.reportError(messageOf(error2));
|
|
719
|
+
throw error2;
|
|
720
|
+
}
|
|
721
|
+
const importDirectory = theme.root ? `${root}/${theme.root.slice(0, -1)}` : root;
|
|
722
|
+
const error = runtime.loadMainQml(`${root}/${theme.entryFile}`, importDirectory);
|
|
723
|
+
if (error) throw new Error(error);
|
|
724
|
+
}
|
|
725
|
+
renderCode(qmlSource, qmlVersion) {
|
|
726
|
+
return this.renderThemeFiles(fromCodeString(qmlSource), { entryFile: "Main.qml", qmlVersion });
|
|
727
|
+
}
|
|
728
|
+
/** Return the active default QML target version used when rendering. */
|
|
729
|
+
getQmlVersion() {
|
|
730
|
+
return this.qmlVersion;
|
|
731
|
+
}
|
|
732
|
+
/** Set the default QML target version for subsequent renders. */
|
|
733
|
+
setQmlVersion(version) {
|
|
734
|
+
if (this.destroyed) throw new Error("This QmlViewer has been destroyed.");
|
|
735
|
+
this.qmlVersion = normalizeQmlVersion(version);
|
|
736
|
+
}
|
|
737
|
+
/** Update the mock environment used by the current and subsequent previews. */
|
|
738
|
+
setSddmConfig(config) {
|
|
739
|
+
if (this.destroyed) throw new Error("This QmlViewer has been destroyed.");
|
|
740
|
+
this.sddmConfig = config;
|
|
741
|
+
this.runtime?.updateSddmConfig(this.mockJson(this.themeConfig));
|
|
742
|
+
}
|
|
743
|
+
destroy() {
|
|
744
|
+
if (this.destroyed) return;
|
|
745
|
+
this.destroyed = true;
|
|
746
|
+
this.stop();
|
|
747
|
+
}
|
|
748
|
+
mockJson(themeConfig) {
|
|
749
|
+
const mock = { ...defaults, ...this.sddmConfig };
|
|
750
|
+
return JSON.stringify({ ...mock, config: { ...themeConfig, ...mock.config } });
|
|
751
|
+
}
|
|
752
|
+
syncVisibility = () => {
|
|
753
|
+
this.runtime?.setRenderingEnabled(this.inViewport && this.document.visibilityState !== "hidden");
|
|
754
|
+
};
|
|
755
|
+
reportError = (message) => {
|
|
756
|
+
if (this.destroyed) return;
|
|
757
|
+
try {
|
|
758
|
+
this.options.onError?.(message);
|
|
759
|
+
} catch (error) {
|
|
760
|
+
console.error("QmlViewer onError callback failed", error);
|
|
761
|
+
}
|
|
762
|
+
};
|
|
763
|
+
stop() {
|
|
764
|
+
this.controller?.abort();
|
|
765
|
+
this.observer?.disconnect();
|
|
766
|
+
this.document.removeEventListener("visibilitychange", this.syncVisibility);
|
|
767
|
+
try {
|
|
768
|
+
this.runtime?.shutdown();
|
|
769
|
+
} catch (error) {
|
|
770
|
+
this.reportError(messageOf(error));
|
|
771
|
+
} finally {
|
|
772
|
+
this.frame?.remove();
|
|
773
|
+
this.frame = void 0;
|
|
774
|
+
this.runtime = void 0;
|
|
775
|
+
this.initializing = void 0;
|
|
776
|
+
this.controller = void 0;
|
|
777
|
+
this.observer = void 0;
|
|
778
|
+
this.inViewport = true;
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
};
|
|
782
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
783
|
+
0 && (module.exports = {
|
|
784
|
+
QmlViewer,
|
|
785
|
+
SUPPORTED_QML_VERSIONS,
|
|
786
|
+
fromCodeString,
|
|
787
|
+
fromFolderInput,
|
|
788
|
+
fromGitHubRepo,
|
|
789
|
+
fromSingleFile,
|
|
790
|
+
fromZipFile,
|
|
791
|
+
parseIni,
|
|
792
|
+
parseThemeConfig,
|
|
793
|
+
transformQmlImports
|
|
794
|
+
});
|