This repository has been archived by the owner on Aug 11, 2020. It is now read-only.
/
BarcodeScannerProxy.js
535 lines (450 loc) · 19 KB
/
BarcodeScannerProxy.js
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
/*
* Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
var urlutil = require('cordova/urlutil');
var CAMERA_STREAM_STATE_CHECK_RETRY_TIMEOUT = 200; // milliseconds
/**
* List of supported barcode formats from ZXing library. Used to return format
* name instead of number code as per plugin spec.
*
* @enum {String}
*/
var BARCODE_FORMAT = {
1: 'AZTEC',
2: 'CODABAR',
4: 'CODE_39',
8: 'CODE_93',
16: 'CODE_128',
32: 'DATA_MATRIX',
64: 'EAN_8',
128: 'EAN_13',
256: 'ITF',
512: 'MAXICODE',
1024: 'PDF_417',
2048: 'QR_CODE',
4096: 'RSS_14',
8192: 'RSS_EXPANDED',
16384: 'UPC_A',
32768: 'UPC_E',
61918: 'All_1D',
65536: 'UPC_EAN_EXTENSION',
131072: 'MSI',
262144: 'PLESSEY'
};
/**
* Detects the first appropriate camera located at the back panel of device. If
* there is no back cameras, returns the first available.
*
* @returns {Promise<String>} Camera id
*/
function findCamera() {
var Devices = Windows.Devices.Enumeration;
// Enumerate cameras and add them to the list
return Devices.DeviceInformation.findAllAsync(Devices.DeviceClass.videoCapture)
.then(function (cameras) {
if (!cameras || cameras.length === 0) {
throw new Error("No cameras found");
}
var backCameras = cameras.filter(function (camera) {
return camera.enclosureLocation && camera.enclosureLocation.panel === Devices.Panel.back;
});
// If there is back cameras, return the id of the first,
// otherwise take the first available device's id
return (backCameras[0] || cameras[0]).id;
});
}
/**
* @param {Windows.Graphics.Display.DisplayOrientations} displayOrientation
* @return {Number}
*/
function videoPreviewRotationLookup(displayOrientation, isMirrored) {
var degreesToRotate;
switch (displayOrientation) {
case Windows.Graphics.Display.DisplayOrientations.landscape:
degreesToRotate = 0;
break;
case Windows.Graphics.Display.DisplayOrientations.portrait:
if (isMirrored) {
degreesToRotate = 270;
} else {
degreesToRotate = 90;
}
break;
case Windows.Graphics.Display.DisplayOrientations.landscapeFlipped:
degreesToRotate = 180;
break;
case Windows.Graphics.Display.DisplayOrientations.portraitFlipped:
if (isMirrored) {
degreesToRotate = 90;
} else {
degreesToRotate = 270;
}
break;
default:
degreesToRotate = 0;
break;
}
return degreesToRotate;
}
/**
* The pure JS implementation of barcode reader from WinRTBarcodeReader.winmd.
* Works only on Windows 10 devices and more efficient than original one.
*
* @class {BarcodeReader}
*/
function BarcodeReader () {
this._promise = null;
this._cancelled = false;
}
/**
* Returns an instance of Barcode reader, depending on capabilities of Media
* Capture API
*
* @static
* @constructs {BarcodeReader}
*
* @param {MediaCapture} mediaCaptureInstance Instance of
* Windows.Media.Capture.MediaCapture class
*
* @return {BarcodeReader} BarcodeReader instance that could be used for
* scanning
*/
BarcodeReader.get = function (mediaCaptureInstance) {
if (mediaCaptureInstance.getPreviewFrameAsync && ZXing.BarcodeReader) {
return new BarcodeReader();
}
// If there is no corresponding API (Win8/8.1/Phone8.1) use old approach with WinMD library
return new WinRTBarcodeReader.Reader();
};
/**
* Initializes instance of reader.
*
* @param {MediaCapture} capture Instance of
* Windows.Media.Capture.MediaCapture class, used for acquiring images/ video
* stream for barcode scanner.
* @param {Number} width Video/image frame width
* @param {Number} height Video/image frame height
*/
BarcodeReader.prototype.init = function (capture, width, height) {
this._capture = capture;
this._width = width;
this._height = height;
this._zxingReader = new ZXing.BarcodeReader();
};
/**
* Starts barcode search routines asyncronously.
*
* @return {Promise<ScanResult>} barcode scan result or null if search
* cancelled.
*/
BarcodeReader.prototype.readCode = function () {
/**
* Grabs a frame from preview stream uning Win10-only API and tries to
* get a barcode using zxing reader provided. If there is no barcode
* found, returns null.
*/
function scanBarcodeAsync(mediaCapture, zxingReader, frameWidth, frameHeight) {
// Shortcuts for namespaces
var Imaging = Windows.Graphics.Imaging;
var Streams = Windows.Storage.Streams;
var frame = new Windows.Media.VideoFrame(Imaging.BitmapPixelFormat.bgra8, frameWidth, frameHeight);
return mediaCapture.getPreviewFrameAsync(frame)
.then(function (capturedFrame) {
// Copy captured frame to buffer for further deserialization
var bitmap = capturedFrame.softwareBitmap;
var rawBuffer = new Streams.Buffer(bitmap.pixelWidth * bitmap.pixelHeight * 4);
capturedFrame.softwareBitmap.copyToBuffer(rawBuffer);
capturedFrame.close();
// Get raw pixel data from buffer
var data = new Uint8Array(rawBuffer.length);
var dataReader = Streams.DataReader.fromBuffer(rawBuffer);
dataReader.readBytes(data);
dataReader.close();
return zxingReader.decode(data, frameWidth, frameHeight, ZXing.BitmapFormat.bgra32);
});
}
var self = this;
return scanBarcodeAsync(this._capture, this._zxingReader, this._width, this._height)
.then(function (result) {
if (self._cancelled)
return null;
return result || (self._promise = self.readCode());
});
};
/**
* Stops barcode search
*/
BarcodeReader.prototype.stop = function () {
this._cancelled = true;
};
module.exports = {
/**
* Scans image via device camera and retieves barcode from it.
* @param {function} success Success callback
* @param {function} fail Error callback
* @param {array} args Arguments array
*/
scan: function (success, fail, args) {
var capturePreview,
capturePreviewAlignmentMark,
captureCancelButton,
navigationButtonsDiv,
previewMirroring,
closeButton,
capture,
reader;
function updatePreviewForRotation(evt) {
if (!capture) {
return;
}
var ROTATION_KEY = "C380465D-2271-428C-9B83-ECEA3B4A85C1";
var displayInformation = (evt && evt.target) || Windows.Graphics.Display.DisplayInformation.getForCurrentView();
var currentOrientation = displayInformation.currentOrientation;
previewMirroring = capture.getPreviewMirroring();
// Lookup up the rotation degrees.
var rotDegree = videoPreviewRotationLookup(currentOrientation, previewMirroring);
// rotate the preview video
var videoEncodingProperties = capture.videoDeviceController.getMediaStreamProperties(Windows.Media.Capture.MediaStreamType.videoPreview);
videoEncodingProperties.properties.insert(ROTATION_KEY, rotDegree);
return capture.videoDeviceController.setMediaStreamPropertiesAsync(Windows.Media.Capture.MediaStreamType.videoPreview, videoEncodingProperties);
}
/**
* Creates a preview frame and necessary objects
*/
function createPreview() {
// Create fullscreen preview
var capturePreviewFrameStyle = document.createElement('link');
capturePreviewFrameStyle.rel = "stylesheet";
capturePreviewFrameStyle.type = "text/css";
capturePreviewFrameStyle.href = urlutil.makeAbsolute("/www/css/plugin-barcodeScanner.css");
document.head.appendChild(capturePreviewFrameStyle);
capturePreviewFrame = document.createElement('div');
capturePreviewFrame.className = "barcode-scanner-wrap";
capturePreview = document.createElement("video");
capturePreview.className = "barcode-scanner-preview";
capturePreview.addEventListener('click', function () {
focus();
});
capturePreviewAlignmentMark = document.createElement('div');
capturePreviewAlignmentMark.className = "barcode-scanner-mark";
navigationButtonsDiv = document.createElement("div");
navigationButtonsDiv.className = "barcode-scanner-app-bar";
navigationButtonsDiv.onclick = function (e) {
e.cancelBubble = true;
};
closeButton = document.createElement("div");
closeButton.innerText = "close";
closeButton.className = "app-bar-action action-close";
navigationButtonsDiv.appendChild(closeButton);
BarcodeReader.scanCancelled = false;
closeButton.addEventListener("click", cancelPreview, false);
document.addEventListener('backbutton', cancelPreview, false);
[capturePreview, capturePreviewAlignmentMark, navigationButtonsDiv].forEach(function (element) {
capturePreviewFrame.appendChild(element);
});
}
function focus(controller) {
var result = WinJS.Promise.wrap();
if (!capturePreview || capturePreview.paused) {
// If the preview is not yet playing, there is no sense in running focus
return result;
}
if (!controller) {
try {
controller = capture && capture.videoDeviceController;
} catch (err) {
console.log('Failed to access focus control for current camera: ' + err);
return result;
}
}
if (!controller.focusControl || !controller.focusControl.supported) {
console.log('Focus control for current camera is not supported');
return result;
}
return controller.focusControl.focusAsync();
}
function setupFocus(focusControl) {
function supportsFocusMode(mode) {
return focusControl.supportedFocusModes.indexOf(mode).returnValue;
}
if (!focusControl || !focusControl.supported || !focusControl.configure) {
return WinJS.Promise.wrap();
}
var FocusMode = Windows.Media.Devices.FocusMode;
var focusConfig = new Windows.Media.Devices.FocusSettings();
focusConfig.autoFocusRange = Windows.Media.Devices.AutoFocusRange.normal;
if (supportsFocusMode(FocusMode.continuous)) {
console.log("Device supports continuous focus mode");
focusConfig.mode = FocusMode.continuous;
} else if (supportsFocusMode(FocusMode.auto)) {
console.log("Device doesn\'t support continuous focus mode, switching to autofocus mode");
focusConfig.mode = FocusMode.auto;
}
focusControl.configure(focusConfig);
// Need to wrap this in setTimeout since continuous focus should start only after preview has started. See
// 'Remarks' at https://msdn.microsoft.com/en-us/library/windows/apps/windows.media.devices.focuscontrol.configure.aspx
return WinJS.Promise.timeout(200)
.then(function () {
return focusControl.focusAsync();
});
}
function disableZoomAndScroll() {
document.body.classList.add('no-zoom');
document.body.classList.add('no-scroll');
}
function enableZoomAndScroll() {
document.body.classList.remove('no-zoom');
document.body.classList.remove('no-scroll');
}
/**
* Starts stream transmission to preview frame and then run barcode search
*/
function startPreview() {
return findCamera()
.then(function (id) {
var captureSettings = new Windows.Media.Capture.MediaCaptureInitializationSettings();
captureSettings.streamingCaptureMode = Windows.Media.Capture.StreamingCaptureMode.video;
captureSettings.photoCaptureSource = Windows.Media.Capture.PhotoCaptureSource.videoPreview;
captureSettings.videoDeviceId = id;
capture = new Windows.Media.Capture.MediaCapture();
return capture.initializeAsync(captureSettings);
})
.then(function () {
var controller = capture.videoDeviceController;
var deviceProps = controller.getAvailableMediaStreamProperties(Windows.Media.Capture.MediaStreamType.videoRecord);
deviceProps = Array.prototype.slice.call(deviceProps);
deviceProps = deviceProps.filter(function (prop) {
// filter out streams with "unknown" subtype - causes errors on some devices
return prop.subtype !== "Unknown";
}).sort(function (propA, propB) {
// sort properties by resolution
return propB.width - propA.width;
});
var maxResProps = deviceProps[0];
return controller.setMediaStreamPropertiesAsync(Windows.Media.Capture.MediaStreamType.videoRecord, maxResProps)
.then(function () {
return {
capture: capture,
width: maxResProps.width,
height: maxResProps.height
};
});
})
.then(function (captureSettings) {
capturePreview.msZoom = true;
capturePreview.src = URL.createObjectURL(capture);
capturePreview.play();
// Insert preview frame and controls into page
document.body.appendChild(capturePreviewFrame);
disableZoomAndScroll();
return setupFocus(captureSettings.capture.videoDeviceController.focusControl)
.then(function () {
Windows.Graphics.Display.DisplayInformation.getForCurrentView().addEventListener("orientationchanged", updatePreviewForRotation, false);
return updatePreviewForRotation();
})
.then(function () {
if (!Windows.Media.Devices.CameraStreamState) {
// CameraStreamState is available starting with Windows 10 so skip this check for 8.1
// https://msdn.microsoft.com/en-us/library/windows/apps/windows.media.devices.camerastreamstate
return WinJS.Promise.as();
}
function checkCameraStreamState() {
if (capture.cameraStreamState !== Windows.Media.Devices.CameraStreamState.streaming) {
// Using loop as MediaCapture.CameraStreamStateChanged does not fire with CameraStreamState.streaming state.
return WinJS.Promise.timeout(CAMERA_STREAM_STATE_CHECK_RETRY_TIMEOUT)
.then(function () {
return checkCameraStreamState();
});
}
return WinJS.Promise.as();
}
// Ensure CameraStreamState is Streaming
return checkCameraStreamState();
})
.then(function () {
return captureSettings;
});
});
}
/**
* Removes preview frame and corresponding objects from window
*/
function destroyPreview() {
Windows.Graphics.Display.DisplayInformation.getForCurrentView().removeEventListener("orientationchanged", updatePreviewForRotation, false);
document.removeEventListener('backbutton', cancelPreview);
capturePreview.pause();
capturePreview.src = null;
if (capturePreviewFrame) {
document.body.removeChild(capturePreviewFrame);
}
reader && reader.stop();
reader = null;
capture && capture.stopRecordAsync();
capture = null;
enableZoomAndScroll();
}
/**
* Stops preview and then call success callback with cancelled=true
* See https://github.com/phonegap-build/BarcodeScanner#using-the-plugin
*/
function cancelPreview() {
BarcodeReader.scanCancelled = true;
reader && reader.stop();
}
function checkCancelled() {
if (BarcodeReader.scanCancelled) {
throw new Error('Canceled');
}
}
WinJS.Promise.wrap(createPreview())
.then(function () {
checkCancelled();
return startPreview();
})
.then(function (captureSettings) {
checkCancelled();
reader = BarcodeReader.get(captureSettings.capture);
reader.init(captureSettings.capture, captureSettings.width, captureSettings.height);
// Add a small timeout before capturing first frame otherwise
// we would get an 'Invalid state' error from 'getPreviewFrameAsync'
return WinJS.Promise.timeout(200)
.then(function () {
checkCancelled();
return reader.readCode();
});
})
.done(function (result) {
destroyPreview();
success({
text: result && result.text,
format: result && BARCODE_FORMAT[result.barcodeFormat],
cancelled: !result
});
}, function (error) {
destroyPreview();
if (error.message == 'Canceled') {
success({
cancelled: true
});
} else {
fail(error);
}
});
},
/**
* Encodes specified data into barcode
* @param {function} success Success callback
* @param {function} fail Error callback
* @param {array} args Arguments array
*/
encode: function (success, fail, args) {
fail("Not implemented yet");
}
};
require("cordova/exec/proxy").add("BarcodeScanner", module.exports);