-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshell.html
376 lines (355 loc) · 19 KB
/
shell.html
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
<!DOCTYPE html>
<!--
SANE WebAssembly (sane-wasm)
Copyright (C) 2023 Gonçalo MB <me@goncalomb.com>
GNU GPLv2 + GNU LGPLv2.1
-->
<html lang="en">
<head>
<meta charset="utf-8">
<title>Test Page for SANE WebAssembly (sane-wasm)</title>
<style>
body {
font-family: sans-serif;
max-width: 950px;
margin: 0 auto;
}
table#options {
width: 100%;
border-collapse: collapse;
}
table#options tr td {
padding: 2px;
}
table#options tr:not(:last-child) td {
border-bottom: 1px solid #555;
}
table#options tr td:last-child {
overflow: hidden;
text-overflow: ellipsis;
max-width: 250px;
}
canvas {
border: 2px solid #555;
margin-bottom: 25px;
}
</style>
</head>
<body>
<header>
<h1>Test Page for SANE WebAssembly (sane-wasm)</h1>
<p>This project (sane-wasm) is a WebAssembly port of the <a href="http://sane-project.org/">SANE API</a> for in-browser scanning (USB scanners).</p>
</header>
<main>
<ul>
<li><strong>This is a test page.</strong> It's not designed for final image acquisition.</li>
<li>This project uses some of the latest web features, a modern browser is required.</li>
<li>Using this page requires understanding the <a href="https://sane-project.gitlab.io/standard/api.html#code-flow">SANE Code Flow</a> and the overall SANE library.</li>
<li>If you reload/leave the page without clearing the scanner state (e.g. closing the page while scanning) you might need to reset the device (i.e. reconnecting).</li>
<li>There are some safeguards in place, but it might still be possible to lock the browser window or the scanner.</li>
<li>Check the console for useful information.</li>
</ul>
<h2>Device Pairing (WebUSB)</h2>
<p>
<button id="btn-request-device">navigator.usb.requestDevice()</button>
<button id="btn-request-device-all">(no filters)</button>
</p>
<ul id="list-paired-devices"></ul>
<h2>LibSANE (sane-wasm)</h2>
<div id="sane-controls">Loading LibSANE (sane-wasm)...</div>
<h2>Scan Result</h2>
<canvas></canvas>
</main>
{{{ SCRIPT }}}
<script>
(function() {
// util function to build the dom
const tree = (data, parent = document.createDocumentFragment()) => {
(Array.isArray(data) ? data : [data]).filter(spec => spec).map(spec => {
if (!Array.isArray(spec)) return document.createTextNode(spec.toString());
const el = spec[0] ? document.createElement(spec[0]) : document.createDocumentFragment();
Object.keys(spec[1] || {}).forEach(attr => el[attr] = spec[1][attr]);
return tree(spec[2] || [], el);
}).forEach(el => parent.appendChild(el));
return parent;
};
// check support
if (!navigator || !navigator.usb) {
const main = document.querySelector("main");
main.innerHTML = "";
main.append(tree([
["p", null, [
["strong", null, "Browser not supported!"],
" Missing ",
["a", { href: "https://developer.mozilla.org/en-US/docs/Web/API/WebUSB_API" }, "WebUSB API"],
".",
]]
]));
return;
}
/* Device Pairing */
function updatePairedDevices() {
const listPairedDevices = document.querySelector("#list-paired-devices");
listPairedDevices.innerHTML = "";
navigator.usb.getDevices().then(devices => {
listPairedDevices.append(tree(devices.map(device => (
["li", null, `${device.productName} (${device.manufacturerName}) [${device.serialNumber}]`]
))));
});
}
function requestDevice(filters = false) {
navigator.usb.requestDevice({
filters: filters ? [
{ classCode: 0x07 }, // printer
] : []
}).finally(() => updatePairedDevices());
}
navigator.usb.addEventListener("connect", e => updatePairedDevices());
navigator.usb.addEventListener("disconnect", e => updatePairedDevices());
updatePairedDevices();
document.querySelector("#btn-request-device").addEventListener("click", e => requestDevice(true));
document.querySelector("#btn-request-device-all").addEventListener("click", e => requestDevice());
/* SANE */
const strstatusCache = {};
function callSANE(name, ...args) {
const res = LibSANE[name](...args);
return res instanceof Promise ? res : Promise.resolve(res);
}
// XXX: improve this
async function testScan() {
const state = await callSANE("sane_get_state");
if (!state.open) {
return;
}
console.log("TEST SCAN START");
await callSANE("sane_start");
const { parameters: params } = await callSANE("sane_get_parameters");;
const canvas = document.querySelector("canvas");
canvas.width = params.pixels_per_line;
canvas.height = params.lines;
const ctx = canvas.getContext("2d");
const reader = (callback) => new Promise((resolve, reject) => {
try {
const read = async () => {
const { status, data } = await callSANE("sane_read");
if (status == 5) { // EOF
resolve();
return;
}
if (status != 0) {
reject();
return;
}
if (data.length) {
callback(data);
}
setTimeout(read, data.length > 0 ? 10 : 200);
} // XXX: uncaught exception
setTimeout(read, 200);
} catch (e) {
reject(e);
}
});
let line = 0;
let rem = new Uint8ClampedArray();
reader(data => {
// TUDO: detect and support other frame types
const lc = Math.floor((rem.length + data.length) / (3 * params.pixels_per_line));
const idata = new Uint8ClampedArray(rem.length + data.length);
idata.set(rem, 0);
idata.set(data, rem.length);
if (lc) {
const odata = new Uint8ClampedArray(lc * params.pixels_per_line * 4);
var i = 0;
for (var j = 0; j < odata.length; i += 3, j += 4) {
odata.set(idata.subarray(i, i + 3), j);
odata[j + 3] = 0xff;
}
rem = idata.subarray(i);
ctx.putImageData(new ImageData(odata, params.pixels_per_line), 0, line);
line += lc;
} else {
rem = idata;
}
}).finally(() => {
callSANE("sane_cancel").finally(() => {
console.log("TEST SCAN STOP");
})
});
}
function populateDevices({ devices }) {
const listDevices = document.querySelector("#list-devices");
listDevices.innerHTML = "";
listDevices.append(tree(devices.map(device => (
["li", null, [
["button", { onclick: e => callSANE("sane_open", device.name).then(populateOptions) }, "LibSANE.sane_open(...)"], " ",
`${device.model} (${device.vendor}) [${device.name}] [${device.type}]`
]]
))));
}
async function populateOptions() {
const state = await callSANE("sane_get_state");
if (!state.open) {
return;
}
const auto = Symbol("auto");
async function createOptionControl(n, opt) {
if (opt.cap.INACTIVE) {
return null;
}
async function setValue(value) {
const { status, info } = value === auto ? await callSANE("sane_control_option_set_auto", n) : await callSANE("sane_control_option_set_value", n, value);
if (status == LibSANE.SANE_STATUS.GOOD) {
if (info.RELOAD_OPTIONS) {
populateOptions();
} else /*if (info.INEXACT)*/ { // always reload
await createOptionControl(n, opt);
}
}
}
function inputElement(value) {
function selectElement(constraint, number = false) {
return ["select", { onchange: e => setValue(number ? Number(e.target.value) : e.target.value) },
constraint.map(v => (
["option", { value: v, selected: v == value ? true : null }, v]
))
];
}
switch (opt.type) {
case LibSANE.SANE_TYPE.BOOL: return ["input", { type: "checkbox", onchange: e => setValue(e.target.checked), checked: value }];
case LibSANE.SANE_TYPE.INT:
case LibSANE.SANE_TYPE.FIXED:
if (opt.size == 1 && opt.constraint_type == LibSANE.SANE_CONSTRAINT.WORD_LIST) {
return selectElement(opt.constraint, true);
} else {
return ["input", { onchange: e => setValue(JSON.parse(e.target.value)), value: JSON.stringify(value) }]
}
case LibSANE.SANE_TYPE.STRING:
if (opt.constraint_type == LibSANE.SANE_CONSTRAINT.STRING_LIST) {
return selectElement(opt.constraint);
} else {
return ["input", { onchange: e => setValue(JSON.parse(e.target.value)), value: JSON.stringify(value) }]
}
case LibSANE.SANE_TYPE.BUTTON: return ["button", { onclick: e => setValue(null) }, opt.title];
case LibSANE.SANE_TYPE.GROUP: return null;
}
}
const result = [];
let value;
if (opt.cap.SOFT_DETECT) {
({ value } = await callSANE("sane_control_option_get_value", n));
result.push([null, null, JSON.stringify(value)]);
}
if (opt.cap.SOFT_SELECT) {
result.push(inputElement(value));
}
if (opt.cap.AUTOMATIC) {
result.push(["button", { onclick: e => setValue(auto) }, "AUTO"]);
}
const el = document.querySelector(`#option-${n}`);
el.innerHTML = "";
el.appendChild(tree(result));
}
const option_descriptors = [];
for (let opt, i = 0; opt || !i; i++) {
({ option_descriptor: opt } = await callSANE("sane_get_option_descriptor", i));
if (opt) {
option_descriptors.push(opt);
}
}
const options = document.querySelector("#options");
options.style.display = null;
options.innerHTML = "";
options.append(tree(option_descriptors.map((opt, n) => (
["tr", null, [
["td", null, `${n}`],
["td", null, [
["strong", null, `${opt.title}`],
` [name=${opt.name}] [type=${LibSANE.SANE_TYPE.asString(opt.type)}] [unit=${LibSANE.SANE_UNIT.asString(opt.unit)}] [size=${opt.size}]`, ["br"],
["abbr", { title: [
`cap=${JSON.stringify(opt.cap, null, 2)}`,
`constraint_type=${LibSANE.SANE_CONSTRAINT.asString(opt.constraint_type)}`,
`constraint=${JSON.stringify(opt.constraint, null, 2)}`,
].join("\n") }, "[cap=...] [constraint_type=...] [constraint=...]"], ["br"],
["small", null, opt.desc],
]],
["td", { id: `option-${n}` }]
]]
))));
let n = 0;
for (const opt of option_descriptors) {
await createOptionControl(n++, opt);
}
}
// reload with debug
function reloadWithDebug() {
const sane = {
debugSANE: true,
debugUSB: true,
debugFunctionCalls: true,
debugTestDevices: 5,
};
location.hash = JSON.stringify(sane);
location.reload();
}
// initialization
window.addEventListener("load", () => {
const sane = JSON.parse(decodeURIComponent(location.hash.substring(1)) || null) || {
debugFunctionCalls: true,
debugTestDevices: 3,
};
console.log("sane = ", sane);
window.LibSANE({ sane }).then(LibSANE => {
// publish module to window
window.LibSANE = LibSANE;
// initialize
const saneControls = document.querySelector("#sane-controls");
saneControls.innerHTML = "";
saneControls.append(tree([
["p", null, [
["button", { onclick: e => reloadWithDebug() }, "RELOAD WITH DEBUG (SANE+USB)"], " ",
["small", null, `${LibSANE.SANE_WASM_VERSION} (${LibSANE.SANE_WASM_COMMIT})`],
]],
["p", null, [
["small", null, [
["strong", null, `SANE backends (${LibSANE.SANE_WASM_BACKENDS.split(" ").length}): `],
LibSANE.SANE_WASM_BACKENDS
]],
]],
["h3", null, "Initialize"],
["p", null, [
["button", { onclick: e => callSANE("sane_get_state") }, "LibSANE.sane_get_state()"], " ",
["button", { onclick: e => callSANE("sane_init") }, "LibSANE.sane_init()"], " ",
["button", { onclick: e => callSANE("sane_exit") }, "LibSANE.sane_exit()"], " ",
["button", { onclick: e => callSANE("sane_strstatus", 999) }, "LibSANE.sane_strstatus(999)"], " ",
]],
["h3", null, "Devices"],
["p", null, [
["button", { onclick: e => callSANE("sane_get_devices").then(populateDevices) }, "LibSANE.sane_get_devices()"], " ",
]],
["ul", { id: "list-devices" }],
["p", null, [
["button", { onclick: e => callSANE("sane_get_option_descriptor", 0) }, "LibSANE.sane_get_option_descriptor(0)"], " ",
["button", { onclick: e => callSANE("sane_close") }, "LibSANE.sane_close()"], " ",
]],
["h3", null, "Options"],
["table", { id: "options", style: "display: none;" }],
["h3", null, "Scan"],
["p", null, [
["button", { onclick: e => callSANE("sane_get_parameters") }, "LibSANE.sane_get_parameters()"], " ",
]],
["p", null, [
["button", { onclick: e => callSANE("sane_start") }, "LibSANE.sane_start()"], " ",
["button", { onclick: e => callSANE("sane_read") }, "LibSANE.sane_read()"], " ",
["button", { onclick: e => callSANE("sane_cancel") }, "LibSANE.sane_cancel()"], " ",
]],
["p", null, [
["button", { onclick: e => testScan() }, "TEST SCAN"], " ",
]],
]));
});
});
})();
</script>
</body>
</html>