capacitor-plugin-scanbot-sdk
Version:
Scanbot Document and Barcode Scanner SDK for Capacitor
344 lines • 11.9 kB
JavaScript
import { ScanbotSDKInternal } from '../index';
import { mapPlainResult, PartiallyConstructible } from '../utils/utils';
import { BufferImageLoadOptions, EncodeImageOptions, ImageInfo, ImageRefPoolSnapshot, PathImageLoadOptions, SaveImageOptions, } from './ImageRefTypes';
class AutoReleasePool {
constructor() {
this.poolObjects = [];
}
releaseAll() {
for (const obj of this.poolObjects) {
if (!obj.isRetained()) {
obj.release();
}
}
}
addObject(obj) {
this.poolObjects.push(obj);
}
}
AutoReleasePool.globalPull = null;
AutoReleasePool.globalPullReferences = 0;
export async function autorelease(computation) {
if (AutoReleasePool.globalPull === null) {
AutoReleasePool.globalPull = new AutoReleasePool();
}
AutoReleasePool.globalPullReferences++;
const releasePoolRef = () => {
AutoReleasePool.globalPullReferences--;
if (AutoReleasePool.globalPullReferences === 0) {
AutoReleasePool.globalPull.releaseAll();
AutoReleasePool.globalPull = null;
}
};
try {
return await computation();
}
finally {
releasePoolRef();
}
}
export class AutoReleasable extends PartiallyConstructible {
constructor(uniqueId) {
super();
this.retained = false;
if (uniqueId) {
if (AutoReleasePool.globalPull === null) {
const errorMessage = 'Initializing an object that contains a ScanbotImage instance as REFERENCE must be wrapped inside an autorelease pool. For example:' +
'\n autorelease(()=>{' +
'\n const barcodeItem = new BarcodeItem(source);' +
'\n });';
throw new Error(errorMessage);
}
AutoReleasePool.globalPull.addObject(this);
}
}
isRetained() {
return this.retained;
}
retain() {
this.retained = true;
}
}
export class ImageRef extends AutoReleasable {
get buffer() {
return this._buffer;
}
constructor(uniqueId, buffer) {
super(uniqueId);
this.released = false;
this.uniqueId = uniqueId;
this._buffer = buffer;
}
static From(source) {
if (source.buffer) {
return new ImageRef(undefined, source.buffer);
}
else {
return ImageRef.deserialize(source);
}
}
static deserialize(serializedRef) {
if (!serializedRef.uniqueId) {
throw new Error('uniqueId must be present in serializedRef argument');
}
// The promise is intentionally not awaited here
ScanbotSDKInternal.imageRefDeserialize({
uniqueId: serializedRef.uniqueId,
})
.catch((error) => {
console.error(`Error while deserializing ImageRef with uniqueId ${serializedRef.uniqueId}: ${error}`);
})
.then((jsResultObject) => {
const success = mapPlainResult(jsResultObject);
if (!success) {
console.error(`Unsuccessful deserialization of ImageRef with uniqueId ${serializedRef.uniqueId}`);
}
});
return new ImageRef(serializedRef.uniqueId, undefined);
}
/**
* Converts the Image Ref to Json representation
*/
async serialize(imageSerializationMode) {
if (imageSerializationMode === 'BUFFER') {
const encodedImage = await this.encodeImage();
if (encodedImage) {
return { buffer: encodedImage };
}
else {
return null;
}
}
else {
this.throwErrorIfUniqueIdIsMissing();
this.throwErrorIfReleased();
// The promise is intentionally not awaited here
ScanbotSDKInternal.imageRefSerialize({ uniqueId: this.uniqueId })
.catch((error) => {
console.error(`Error while serializing ImageRef with uniqueId ${this.uniqueId}: ${error}`);
})
.then((jsResultObject) => {
const success = mapPlainResult(jsResultObject);
if (!success) {
console.error(`Unsuccessful serialization of ImageRef with uniqueId ${this.uniqueId}`);
}
});
return { uniqueId: this.uniqueId };
}
}
/**
* Creates ImageRef with uniqueId from the file uri to an image.
*/
static async fromImageFileUri(uri, options = new PathImageLoadOptions()) {
try {
const serializedImageRefUniqueId = await ScanbotSDKInternal.imageRefFromImageFileUri({
uri: uri,
options: options,
}).then((jsResultObject) => mapPlainResult(jsResultObject));
return ImageRef.deserialize({ uniqueId: serializedImageRefUniqueId });
}
catch (error) {
console.error(error);
return null;
}
}
/**
* Creates ImageRef with uniqueId from base64 encoded buffer, e.g. from jpeg.
*/
static async fromEncodedBuffer(buffer, options = new BufferImageLoadOptions()) {
try {
const serializedImageRefUniqueId = await ScanbotSDKInternal.imageRefFromEncodedBuffer({
buffer: buffer,
options: options,
}).then((jsResultObject) => mapPlainResult(jsResultObject));
return ImageRef.deserialize({ uniqueId: serializedImageRefUniqueId });
}
catch (error) {
console.error(error);
return null;
}
}
/**
* Creates a deep copy of the image.
* If uniqueId is not set or the image is already released, an exception will be thrown.
*/
async clone() {
this.throwErrorIfUniqueIdIsMissing();
this.throwErrorIfReleased();
try {
const serializedImageRefUniqueId = await ScanbotSDKInternal.imageRefClone({
uniqueId: this.uniqueId,
}).then((jsResultObject) => mapPlainResult(jsResultObject));
return ImageRef.deserialize({ uniqueId: serializedImageRefUniqueId });
}
catch (error) {
console.error(error);
return null;
}
}
/**
* Compresses ImageRef and stores it either on disk or in memory according to global settings.
* If uniqueId is not set or the image is already released, an exception will be thrown.
*/
async hibernate() {
this.throwErrorIfUniqueIdIsMissing();
this.throwErrorIfReleased();
try {
await ScanbotSDKInternal.imageRefHibernate({
uniqueId: this.uniqueId,
});
}
catch (error) {
console.error(error);
}
}
/**
* Releases native resources stored by the ref.
* If two different ImageRef objects have the same uniqueId both of them become cleared.
* If uniqueId is not set or the image is already released, an exception will be thrown.
*/
async clear() {
this.throwErrorIfUniqueIdIsMissing();
this.throwErrorIfReleased();
try {
await ScanbotSDKInternal.imageRefClear({ uniqueId: this.uniqueId });
}
catch (error) {
console.error(error);
}
}
/**
* Information about stored image as reference.
* If uniqueId is not set or the image is already released, an exception will be thrown.
*/
async info() {
this.throwErrorIfUniqueIdIsMissing();
this.throwErrorIfReleased();
try {
const imageInfo = await ScanbotSDKInternal.imageRefInfo({
uniqueId: this.uniqueId,
});
return new ImageInfo(imageInfo);
}
catch (error) {
console.error(error);
return null;
}
}
/**
* Saves the stored image with the given options.
* If uniqueId is not set or the image is already released, an exception will be thrown.
*/
async saveImage(path, options = new SaveImageOptions()) {
this.throwErrorIfUniqueIdIsMissing();
this.throwErrorIfReleased();
try {
return await ScanbotSDKInternal.imageRefSaveImage({
uniqueId: this.uniqueId,
path: path,
options: options,
}).then((jsResultObject) => mapPlainResult(jsResultObject));
}
catch (error) {
console.error(error);
return false;
}
}
/**
* Encode image.
*/
async encodeInPlace() {
if (this._buffer) {
// NO-OP, ImageRef is already converted.
}
else {
this.throwErrorIfUniqueIdIsMissing();
this.throwErrorIfReleased();
try {
const imageAsBuffer = await ScanbotSDKInternal.imageRefEncodeImage({
uniqueId: this.uniqueId,
options: new EncodeImageOptions(),
}).then((jsResultObject) => mapPlainResult(jsResultObject));
if (imageAsBuffer) {
this._buffer = imageAsBuffer;
}
}
catch (error) {
console.error(error);
}
}
}
/**
* Returns the stored image as base64.
*/
async encodeImage(options) {
if (this._buffer) {
if (options) {
throw new Error('EncodeImageOptions are not available when image is already encoded to base64');
}
return this._buffer;
}
else {
this.throwErrorIfUniqueIdIsMissing();
this.throwErrorIfReleased();
try {
return await ScanbotSDKInternal.imageRefEncodeImage({
uniqueId: this.uniqueId,
options: options !== null && options !== void 0 ? options : new EncodeImageOptions(),
}).then((jsResultObject) => mapPlainResult(jsResultObject));
}
catch (error) {
console.error(error);
return null;
}
}
}
/**
* Releases strong reference to the image.
* If uniqueId to the image is not set, an exception will be thrown.
*/
release() {
this.throwErrorIfUniqueIdIsMissing();
if (!this.released) {
// The promise is intentionally not awaited here
ScanbotSDKInternal.imageRefRelease({
uniqueId: this.uniqueId,
}).catch((error) => {
console.error(`Error while releasing ImageRef with uniqueId ${this.uniqueId}: ${error}`);
});
this.released = true;
}
}
/**
* Returns a snapshot of all alive ImageRefs.
* The snapshot contains a list of ImageRefs with information such as in-memory size.
*/
static async makeSnapshot() {
try {
const snapshot = await ScanbotSDKInternal.makeSnapshot();
return new ImageRefPoolSnapshot(snapshot);
}
catch (error) {
console.error(error);
return null;
}
}
/**
* Releases all alive images despite any existing references.
*/
static releaseAll() {
// The promise is intentionally not awaited here
ScanbotSDKInternal.imageRefReleaseAll().catch(() => { });
}
throwErrorIfUniqueIdIsMissing() {
if (!this.uniqueId) {
throw new Error('uniqueId is missing');
}
}
throwErrorIfReleased() {
if (this.released) {
throw new Error(`ImageRef with uniqueId ${this.uniqueId} has been released`);
}
}
}
//# sourceMappingURL=image.js.map