Commit 360b0079 authored by Chok's avatar Chok
Browse files

chok: 8.1.0 commit

parent bf07bdf3
Pipeline #22 failed with stages
repositories{
jcenter()
flatDir{
dirs 'libs'
}
}
dependencies {
implementation(name:'barcodescanner-release-2.1.5', ext:'aar')
}
android {
packagingOptions {
exclude 'META-INF/NOTICE'
exclude 'META-INF/LICENSE'
}
}
/**
* PhoneGap is available under *either* the terms of the modified BSD license *or* the
* MIT License (2008). See http://opensource.org/licenses/alphabetical for full text.
*
* Copyright (c) Matt Kane 2010
* Copyright (c) 2011, IBM Corporation
* Copyright (c) 2013, Maciej Nux Jaros
*/
package com.phonegap.plugins.barcodescanner;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.content.pm.PackageManager;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.PluginResult;
import org.apache.cordova.PermissionHelper;
import com.google.zxing.client.android.CaptureActivity;
import com.google.zxing.client.android.encode.EncodeActivity;
import com.google.zxing.client.android.Intents;
/**
* This calls out to the ZXing barcode reader and returns the result.
*
* @sa https://github.com/apache/cordova-android/blob/master/framework/src/org/apache/cordova/CordovaPlugin.java
*/
public class BarcodeScanner extends CordovaPlugin {
public static final int REQUEST_CODE = 0x0ba7c;
private static final String SCAN = "scan";
private static final String ENCODE = "encode";
private static final String CANCELLED = "cancelled";
private static final String FORMAT = "format";
private static final String TEXT = "text";
private static final String DATA = "data";
private static final String TYPE = "type";
private static final String PREFER_FRONTCAMERA = "preferFrontCamera";
private static final String ORIENTATION = "orientation";
private static final String SHOW_FLIP_CAMERA_BUTTON = "showFlipCameraButton";
private static final String RESULTDISPLAY_DURATION = "resultDisplayDuration";
private static final String SHOW_TORCH_BUTTON = "showTorchButton";
private static final String TORCH_ON = "torchOn";
private static final String SAVE_HISTORY = "saveHistory";
private static final String DISABLE_BEEP = "disableSuccessBeep";
private static final String FORMATS = "formats";
private static final String PROMPT = "prompt";
private static final String TEXT_TYPE = "TEXT_TYPE";
private static final String EMAIL_TYPE = "EMAIL_TYPE";
private static final String PHONE_TYPE = "PHONE_TYPE";
private static final String SMS_TYPE = "SMS_TYPE";
private static final String LOG_TAG = "BarcodeScanner";
private String [] permissions = { Manifest.permission.CAMERA };
private JSONArray requestArgs;
private CallbackContext callbackContext;
/**
* Constructor.
*/
public BarcodeScanner() {
}
/**
* Executes the request.
*
* This method is called from the WebView thread. To do a non-trivial amount of work, use:
* cordova.getThreadPool().execute(runnable);
*
* To run on the UI thread, use:
* cordova.getActivity().runOnUiThread(runnable);
*
* @param action The action to execute.
* @param args The exec() arguments.
* @param callbackContext The callback context used when calling back into JavaScript.
* @return Whether the action was valid.
*
* @sa https://github.com/apache/cordova-android/blob/master/framework/src/org/apache/cordova/CordovaPlugin.java
*/
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
this.callbackContext = callbackContext;
this.requestArgs = args;
if (action.equals(ENCODE)) {
JSONObject obj = args.optJSONObject(0);
if (obj != null) {
String type = obj.optString(TYPE);
String data = obj.optString(DATA);
// If the type is null then force the type to text
if (type == null) {
type = TEXT_TYPE;
}
if (data == null) {
callbackContext.error("User did not specify data to encode");
return true;
}
encode(type, data);
} else {
callbackContext.error("User did not specify data to encode");
return true;
}
} else if (action.equals(SCAN)) {
//android permission auto add
if(!hasPermisssion()) {
requestPermissions(0);
} else {
scan(args);
}
} else {
return false;
}
return true;
}
/**
* Starts an intent to scan and decode a barcode.
*/
public void scan(final JSONArray args) {
final CordovaPlugin that = this;
cordova.getThreadPool().execute(new Runnable() {
public void run() {
Intent intentScan = new Intent(that.cordova.getActivity().getBaseContext(), CaptureActivity.class);
intentScan.setAction(Intents.Scan.ACTION);
intentScan.addCategory(Intent.CATEGORY_DEFAULT);
// add config as intent extras
if (args.length() > 0) {
JSONObject obj;
JSONArray names;
String key;
Object value;
for (int i = 0; i < args.length(); i++) {
try {
obj = args.getJSONObject(i);
} catch (JSONException e) {
Log.i("CordovaLog", e.getLocalizedMessage());
continue;
}
names = obj.names();
for (int j = 0; j < names.length(); j++) {
try {
key = names.getString(j);
value = obj.get(key);
if (value instanceof Integer) {
intentScan.putExtra(key, (Integer) value);
} else if (value instanceof String) {
intentScan.putExtra(key, (String) value);
}
} catch (JSONException e) {
Log.i("CordovaLog", e.getLocalizedMessage());
}
}
intentScan.putExtra(Intents.Scan.CAMERA_ID, obj.optBoolean(PREFER_FRONTCAMERA, false) ? 1 : 0);
intentScan.putExtra(Intents.Scan.SHOW_FLIP_CAMERA_BUTTON, obj.optBoolean(SHOW_FLIP_CAMERA_BUTTON, false));
intentScan.putExtra(Intents.Scan.SHOW_TORCH_BUTTON, obj.optBoolean(SHOW_TORCH_BUTTON, false));
intentScan.putExtra(Intents.Scan.TORCH_ON, obj.optBoolean(TORCH_ON, false));
intentScan.putExtra(Intents.Scan.SAVE_HISTORY, obj.optBoolean(SAVE_HISTORY, false));
boolean beep = obj.optBoolean(DISABLE_BEEP, false);
intentScan.putExtra(Intents.Scan.BEEP_ON_SCAN, !beep);
if (obj.has(RESULTDISPLAY_DURATION)) {
intentScan.putExtra(Intents.Scan.RESULT_DISPLAY_DURATION_MS, "" + obj.optLong(RESULTDISPLAY_DURATION));
}
if (obj.has(FORMATS)) {
intentScan.putExtra(Intents.Scan.FORMATS, obj.optString(FORMATS));
}
if (obj.has(PROMPT)) {
intentScan.putExtra(Intents.Scan.PROMPT_MESSAGE, obj.optString(PROMPT));
}
if (obj.has(ORIENTATION)) {
intentScan.putExtra(Intents.Scan.ORIENTATION_LOCK, obj.optString(ORIENTATION));
}
}
}
// avoid calling other phonegap apps
intentScan.setPackage(that.cordova.getActivity().getApplicationContext().getPackageName());
that.cordova.startActivityForResult(that, intentScan, REQUEST_CODE);
}
});
}
/**
* Called when the barcode scanner intent completes.
*
* @param requestCode The request code originally supplied to startActivityForResult(),
* allowing you to identify who this result came from.
* @param resultCode The integer result code returned by the child activity through its setResult().
* @param intent An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
*/
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == REQUEST_CODE && this.callbackContext != null) {
if (resultCode == Activity.RESULT_OK) {
JSONObject obj = new JSONObject();
try {
obj.put(TEXT, intent.getStringExtra("SCAN_RESULT"));
obj.put(FORMAT, intent.getStringExtra("SCAN_RESULT_FORMAT"));
obj.put(CANCELLED, false);
} catch (JSONException e) {
Log.d(LOG_TAG, "This should never happen");
}
//this.success(new PluginResult(PluginResult.Status.OK, obj), this.callback);
this.callbackContext.success(obj);
} else if (resultCode == Activity.RESULT_CANCELED) {
JSONObject obj = new JSONObject();
try {
obj.put(TEXT, "");
obj.put(FORMAT, "");
obj.put(CANCELLED, true);
} catch (JSONException e) {
Log.d(LOG_TAG, "This should never happen");
}
//this.success(new PluginResult(PluginResult.Status.OK, obj), this.callback);
this.callbackContext.success(obj);
} else {
//this.error(new PluginResult(PluginResult.Status.ERROR), this.callback);
this.callbackContext.error("Unexpected error");
}
}
}
/**
* Initiates a barcode encode.
*
* @param type Endoiding type.
* @param data The data to encode in the bar code.
*/
public void encode(String type, String data) {
Intent intentEncode = new Intent(this.cordova.getActivity().getBaseContext(), EncodeActivity.class);
intentEncode.setAction(Intents.Encode.ACTION);
intentEncode.putExtra(Intents.Encode.TYPE, type);
intentEncode.putExtra(Intents.Encode.DATA, data);
// avoid calling other phonegap apps
intentEncode.setPackage(this.cordova.getActivity().getApplicationContext().getPackageName());
this.cordova.getActivity().startActivity(intentEncode);
}
/**
* check application's permissions
*/
public boolean hasPermisssion() {
for(String p : permissions)
{
if(!PermissionHelper.hasPermission(this, p))
{
return false;
}
}
return true;
}
/**
* We override this so that we can access the permissions variable, which no longer exists in
* the parent class, since we can't initialize it reliably in the constructor!
*
* @param requestCode The code to get request action
*/
public void requestPermissions(int requestCode)
{
PermissionHelper.requestPermissions(this, requestCode, permissions);
}
/**
* processes the result of permission request
*
* @param requestCode The code to get request action
* @param permissions The collection of permissions
* @param grantResults The result of grant
*/
public void onRequestPermissionResult(int requestCode, String[] permissions,
int[] grantResults) throws JSONException
{
PluginResult result;
for (int r : grantResults) {
if (r == PackageManager.PERMISSION_DENIED) {
Log.d(LOG_TAG, "Permission Denied!");
result = new PluginResult(PluginResult.Status.ILLEGAL_ACCESS_EXCEPTION);
this.callbackContext.sendPluginResult(result);
return;
}
}
switch(requestCode)
{
case 0:
scan(this.requestArgs);
break;
}
}
/**
* This plugin launches an external Activity when the camera is opened, so we
* need to implement the save/restore API in case the Activity gets killed
* by the OS while it's in the background.
*/
public void onRestoreStateForActivityResult(Bundle state, CallbackContext callbackContext) {
this.callbackContext = callbackContext;
}
}
function scan(success, error) {
var code = window.prompt("Enter barcode value (empty value will fire the error handler):");
if(code) {
var result = {
text:code,
format:"Fake",
cancelled:false
};
success(result);
} else {
error("No barcode");
}
}
function encode(type, data, success, errorCallback) {
success();
}
module.exports = {
scan: scan,
encode: encode
};
require("cordova/exec/proxy").add("BarcodeScanner",module.exports);
\ No newline at end of file
This diff is collapsed.
<?xml version="1.0" encoding="UTF-8"?>
<archive type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="8.00">
<data>
<int key="IBDocument.SystemTarget">1280</int>
<string key="IBDocument.SystemVersion">11C74</string>
<string key="IBDocument.InterfaceBuilderVersion">1938</string>
<string key="IBDocument.AppKitVersion">1138.23</string>
<string key="IBDocument.HIToolboxVersion">567.00</string>
<object class="NSMutableDictionary" key="IBDocument.PluginVersions">
<string key="NS.key.0">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
<string key="NS.object.0">933</string>
</object>
<array key="IBDocument.IntegratedClassDependencies">
<string>IBUINavigationItem</string>
<string>IBUIBarButtonItem</string>
<string>IBUIView</string>
<string>IBUINavigationBar</string>
<string>IBProxyObject</string>
</array>
<array key="IBDocument.PluginDependencies">
<string>com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
</array>
<object class="NSMutableDictionary" key="IBDocument.Metadata">
<string key="NS.key.0">PluginDependencyRecalculationVersion</string>
<integer value="1" key="NS.object.0"/>
</object>
<array class="NSMutableArray" key="IBDocument.RootObjects" id="1000">
<object class="IBProxyObject" id="372490531">
<string key="IBProxiedObjectIdentifier">IBFilesOwner</string>
<string key="targetRuntimeIdentifier">IBCocoaTouchFramework</string>
</object>
<object class="IBProxyObject" id="975951072">
<string key="IBProxiedObjectIdentifier">IBFirstResponder</string>
<string key="targetRuntimeIdentifier">IBCocoaTouchFramework</string>
</object>
<object class="IBUIView" id="191373211">
<reference key="NSNextResponder"/>
<int key="NSvFlags">274</int>
<array class="NSMutableArray" key="NSSubviews">
<object class="IBUINavigationBar" id="1064216609">
<reference key="NSNextResponder" ref="191373211"/>
<int key="NSvFlags">290</int>
<string key="NSFrameSize">{320, 44}</string>
<reference key="NSSuperview" ref="191373211"/>
<reference key="NSWindow"/>
<reference key="NSNextKeyView"/>
<string key="NSReuseIdentifierKey">_NS:260</string>
<string key="targetRuntimeIdentifier">IBCocoaTouchFramework</string>
<int key="IBUIBarStyle">1</int>
<array class="NSMutableArray" key="IBUIItems">
<object class="IBUINavigationItem" id="240626599">
<reference key="IBUINavigationBar" ref="1064216609"/>
<string key="IBUITitle">Barcode Scanner</string>
<object class="IBUIBarButtonItem" key="IBUILeftBarButtonItem" id="1053701234">
<string key="IBUITitle">Cancel</string>
<string key="targetRuntimeIdentifier">IBCocoaTouchFramework</string>
<int key="IBUIStyle">1</int>
<reference key="IBUINavigationItem" ref="240626599"/>
</object>
<string key="targetRuntimeIdentifier">IBCocoaTouchFramework</string>
</object>
</array>
</object>
</array>
<string key="NSFrameSize">{320, 460}</string>
<reference key="NSSuperview"/>
<reference key="NSWindow"/>
<reference key="NSNextKeyView" ref="1064216609"/>
<object class="NSColor" key="IBUIBackgroundColor">
<int key="NSColorSpace">3</int>
<bytes key="NSWhite">MSAwAA</bytes>
<object class="NSColorSpace" key="NSCustomColorSpace">
<int key="NSID">2</int>
</object>
</object>
<string key="targetRuntimeIdentifier">IBCocoaTouchFramework</string>
</object>
</array>
<object class="IBObjectContainer" key="IBDocument.Objects">
<array class="NSMutableArray" key="connectionRecords">
<object class="IBConnectionRecord">
<object class="IBCocoaTouchOutletConnection" key="connection">
<string key="label">overlayView</string>
<reference key="source" ref="372490531"/>
<reference key="destination" ref="191373211"/>
</object>
<int key="connectionID">9</int>
</object>
</array>
<object class="IBMutableOrderedSet" key="objectRecords">
<array key="orderedObjects">
<object class="IBObjectRecord">
<int key="objectID">0</int>
<array key="object" id="0"/>
<reference key="children" ref="1000"/>
<nil key="parent"/>
</object>
<object class="IBObjectRecord">
<int key="objectID">1</int>
<reference key="object" ref="191373211"/>
<array class="NSMutableArray" key="children">
<reference ref="1064216609"/>
</array>
<reference key="parent" ref="0"/>
</object>
<object class="IBObjectRecord">
<int key="objectID">-1</int>
<reference key="object" ref="372490531"/>
<reference key="parent" ref="0"/>
<string key="objectName">File's Owner</string>
</object>
<object class="IBObjectRecord">
<int key="objectID">-2</int>
<reference key="object" ref="975951072"/>
<reference key="parent" ref="0"/>
</object>
<object class="IBObjectRecord">
<int key="objectID">3</int>
<reference key="object" ref="1064216609"/>
<array class="NSMutableArray" key="children">
<reference ref="240626599"/>
</array>
<reference key="parent" ref="191373211"/>
</object>
<object class="IBObjectRecord">
<int key="objectID">4</int>
<reference key="object" ref="240626599"/>
<array class="NSMutableArray" key="children">
<reference ref="1053701234"/>
</array>
<reference key="parent" ref="1064216609"/>
</object>
<object class="IBObjectRecord">
<int key="objectID">10</int>
<reference key="object" ref="1053701234"/>
<reference key="parent" ref="240626599"/>
</object>
</array>
</object>
<dictionary class="NSMutableDictionary" key="flattenedProperties">
<string key="-1.CustomClassName">PGbcsViewController</string>
<string key="-1.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
<string key="-2.CustomClassName">UIResponder</string>
<string key="-2.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
<string key="1.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
<string key="10.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
<string key="3.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
<string key="4.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
</dictionary>
<dictionary class="NSMutableDictionary" key="unlocalizedProperties"/>
<nil key="activeLocalization"/>
<dictionary class="NSMutableDictionary" key="localizations"/>
<nil key="sourceID"/>
<int key="maxID">11</int>
</object>
<object class="IBClassDescriber" key="IBDocument.Classes">
<array class="NSMutableArray" key="referencedPartialClassDescriptions">
<object class="IBPartialClassDescription">
<string key="className">PGbcsViewController</string>
<string key="superclassName">UIViewController</string>
<object class="NSMutableDictionary" key="outlets">
<string key="NS.key.0">overlayView</string>
<string key="NS.object.0">UIView</string>
</object>
<object class="NSMutableDictionary" key="toOneOutletInfosByName">
<string key="NS.key.0">overlayView</string>
<object class="IBToOneOutletInfo" key="NS.object.0">
<string key="name">overlayView</string>
<string key="candidateClassName">UIView</string>
</object>
</object>
<object class="IBClassDescriptionSource" key="sourceIdentifier">
<string key="majorKey">IBProjectSource</string>
<string key="minorKey">./Classes/PGbcsViewController.h</string>
</object>
</object>
</array>
</object>
<int key="IBDocument.localizationMode">0</int>
<string key="IBDocument.TargetRuntimeIdentifier">IBCocoaTouchFramework</string>
<bool key="IBDocument.PluginDeclaredDependenciesTrackSystemTargetVersion">YES</bool>
<int key="IBDocument.defaultPropertyAccessControl">3</int>
<string key="IBCocoaTouchPluginVersion">933</string>
</data>
</archive>
This diff is collapsed.
.barcode-scanner-wrap {
margin: 0;
padding: 0;
outline: 0;
font-size: 100%;
vertical-align: baseline;
background: 0 0 black;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 9999999;
-ms-user-select: none;
}
.barcode-scanner-preview {
width: auto;
height: calc(100% - 70px);
position: absolute;
top: calc(50% - 35px);
left: 50%;
transform: translateX(-50%) translateY(-50%);
}
.barcode-scanner-mark {
position: absolute;
left: 0;
top: 50%;
width: 100%;
height: 3px;
background: red;
z-index: 9999999;
}
.barcode-scanner-app-bar {
height: 70px;
width: 100%;
padding-top: 10px;
z-index: 9999999;
text-align: center;
user-select: none;
position: absolute;
bottom: 0px;
}
.app-bar-action {
width: 40px;
height: 40px;
margin: 0 auto;
font-family: "Segoe UI Symbol";
color: white;
font-size: 12px;
text-transform: lowercase;
text-align: center;
cursor: default;
}
@media all and (orientation: landscape) {
.app-bar-action {
float: right;
margin-right: 20px;
}
}
.app-bar-action::before {
font-size: 28px;
display: block;
height: 36px;
}
.action-close::before {
content: "\E0C7";
/* close icon is larger so we re-size it to fit other icons */
font-size: 20px;
line-height: 40px;
}
.action-close:hover::before {
content: "\E0CA";
}
.no-zoom {
-ms-content-zooming: none;
}
.no-scroll {
overflow: hidden;
}
/*
* 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.
*/
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("WinRTBarcodeReader")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WinRTBarcodeReader")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: ComVisible(false)]
\ No newline at end of file
/*
* 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.
*/
namespace WinRTBarcodeReader
{
using System;
using System.Threading;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Graphics.Imaging;
using Windows.Media.Capture;
using Windows.Media.MediaProperties;
using Windows.Storage.Streams;
using ZXing;
/// <summary>
/// Defines the Reader type, that perform barcode search asynchronously.
/// </summary>
public sealed class Reader
{
#region Private fields
/// <summary>
/// Data reader, used to create bitmap array.
/// </summary>
private BarcodeReader barcodeReader;
/// <summary>
/// The cancel search flag.
/// </summary>
private CancellationTokenSource cancelSearch;
/// <summary>
/// MediaCapture instance, used for barcode search.
/// </summary>
private MediaCapture capture;
/// <summary>
/// Encoding properties for mediaCapture object.
/// </summary>
private ImageEncodingProperties encodingProps;
/// <summary>
/// Image stream for MediaCapture content.
/// </summary>
private InMemoryRandomAccessStream imageStream;
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="Reader" /> class.
/// </summary>
/// <param name="capture">MediaCapture instance.</param>
/// <param name="width">Capture frame width.</param>
/// <param name="height">Capture frame height.</param>
public void Init(MediaCapture capture, uint width, uint height)
{
this.capture = capture;
encodingProps = ImageEncodingProperties.CreateJpeg();
encodingProps.Width = width;
encodingProps.Height = height;
barcodeReader = new BarcodeReader {Options = {TryHarder = true}};
cancelSearch = new CancellationTokenSource();
}
#endregion
#region Public methods
/// <summary>
/// Perform async MediaCapture analysis and searches for barcode.
/// </summary>
/// <returns>IAsyncOperation object</returns>
public IAsyncOperation<Result> ReadCode()
{
return this.Read().AsAsyncOperation();
}
/// <summary>
/// Send signal to stop barcode search.
/// </summary>
public void Stop()
{
this.cancelSearch.Cancel();
}
#endregion
#region Private methods
/// <summary>
/// Perform async MediaCapture analysis and searches for barcode.
/// </summary>
/// <returns>Task object</returns>
private async Task<Result> Read()
{
Result result = null;
try
{
while (result == null)
{
result = await GetCameraImage(cancelSearch.Token);
}
}
catch (OperationCanceledException) {
Console.WriteLine("Barcode reading operation was canceled.");
}
return result;
}
/// <summary>
/// Perform image capture from mediaCapture object
/// </summary>
/// <param name="cancelToken">
/// The cancel Token.
/// </param>
/// <returns>
/// Decoded barcode string.
/// </returns>
private async Task<Result> GetCameraImage(CancellationToken cancelToken)
{
if (cancelToken.IsCancellationRequested)
{
throw new OperationCanceledException(cancelToken);
}
imageStream = new InMemoryRandomAccessStream();
await capture.CapturePhotoToStreamAsync(encodingProps, imageStream);
await imageStream.FlushAsync();
var decoder = await BitmapDecoder.CreateAsync(imageStream);
byte[] pixels =
(await
decoder.GetPixelDataAsync(BitmapPixelFormat.Rgba8,
BitmapAlphaMode.Ignore,
new BitmapTransform(),
ExifOrientationMode.IgnoreExifOrientation,
ColorManagementMode.DoNotColorManage)).DetachPixelData();
const BitmapFormat format = BitmapFormat.RGB32;
imageStream.Dispose();
var result =
await
Task.Run(
() => barcodeReader.Decode(pixels, (int) decoder.PixelWidth, (int) decoder.PixelHeight, format),
cancelToken);
return result;
}
#endregion
}
}
<?xml version="1.0" encoding="utf-8"?>
<!--
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.
-->
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectName>WinRTBarcodeReader</ProjectName>
<ProjectGuid>{01412F36-3781-4AF0-903C-ACEA7552C99C}</ProjectGuid>
<OutputType>winmdobj</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>WinRTBarcodeReader</RootNamespace>
<AssemblyName>WinRTBarcodeReader</AssemblyName>
<DefaultLanguage>en-US</DefaultLanguage>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{BC8A1FFA-BEE3-4634-8014-F334798102B3};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<TargetPlatformVersion>8.1</TargetPlatformVersion>
<MinimumVisualStudioVersion>12</MinimumVisualStudioVersion>
<TargetFrameworkVersion />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE;NETFX_CORE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugSymbols>false</DebugSymbols>
<DebugType>None</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE;NETFX_CORE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|ARM'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\ARM\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE;NETFX_CORE</DefineConstants>
<NoWarn>;2008</NoWarn>
<DebugType>full</DebugType>
<PlatformTarget>ARM</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|ARM'">
<OutputPath>bin\ARM\Release\</OutputPath>
<DefineConstants>TRACE;NETFX_CORE</DefineConstants>
<Optimize>true</Optimize>
<NoWarn>;2008</NoWarn>
<DebugSymbols>false</DebugSymbols>
<DebugType>None</DebugType>
<PlatformTarget>ARM</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x64\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE;NETFX_CORE</DefineConstants>
<NoWarn>;2008</NoWarn>
<DebugType>full</DebugType>
<PlatformTarget>x64</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
<OutputPath>bin\x64\Release\</OutputPath>
<DefineConstants>TRACE;NETFX_CORE</DefineConstants>
<Optimize>true</Optimize>
<NoWarn>;2008</NoWarn>
<DebugSymbols>false</DebugSymbols>
<DebugType>None</DebugType>
<PlatformTarget>x64</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x86\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE;NETFX_CORE</DefineConstants>
<NoWarn>;2008</NoWarn>
<DebugType>full</DebugType>
<PlatformTarget>x86</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">
<OutputPath>bin\x86\Release\</OutputPath>
<DefineConstants>TRACE;NETFX_CORE</DefineConstants>
<Optimize>true</Optimize>
<NoWarn>;2008</NoWarn>
<DebugSymbols>false</DebugSymbols>
<DebugType>None</DebugType>
<PlatformTarget>x86</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<ItemGroup>
<Compile Include="Reader.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<Reference Include="ZXing">
<HintPath>ZXing.winmd</HintPath>
</Reference>
</ItemGroup>
<PropertyGroup Condition=" '$(VisualStudioVersion)' == '' or '$(VisualStudioVersion)' &lt; '12.0' ">
<VisualStudioVersion>12.0</VisualStudioVersion>
</PropertyGroup>
<Import Project="$(MSBuildExtensionsPath)\Microsoft\WindowsXaml\v$(VisualStudioVersion)\Microsoft.Windows.UI.Xaml.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
\ No newline at end of file
/**
* cordova is available under the MIT License (2008).
* See http://opensource.org/licenses/alphabetical for full text.
*
* Copyright (c) Matt Kane 2010
* Copyright (c) 2011, IBM Corporation
* Copyright (c) 2012-2017, Adobe Systems
*/
var exec = cordova.require("cordova/exec");
var scanInProgress = false;
/**
* Constructor.
*
* @returns {BarcodeScanner}
*/
function BarcodeScanner() {
/**
* Encoding constants.
*
* @type Object
*/
this.Encode = {
TEXT_TYPE: "TEXT_TYPE",
EMAIL_TYPE: "EMAIL_TYPE",
PHONE_TYPE: "PHONE_TYPE",
SMS_TYPE: "SMS_TYPE"
// CONTACT_TYPE: "CONTACT_TYPE", // TODO: not implemented, requires passing a Bundle class from Javascript to Java
// LOCATION_TYPE: "LOCATION_TYPE" // TODO: not implemented, requires passing a Bundle class from Javascript to Java
};
/**
* Barcode format constants, defined in ZXing library.
*
* @type Object
*/
this.format = {
"all_1D": 61918,
"aztec": 1,
"codabar": 2,
"code_128": 16,
"code_39": 4,
"code_93": 8,
"data_MATRIX": 32,
"ean_13": 128,
"ean_8": 64,
"itf": 256,
"maxicode": 512,
"msi": 131072,
"pdf_417": 1024,
"plessey": 262144,
"qr_CODE": 2048,
"rss_14": 4096,
"rss_EXPANDED": 8192,
"upc_A": 16384,
"upc_E": 32768,
"upc_EAN_EXTENSION": 65536
};
}
/**
* Read code from scanner.
*
* @param {Function} successCallback This function will recieve a result object: {
* text : '12345-mock', // The code that was scanned.
* format : 'FORMAT_NAME', // Code format.
* cancelled : true/false, // Was canceled.
* }
* @param {Function} errorCallback
* @param config
*/
BarcodeScanner.prototype.scan = function (successCallback, errorCallback, config) {
if (config instanceof Array) {
// do nothing
} else {
if (typeof(config) === 'object') {
// string spaces between formats, ZXing does not like that
if (config.formats) {
config.formats = config.formats.replace(/\s+/g, '');
}
config = [ config ];
} else {
config = [];
}
}
if (errorCallback == null) {
errorCallback = function () {
};
}
if (typeof errorCallback != "function") {
console.log("BarcodeScanner.scan failure: failure parameter not a function");
return;
}
if (typeof successCallback != "function") {
console.log("BarcodeScanner.scan failure: success callback parameter must be a function");
return;
}
if (scanInProgress) {
errorCallback('Scan is already in progress');
return;
}
scanInProgress = true;
exec(
function(result) {
scanInProgress = false;
// work around bug in ZXing library
if (result.format === 'UPC_A' && result.text.length === 13) {
result.text = result.text.substring(1);
}
successCallback(result);
},
function(error) {
scanInProgress = false;
errorCallback(error);
},
'BarcodeScanner',
'scan',
config
);
};
//-------------------------------------------------------------------
BarcodeScanner.prototype.encode = function (type, data, successCallback, errorCallback, options) {
if (errorCallback == null) {
errorCallback = function () {
};
}
if (typeof errorCallback != "function") {
console.log("BarcodeScanner.encode failure: failure parameter not a function");
return;
}
if (typeof successCallback != "function") {
console.log("BarcodeScanner.encode failure: success callback parameter must be a function");
return;
}
exec(successCallback, errorCallback, 'BarcodeScanner', 'encode', [
{"type": type, "data": data, "options": options}
]);
};
var barcodeScanner = new BarcodeScanner();
module.exports = barcodeScanner;
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment