text
stringlengths 9
39.2M
| dir
stringlengths 25
226
| lang
stringclasses 163
values | created_date
timestamp[s] | updated_date
timestamp[s] | repo_name
stringclasses 751
values | repo_full_name
stringclasses 752
values | star
int64 1.01k
183k
| len_tokens
int64 1
18.5M
|
|---|---|---|---|---|---|---|---|---|
```objective-c
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface ZXIGTIN : NSObject
@property(nonatomic, nonnull)NSString *country;
@property(nonatomic, nonnull)NSString *addOn;
@property(nonatomic, nonnull)NSString *price;
@property(nonatomic, nonnull)NSString *issueNumber;
- (instancetype)initWithCountry:(NSString *)country
addOn:(NSString *)addOn
price:(NSString *)price
issueNumber:(NSString *)issueNumber;
@end
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/wrappers/ios/Sources/Wrapper/Reader/ZXIGTIN.h
|
objective-c
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 99
|
```xml
//
#import "ZXIGTIN.h"
@implementation ZXIGTIN
- (instancetype)initWithCountry:(NSString *)country
addOn:(NSString *)addOn
price:(NSString *)price
issueNumber:(NSString *)issueNumber {
self = [super init];
self.country = country;
self.addOn = addOn;
self.price = price;
self.issueNumber = issueNumber;
return self;
}
@end
```
|
/content/code_sandbox/wrappers/ios/Sources/Wrapper/Reader/ZXIGTIN.mm
|
xml
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 92
|
```xml
//
#import "ZXIResult.h"
@implementation ZXIResult
- (instancetype)init:(NSString *)text
format:(ZXIFormat)format
bytes:(NSData *)bytes
position:(ZXIPosition *)position
orientation:(NSInteger)orientation
ecLevel:(NSString *)ecLevel
symbologyIdentifier:(NSString *)symbologyIdentifier
sequenceSize:(NSInteger)sequenceSize
sequenceIndex:(NSInteger)sequenceIndex
sequenceId:(NSString *)sequenceId
readerInit:(BOOL)readerInit
lineCount:(NSInteger)lineCount
gtin:(ZXIGTIN *)gtin {
self = [super init];
self.text = text;
self.format = format;
self.bytes = bytes;
self.position = position;
self.orientation = orientation;
self.ecLevel = ecLevel;
self.symbologyIdentifier = symbologyIdentifier;
self.sequenceSize = sequenceSize;
self.sequenceIndex = sequenceIndex;
self.sequenceId = sequenceId;
self.readerInit = readerInit;
self.lineCount = lineCount;
self.gtin = gtin;
return self;
}
@end
```
|
/content/code_sandbox/wrappers/ios/Sources/Wrapper/Reader/ZXIResult.mm
|
xml
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 242
|
```xml
//
#import "ZXIReaderOptions.h"
#import "ReaderOptions.h"
@interface ZXIReaderOptions()
@property(nonatomic) ZXing::ReaderOptions cppOpts;
@end
@implementation ZXIReaderOptions
-(instancetype)init {
self = [super init];
self.cppOpts = ZXing::ReaderOptions();
return self;
}
-(BOOL)tryHarder {
return self.cppOpts.tryHarder();
}
-(void)setTryHarder:(BOOL)tryHarder {
self.cppOpts = self.cppOpts.setTryHarder(tryHarder);
}
-(BOOL)tryRotate {
return self.cppOpts.tryRotate();
}
-(void)setTryRotate:(BOOL)tryRotate {
self.cppOpts = self.cppOpts.setTryRotate(tryRotate);
}
-(BOOL)tryInvert {
return self.cppOpts.tryInvert();
}
-(void)setTryInvert:(BOOL)tryInvert {
self.cppOpts = self.cppOpts.setTryInvert(tryInvert);
}
-(BOOL)tryDownscale {
return self.cppOpts.tryDownscale();
}
-(void)setTryDownscale:(BOOL)tryDownscale {
self.cppOpts = self.cppOpts.setTryDownscale(tryDownscale);
}
-(BOOL)isPure {
return self.cppOpts.isPure();
}
-(void)setIsPure:(BOOL)isPure {
self.cppOpts = self.cppOpts.setIsPure(isPure);
}
-(ZXIBinarizer)binarizer {
switch (self.cppOpts.binarizer()) {
default:
case ZXing::Binarizer::LocalAverage:
return ZXIBinarizer::ZXIBinarizerLocalAverage;
case ZXing::Binarizer::GlobalHistogram:
return ZXIBinarizer::ZXIBinarizerGlobalHistogram;
case ZXing::Binarizer::FixedThreshold:
return ZXIBinarizer::ZXIBinarizerFixedThreshold;
case ZXing::Binarizer::BoolCast:
return ZXIBinarizer::ZXIBinarizerBoolCast;
}
}
ZXing::Binarizer toNativeBinarizer(ZXIBinarizer binarizer) {
switch (binarizer) {
default:
case ZXIBinarizerLocalAverage:
return ZXing::Binarizer::LocalAverage;
case ZXIBinarizerGlobalHistogram:
return ZXing::Binarizer::GlobalHistogram;
case ZXIBinarizerFixedThreshold:
return ZXing::Binarizer::FixedThreshold;
case ZXIBinarizerBoolCast:
return ZXing::Binarizer::BoolCast;
}
}
-(void)setBinarizer:(ZXIBinarizer)binarizer {
self.cppOpts = self.cppOpts.setBinarizer(toNativeBinarizer(binarizer));
}
-(NSInteger)downscaleFactor {
return self.cppOpts.downscaleFactor();
}
-(void)setDownscaleFactor:(NSInteger)downscaleFactor {
self.cppOpts = self.cppOpts.setDownscaleFactor(downscaleFactor);
}
-(NSInteger)downscaleThreshold {
return self.cppOpts.downscaleThreshold();
}
-(void)setDownscaleThreshold:(NSInteger)downscaleThreshold {
self.cppOpts = self.cppOpts.setDownscaleThreshold(downscaleThreshold);
}
-(NSInteger)minLineCount {
return self.cppOpts.minLineCount();
}
-(void)setMinLineCount:(NSInteger)minLineCount {
self.cppOpts = self.cppOpts.setMinLineCount(minLineCount);
}
- (NSInteger)maxNumberOfSymbols {
return self.cppOpts.maxNumberOfSymbols();
}
-(void)setMaxNumberOfSymbols:(NSInteger)maxNumberOfSymbols {
self.cppOpts = self.cppOpts.setMaxNumberOfSymbols(maxNumberOfSymbols);
}
-(BOOL)tryCode39ExtendedMode {
return self.cppOpts.tryCode39ExtendedMode();
}
-(void)setTryCode39ExtendedMode:(BOOL)tryCode39ExtendedMode {
self.cppOpts = self.cppOpts.setTryCode39ExtendedMode(tryCode39ExtendedMode);
}
-(BOOL)validateCode39CheckSum {
return self.cppOpts.validateCode39CheckSum();
}
-(void)setValidateCode39CheckSum:(BOOL)validateCode39CheckSum {
self.cppOpts = self.cppOpts.setValidateCode39CheckSum(validateCode39CheckSum);
}
-(BOOL)validateITFCheckSum {
return self.cppOpts.validateITFCheckSum();
}
-(void)setValidateITFCheckSum:(BOOL)validateITFCheckSum {
self.cppOpts = self.cppOpts.setValidateITFCheckSum(validateITFCheckSum);
}
-(BOOL)returnCodabarStartEnd {
return self.cppOpts.returnCodabarStartEnd();
}
-(void)setReturnCodabarStartEnd:(BOOL)returnCodabarStartEnd {
self.cppOpts = self.cppOpts.setReturnCodabarStartEnd(returnCodabarStartEnd);
}
-(BOOL)returnErrors {
return self.cppOpts.returnErrors();
}
-(void)setReturnErrors:(BOOL)returnErrors {
self.cppOpts = self.cppOpts.setReturnErrors(returnErrors);
}
-(ZXIEanAddOnSymbol)eanAddOnSymbol {
switch (self.cppOpts.eanAddOnSymbol()) {
default:
case ZXing::EanAddOnSymbol::Ignore:
return ZXIEanAddOnSymbol::ZXIEanAddOnSymbolIgnore;
case ZXing::EanAddOnSymbol::Read:
return ZXIEanAddOnSymbol::ZXIEanAddOnSymbolRead;
case ZXing::EanAddOnSymbol::Require:
return ZXIEanAddOnSymbol::ZXIEanAddOnSymbolRequire;
}
}
ZXing::EanAddOnSymbol toNativeEanAddOnSymbol(ZXIEanAddOnSymbol eanAddOnSymbol) {
switch (eanAddOnSymbol) {
default:
case ZXIEanAddOnSymbolIgnore:
return ZXing::EanAddOnSymbol::Ignore;
case ZXIEanAddOnSymbolRead:
return ZXing::EanAddOnSymbol::Read;
case ZXIEanAddOnSymbolRequire:
return ZXing::EanAddOnSymbol::Require;
}
}
-(void)setEanAddOnSymbol:(ZXIEanAddOnSymbol)eanAddOnSymbol {
self.cppOpts = self.cppOpts.setEanAddOnSymbol(toNativeEanAddOnSymbol(eanAddOnSymbol));
}
-(ZXITextMode)textMode {
switch (self.cppOpts.textMode()) {
default:
case ZXing::TextMode::Plain:
return ZXITextMode::ZXITextModePlain;
case ZXing::TextMode::ECI:
return ZXITextMode::ZXITextModeECI;
case ZXing::TextMode::HRI:
return ZXITextMode::ZXITextModeHRI;
case ZXing::TextMode::Hex:
return ZXITextMode::ZXITextModeHex;
case ZXing::TextMode::Escaped:
return ZXITextMode::ZXITextModeEscaped;
}
}
ZXing::TextMode toNativeTextMode(ZXITextMode mode) {
switch (mode) {
default:
case ZXITextModePlain:
return ZXing::TextMode::Plain;
case ZXITextModeECI:
return ZXing::TextMode::ECI;
case ZXITextModeHRI:
return ZXing::TextMode::HRI;
case ZXITextModeHex:
return ZXing::TextMode::Hex;
case ZXITextModeEscaped:
return ZXing::TextMode::Escaped;
}
}
-(void)setTextMode:(ZXITextMode)textMode {
self.cppOpts = self.cppOpts.setTextMode(toNativeTextMode(textMode));
}
@end
```
|
/content/code_sandbox/wrappers/ios/Sources/Wrapper/Reader/ZXIReaderOptions.mm
|
xml
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 1,634
|
```xml
//
#import "ZXIBarcodeReader.h"
#import "ReadBarcode.h"
#import "ImageView.h"
#import "Barcode.h"
#import "GTIN.h"
#import "ZXIFormatHelper.h"
#import "ZXIPosition+Helper.h"
#import "ZXIErrors.h"
using namespace ZXing;
NSString *stringToNSString(const std::string &text) {
return [[NSString alloc]initWithBytes:text.data() length:text.size() encoding:NSUTF8StringEncoding];
}
ZXIGTIN *getGTIN(const Result &result) {
try {
auto country = GTIN::LookupCountryIdentifier(result.text(TextMode::Plain), result.format());
auto addOn = GTIN::EanAddOn(result);
return country.empty()
? nullptr
: [[ZXIGTIN alloc]initWithCountry:stringToNSString(country)
addOn:stringToNSString(addOn)
price:stringToNSString(GTIN::Price(addOn))
issueNumber:stringToNSString(GTIN::IssueNr(addOn))];
} catch (std::exception e) {
// Because invalid GTIN data can lead to exceptions, in which case
// we don't want to discard the whole result.
return nullptr;
}
}
@interface ZXIReaderOptions()
@property(nonatomic) ZXing::ReaderOptions cppOpts;
@end
@interface ZXIBarcodeReader()
@property (nonatomic, strong) CIContext* ciContext;
@end
@implementation ZXIBarcodeReader
- (instancetype)init {
return [self initWithOptions: [[ZXIReaderOptions alloc] init]];
}
- (instancetype)initWithOptions:(ZXIReaderOptions*)options{
self = [super init];
self.ciContext = [[CIContext alloc] initWithOptions:@{kCIContextWorkingColorSpace: [NSNull new]}];
self.options = options;
return self;
}
- (NSArray<ZXIResult *> *)readCVPixelBuffer:(nonnull CVPixelBufferRef)pixelBuffer
error:(NSError *__autoreleasing _Nullable *)error {
OSType pixelFormat = CVPixelBufferGetPixelFormatType(pixelBuffer);
// We tried to work with all luminance based formats listed in kCVPixelFormatType
// but only the following ones seem to be supported on iOS.
switch (pixelFormat) {
case kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange:
case kCVPixelFormatType_420YpCbCr8BiPlanarFullRange:
NSInteger cols = CVPixelBufferGetWidth(pixelBuffer);
NSInteger rows = CVPixelBufferGetHeight(pixelBuffer);
NSInteger bytesPerRow = CVPixelBufferGetBytesPerRowOfPlane(pixelBuffer, 0);
CVPixelBufferLockBaseAddress(pixelBuffer, kCVPixelBufferLock_ReadOnly);
const uint8_t * bytes = static_cast<const uint8_t *>(CVPixelBufferGetBaseAddressOfPlane(pixelBuffer, 0));
ImageView imageView = ImageView(
static_cast<const uint8_t *>(bytes),
static_cast<int>(cols),
static_cast<int>(rows),
ImageFormat::Lum,
static_cast<int>(bytesPerRow),
0);
NSArray* results = [self readImageView:imageView error:error];
CVPixelBufferUnlockBaseAddress(pixelBuffer, kCVPixelBufferLock_ReadOnly);
return results;
}
// If given pixel format is not a supported type with a luminance channel we just use the
// default method
return [self readCIImage:[[CIImage alloc] initWithCVImageBuffer:pixelBuffer] error:error];
}
- (NSArray<ZXIResult *> *)readCIImage:(nonnull CIImage *)image
error:(NSError *__autoreleasing _Nullable *)error {
CGImageRef cgImage = [self.ciContext createCGImage:image fromRect:image.extent];
auto results = [self readCGImage:cgImage error:error];
CGImageRelease(cgImage);
return results;
}
- (NSArray<ZXIResult *> *)readCGImage:(nonnull CGImageRef)image
error:(NSError *__autoreleasing _Nullable *)error {
CGFloat cols = CGImageGetWidth(image);
CGFloat rows = CGImageGetHeight(image);
NSMutableData *data = [NSMutableData dataWithLength: cols * rows];
CGColorSpaceRef colorSpace = CGColorSpaceCreateWithName(kCGColorSpaceGenericGray);
CGContextRef contextRef = CGBitmapContextCreate(data.mutableBytes,// Pointer to backing data
cols, // Width of bitmap
rows, // Height of bitmap
8, // Bits per component
cols, // Bytes per row
colorSpace, // Colorspace
kCGBitmapByteOrderDefault); // Bitmap info flags
CGColorSpaceRelease(colorSpace);
CGContextDrawImage(contextRef, CGRectMake(0, 0, cols, rows), image);
CGContextRelease(contextRef);
ImageView imageView = ImageView(
static_cast<const uint8_t *>(data.bytes),
static_cast<int>(cols),
static_cast<int>(rows),
ImageFormat::Lum);
return [self readImageView:imageView error:error];
}
- (NSArray<ZXIResult*> *)readImageView:(ImageView)imageView
error:(NSError *__autoreleasing _Nullable *)error {
try {
Barcodes results = ReadBarcodes(imageView, self.options.cppOpts);
NSMutableArray* zxiResults = [NSMutableArray array];
for (auto result: results) {
[zxiResults addObject:
[[ZXIResult alloc] init:stringToNSString(result.text())
format:ZXIFormatFromBarcodeFormat(result.format())
bytes:[[NSData alloc] initWithBytes:result.bytes().data() length:result.bytes().size()]
position:[[ZXIPosition alloc]initWithPosition: result.position()]
orientation:result.orientation()
ecLevel:stringToNSString(result.ecLevel())
symbologyIdentifier:stringToNSString(result.symbologyIdentifier())
sequenceSize:result.sequenceSize()
sequenceIndex:result.sequenceIndex()
sequenceId:stringToNSString(result.sequenceId())
readerInit:result.readerInit()
lineCount:result.lineCount()
gtin:getGTIN(result)]
];
}
return zxiResults;
} catch(std::exception &e) {
SetNSError(error, ZXIReaderError, e.what());
return nil;
}
}
@end
```
|
/content/code_sandbox/wrappers/ios/Sources/Wrapper/Reader/ZXIBarcodeReader.mm
|
xml
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 1,335
|
```objective-c
//
#import <Foundation/Foundation.h>
#import "ZXIFormat.h"
NS_ASSUME_NONNULL_BEGIN
extern const int AZTEC_ERROR_CORRECTION_0;
extern const int AZTEC_ERROR_CORRECTION_12;
extern const int AZTEC_ERROR_CORRECTION_25;
extern const int AZTEC_ERROR_CORRECTION_37;
extern const int AZTEC_ERROR_CORRECTION_50;
extern const int AZTEC_ERROR_CORRECTION_62;
extern const int AZTEC_ERROR_CORRECTION_75;
extern const int AZTEC_ERROR_CORRECTION_87;
extern const int AZTEC_ERROR_CORRECTION_100;
extern const int QR_ERROR_CORRECTION_LOW;
extern const int QR_ERROR_CORRECTION_MEDIUM;
extern const int QR_ERROR_CORRECTION_QUARTILE;
extern const int QR_ERROR_CORRECTION_HIGH;
extern const int PDF417_ERROR_CORRECTION_0;
extern const int PDF417_ERROR_CORRECTION_1;
extern const int PDF417_ERROR_CORRECTION_2;
extern const int PDF417_ERROR_CORRECTION_3;
extern const int PDF417_ERROR_CORRECTION_4;
extern const int PDF417_ERROR_CORRECTION_5;
extern const int PDF417_ERROR_CORRECTION_6;
extern const int PDF417_ERROR_CORRECTION_7;
extern const int PDF417_ERROR_CORRECTION_8;
@interface ZXIWriterOptions : NSObject
@property(nonatomic) ZXIFormat format;
@property(nonatomic) int width;
@property(nonatomic) int height;
@property(nonatomic) int ecLevel;
@property(nonatomic) int margin;
- (instancetype)initWithFormat:(ZXIFormat)format;
- (instancetype)initWithFormat:(ZXIFormat)format
width:(int)width
height:(int)height
ecLevel:(int)ecLevel
margin:(int)margin;
@end
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/wrappers/ios/Sources/Wrapper/Writer/ZXIWriterOptions.h
|
objective-c
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 389
|
```objective-c
//
#import <Foundation/Foundation.h>
#import "ZXIWriterOptions.h"
NS_ASSUME_NONNULL_BEGIN
@interface ZXIBarcodeWriter : NSObject
@property(nonatomic, strong) ZXIWriterOptions *options;
-(instancetype)initWithOptions:(ZXIWriterOptions*)options;
-(nullable CGImageRef)writeString:(NSString *)contents
error:(NSError *__autoreleasing _Nullable *)error;
-(nullable CGImageRef)writeData:(NSData *)data
error:(NSError *__autoreleasing _Nullable *)error;
@end
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/wrappers/ios/Sources/Wrapper/Writer/ZXIBarcodeWriter.h
|
objective-c
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 115
|
```xml
//
#import "ZXIWriterOptions.h"
const int AZTEC_ERROR_CORRECTION_0 = 0;
const int AZTEC_ERROR_CORRECTION_12 = 1;
const int AZTEC_ERROR_CORRECTION_25 = 2;
const int AZTEC_ERROR_CORRECTION_37 = 3;
const int AZTEC_ERROR_CORRECTION_50 = 4;
const int AZTEC_ERROR_CORRECTION_62 = 5;
const int AZTEC_ERROR_CORRECTION_75 = 6;
const int AZTEC_ERROR_CORRECTION_87 = 7;
const int AZTEC_ERROR_CORRECTION_100 = 8;
const int QR_ERROR_CORRECTION_LOW = 2;
const int QR_ERROR_CORRECTION_MEDIUM = 4;
const int QR_ERROR_CORRECTION_QUARTILE = 6;
const int QR_ERROR_CORRECTION_HIGH = 8;
const int PDF417_ERROR_CORRECTION_0 = 0;
const int PDF417_ERROR_CORRECTION_1 = 1;
const int PDF417_ERROR_CORRECTION_2 = 2;
const int PDF417_ERROR_CORRECTION_3 = 3;
const int PDF417_ERROR_CORRECTION_4 = 4;
const int PDF417_ERROR_CORRECTION_5 = 5;
const int PDF417_ERROR_CORRECTION_6 = 6;
const int PDF417_ERROR_CORRECTION_7 = 7;
const int PDF417_ERROR_CORRECTION_8 = 8;
@implementation ZXIWriterOptions
- (instancetype)initWithFormat:(ZXIFormat)format {
self = [super init];
self.format = format;
self.width = 0;
self.height = 0;
self.ecLevel = -1;
self.margin = -1;
return self;
}
- (instancetype)initWithFormat:(ZXIFormat)format
width:(int)width
height:(int)height
ecLevel:(int)ecLevel
margin:(int)margin {
self = [super init];
self.format = format;
self.width = width;
self.height = height;
self.ecLevel = ecLevel;
self.margin = margin;
return self;
}
@end
```
|
/content/code_sandbox/wrappers/ios/Sources/Wrapper/Writer/ZXIWriterOptions.mm
|
xml
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 474
|
```xml
//
#import <CoreGraphics/CoreGraphics.h>
#import "ZXIBarcodeWriter.h"
#import "ZXIWriterOptions.h"
#import "MultiFormatWriter.h"
#import "BitMatrix.h"
#import "BitMatrixIO.h"
#import "ZXIFormatHelper.h"
#import "ZXIErrors.h"
#import <iostream>
using namespace ZXing;
std::wstring NSStringToStringW(NSString* str) {
NSData* asData = [str dataUsingEncoding:CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingUTF32LE)];
return std::wstring((wchar_t*)[asData bytes], [asData length] /
sizeof(wchar_t));
}
std::wstring NSDataToStringW(NSData *data) {
std::wstring s;
const unsigned char *bytes = (const unsigned char *) [data bytes];
size_t len = [data length];
for (int i = 0; i < len; ++i) {
s.push_back(bytes[i]);
}
return s;
}
@implementation ZXIBarcodeWriter
- (instancetype)init {
return [self initWithOptions: [[ZXIWriterOptions alloc] init]];
}
- (instancetype)initWithOptions:(ZXIWriterOptions*)options{
self = [super init];
self.options = options;
return self;
}
-(CGImageRef)writeData:(NSData *)data
error:(NSError *__autoreleasing _Nullable *)error {
return [self encode: NSDataToStringW(data)
encoding: CharacterSet::BINARY
format: self.options.format
width: self.options.width
height: self.options.height
margin: self.options.margin
ecLevel: self.options.ecLevel
error: error];
}
-(CGImageRef)writeString:(NSString *)contents
error:(NSError *__autoreleasing _Nullable *)error {
return [self encode: NSStringToStringW(contents)
encoding: CharacterSet::UTF8
format: self.options.format
width: self.options.width
height: self.options.height
margin: self.options.margin
ecLevel: self.options.ecLevel
error: error];
}
-(CGImageRef)encode:(std::wstring)content
encoding:(CharacterSet)encoding
format:(ZXIFormat)format
width:(int)width
height:(int)height
margin:(int)margin
ecLevel:(int)ecLevel
error:(NSError *__autoreleasing _Nullable *)error {
MultiFormatWriter writer { BarcodeFormatFromZXIFormat(format) };
writer.setEncoding(encoding);
writer.setMargin(margin);
writer.setEccLevel(ecLevel);
// Catch exception for invalid formats
try {
BitMatrix bitMatrix = writer.encode(content, width, height);
return [self inflate:&bitMatrix];
} catch(std::exception &e) {
SetNSError(error, ZXIWriterError, e.what());
return nil;
}
}
-(CGImageRef)inflate:(BitMatrix *)bitMatrix {
int realWidth = bitMatrix->width();
int realHeight = bitMatrix->height();
#ifdef DEBUG
std::cout << ToString(*bitMatrix, 'X', ' ', false, false);
#endif
NSMutableData *resultAsNSData = [[NSMutableData alloc] initWithLength:realWidth * realHeight];
size_t index = 0;
uint8_t *bytes = (uint8_t*)resultAsNSData.mutableBytes;
for (int y = 0; y < realHeight; ++y) {
for (int x = 0; x < realWidth; ++x) {
bytes[index] = bitMatrix->get(x, y) ? 0 : 255;
++index;
}
}
CGColorSpaceRef colorSpace = CGColorSpaceCreateWithName(kCGColorSpaceGenericGray);
return CGImageCreate(realWidth,
realHeight,
8,
8,
realWidth,
colorSpace,
kCGBitmapByteOrderDefault,
CGDataProviderCreateWithCFData((CFDataRef)resultAsNSData),
NULL,
YES,
kCGRenderingIntentDefault);
}
@end
```
|
/content/code_sandbox/wrappers/ios/Sources/Wrapper/Writer/ZXIBarcodeWriter.mm
|
xml
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 879
|
```unknown
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:">
</FileRef>
</Workspace>
```
|
/content/code_sandbox/wrappers/ios/demo/demo.xcodeproj/project.xcworkspace/contents.xcworkspacedata
|
unknown
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 46
|
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "path_to_url">
<plist version="1.0">
<dict>
<key>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>
```
|
/content/code_sandbox/wrappers/ios/demo/demo.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist
|
xml
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 72
|
```unknown
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1340"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "388BF024283CC49D005CE271"
BuildableName = "demo.app"
BlueprintName = "demo"
ReferencedContainer = "container:demo.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "388BF024283CC49D005CE271"
BuildableName = "demo.app"
BlueprintName = "demo"
ReferencedContainer = "container:demo.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<AdditionalOptions>
<AdditionalOption
key = "MallocStackLogging"
value = ""
isEnabled = "YES">
</AdditionalOption>
<AdditionalOption
key = "PrefersMallocStackLoggingLite"
value = ""
isEnabled = "YES">
</AdditionalOption>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "388BF024283CC49D005CE271"
BuildableName = "demo.app"
BlueprintName = "demo"
ReferencedContainer = "container:demo.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
```
|
/content/code_sandbox/wrappers/ios/demo/demo.xcodeproj/xcshareddata/xcschemes/demo.xcscheme
|
unknown
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 710
|
```swift
//
// demo
//
//
import UIKit
import ZXingCpp
class WriteViewController: UIViewController {
@IBOutlet fileprivate var imageView: UIImageView!
// MARK: - Actions
@IBAction func textFieldChanged(_ sender: UITextField) {
let options = ZXIWriterOptions(format: .QR_CODE, width: 200, height: 200, ecLevel: QR_ERROR_CORRECTION_LOW, margin: -1)
guard let text = sender.text,
let image = try? ZXIBarcodeWriter(options: options).write(text)
else {
return
}
imageView.image = UIImage(cgImage: image.takeRetainedValue())
}
}
```
|
/content/code_sandbox/wrappers/ios/demo/demo/WriteViewController.swift
|
swift
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 141
|
```swift
// demo
//
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
```
|
/content/code_sandbox/wrappers/ios/demo/demo/SceneDelegate.swift
|
swift
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 452
|
```swift
// demo
//
//
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
```
|
/content/code_sandbox/wrappers/ios/demo/demo/AppDelegate.swift
|
swift
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 241
|
```swift
// demo
//
//
import UIKit
import AVFoundation
import ZXingCpp
class ViewController: UIViewController {
let captureSession = AVCaptureSession()
lazy var preview = AVCaptureVideoPreviewLayer(session: captureSession)
let queue = DispatchQueue(label: "com.zxing_cpp.ios.demo")
let reader = ZXIBarcodeReader()
let zxingLock = DispatchSemaphore(value: 1)
override func viewDidLoad() {
super.viewDidLoad()
self.preview.videoGravity = AVLayerVideoGravity.resizeAspectFill
self.preview.frame = self.view.layer.bounds
self.view.layer.addSublayer(self.preview)
// setup camera session
self.requestAccess {
let discoverySession = AVCaptureDevice.DiscoverySession(
deviceTypes: [
.builtInTripleCamera,
.builtInDualWideCamera,
.builtInDualCamera,
.builtInWideAngleCamera
],
mediaType: .video,
position: .back)
let device = discoverySession.devices.first!
let cameraInput = try! AVCaptureDeviceInput(device: device)
self.captureSession.beginConfiguration()
self.captureSession.addInput(cameraInput)
let videoDataOutput = AVCaptureVideoDataOutput()
videoDataOutput.setSampleBufferDelegate(self, queue: self.queue)
videoDataOutput.videoSettings = [kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange]
videoDataOutput.alwaysDiscardsLateVideoFrames = true
self.captureSession.addOutput(videoDataOutput)
self.captureSession.commitConfiguration()
DispatchQueue.global(qos: .background).async {
self.captureSession.startRunning()
}
}
}
}
extension ViewController {
func requestAccess(_ completion: @escaping () -> Void) {
if AVCaptureDevice.authorizationStatus(for: AVMediaType.video) == .notDetermined {
AVCaptureDevice.requestAccess(for: .video) { _ in
completion()
}
} else {
completion()
}
}
}
extension ViewController: AVCaptureVideoDataOutputSampleBufferDelegate {
func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
guard self.zxingLock.wait(timeout: DispatchTime.now()) == .success else {
// The previous image is still processed, drop the new one to prevent too much pressure
return
}
let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)!
if let result = try? reader.read(imageBuffer).first {
print("Found barcode of format", result.format.rawValue, "with text", result.text)
}
self.zxingLock.signal()
}
}
```
|
/content/code_sandbox/wrappers/ios/demo/demo/ViewController.swift
|
swift
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 566
|
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "path_to_url">
<plist version="1.0">
<dict>
<key>UIApplicationSceneManifest</key>
<dict>
<key>UIApplicationSupportsMultipleScenes</key>
<false/>
<key>UISceneConfigurations</key>
<dict>
<key>UIWindowSceneSessionRoleApplication</key>
<array>
<dict>
<key>UISceneConfigurationName</key>
<string>Default Configuration</string>
<key>UISceneDelegateClassName</key>
<string>$(PRODUCT_MODULE_NAME).SceneDelegate</string>
<key>UISceneStoryboardFile</key>
<string>Main</string>
</dict>
</array>
</dict>
</dict>
</dict>
</plist>
```
|
/content/code_sandbox/wrappers/ios/demo/demo/Info.plist
|
xml
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 213
|
```xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="13122.16" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="13104.12"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="EHf-IW-A2E">
<objects>
<viewController id="01J-lp-oVM" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" xcode11CocoaTouchSystemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
<viewLayoutGuide key="safeArea" id="6Tk-OE-BBY"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="53" y="375"/>
</scene>
</scenes>
</document>
```
|
/content/code_sandbox/wrappers/ios/demo/demo/Base.lproj/LaunchScreen.storyboard
|
xml
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 417
|
```unknown
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 55;
objects = {
/* Begin PBXBuildFile section */
388BF029283CC49D005CE271 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 388BF028283CC49D005CE271 /* AppDelegate.swift */; };
388BF02B283CC49D005CE271 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 388BF02A283CC49D005CE271 /* SceneDelegate.swift */; };
388BF02D283CC49D005CE271 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 388BF02C283CC49D005CE271 /* ViewController.swift */; };
388BF030283CC49D005CE271 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 388BF02E283CC49D005CE271 /* Main.storyboard */; };
388BF032283CC49E005CE271 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 388BF031283CC49E005CE271 /* Assets.xcassets */; };
388BF035283CC49E005CE271 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 388BF033283CC49E005CE271 /* LaunchScreen.storyboard */; };
5EFA4B742ADF0F35000132A0 /* ZXingCpp in Frameworks */ = {isa = PBXBuildFile; productRef = 5EFA4B732ADF0F35000132A0 /* ZXingCpp */; };
950744522860A3A300E02D06 /* WriteViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 950744512860A3A300E02D06 /* WriteViewController.swift */; };
/* End PBXBuildFile section */
/* Begin PBXCopyFilesBuildPhase section */
52A975482ADAD7DE002D6BD8 /* Embed Frameworks */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 2147483647;
dstPath = "";
dstSubfolderSpec = 10;
files = (
);
name = "Embed Frameworks";
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
388BF025283CC49D005CE271 /* demo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = demo.app; sourceTree = BUILT_PRODUCTS_DIR; };
388BF028283CC49D005CE271 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
388BF02A283CC49D005CE271 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = "<group>"; };
388BF02C283CC49D005CE271 /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = "<group>"; };
388BF02F283CC49D005CE271 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = "<group>"; };
388BF031283CC49E005CE271 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
388BF034283CC49E005CE271 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
388BF036283CC49E005CE271 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
388BF043283CE0AC005CE271 /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = "<group>"; };
5EFA4B712ADF0F16000132A0 /* zxing-cpp */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = "zxing-cpp"; path = ../../..; sourceTree = "<group>"; };
950744512860A3A300E02D06 /* WriteViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WriteViewController.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
388BF022283CC49D005CE271 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
5EFA4B742ADF0F35000132A0 /* ZXingCpp in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
388BF01C283CC49D005CE271 = {
isa = PBXGroup;
children = (
5EFA4B702ADF0F16000132A0 /* Packages */,
388BF043283CE0AC005CE271 /* README.md */,
388BF027283CC49D005CE271 /* demo */,
388BF026283CC49D005CE271 /* Products */,
5EFA4B722ADF0F35000132A0 /* Frameworks */,
);
sourceTree = "<group>";
};
388BF026283CC49D005CE271 /* Products */ = {
isa = PBXGroup;
children = (
388BF025283CC49D005CE271 /* demo.app */,
);
name = Products;
sourceTree = "<group>";
};
388BF027283CC49D005CE271 /* demo */ = {
isa = PBXGroup;
children = (
388BF028283CC49D005CE271 /* AppDelegate.swift */,
388BF02A283CC49D005CE271 /* SceneDelegate.swift */,
388BF02C283CC49D005CE271 /* ViewController.swift */,
950744512860A3A300E02D06 /* WriteViewController.swift */,
388BF02E283CC49D005CE271 /* Main.storyboard */,
388BF031283CC49E005CE271 /* Assets.xcassets */,
388BF033283CC49E005CE271 /* LaunchScreen.storyboard */,
388BF036283CC49E005CE271 /* Info.plist */,
);
path = demo;
sourceTree = "<group>";
};
5EFA4B702ADF0F16000132A0 /* Packages */ = {
isa = PBXGroup;
children = (
5EFA4B712ADF0F16000132A0 /* zxing-cpp */,
);
name = Packages;
sourceTree = "<group>";
};
5EFA4B722ADF0F35000132A0 /* Frameworks */ = {
isa = PBXGroup;
children = (
);
name = Frameworks;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
388BF024283CC49D005CE271 /* demo */ = {
isa = PBXNativeTarget;
buildConfigurationList = 388BF039283CC49E005CE271 /* Build configuration list for PBXNativeTarget "demo" */;
buildPhases = (
388BF021283CC49D005CE271 /* Sources */,
388BF022283CC49D005CE271 /* Frameworks */,
388BF023283CC49D005CE271 /* Resources */,
52A975482ADAD7DE002D6BD8 /* Embed Frameworks */,
);
buildRules = (
);
dependencies = (
);
name = demo;
packageProductDependencies = (
5EFA4B732ADF0F35000132A0 /* ZXingCpp */,
);
productName = demo;
productReference = 388BF025283CC49D005CE271 /* demo.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
388BF01D283CC49D005CE271 /* Project object */ = {
isa = PBXProject;
attributes = {
BuildIndependentTargetsInParallel = 1;
LastSwiftUpdateCheck = 1340;
LastUpgradeCheck = 1340;
TargetAttributes = {
388BF024283CC49D005CE271 = {
CreatedOnToolsVersion = 13.4;
};
};
};
buildConfigurationList = 388BF020283CC49D005CE271 /* Build configuration list for PBXProject "demo" */;
compatibilityVersion = "Xcode 13.0";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = 388BF01C283CC49D005CE271;
packageReferences = (
);
productRefGroup = 388BF026283CC49D005CE271 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
388BF024283CC49D005CE271 /* demo */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
388BF023283CC49D005CE271 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
388BF035283CC49E005CE271 /* LaunchScreen.storyboard in Resources */,
388BF032283CC49E005CE271 /* Assets.xcassets in Resources */,
388BF030283CC49D005CE271 /* Main.storyboard in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
388BF021283CC49D005CE271 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
388BF02D283CC49D005CE271 /* ViewController.swift in Sources */,
388BF029283CC49D005CE271 /* AppDelegate.swift in Sources */,
950744522860A3A300E02D06 /* WriteViewController.swift in Sources */,
388BF02B283CC49D005CE271 /* SceneDelegate.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXVariantGroup section */
388BF02E283CC49D005CE271 /* Main.storyboard */ = {
isa = PBXVariantGroup;
children = (
388BF02F283CC49D005CE271 /* Base */,
);
name = Main.storyboard;
sourceTree = "<group>";
};
388BF033283CC49E005CE271 /* LaunchScreen.storyboard */ = {
isa = PBXVariantGroup;
children = (
388BF034283CC49E005CE271 /* Base */,
);
name = LaunchScreen.storyboard;
sourceTree = "<group>";
};
/* End PBXVariantGroup section */
/* Begin XCBuildConfiguration section */
388BF037283CC49E005CE271 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++17";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
GCC_C_LANGUAGE_STANDARD = gnu11;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 14.0;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
};
name = Debug;
};
388BF038283CC49E005CE271 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++17";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_C_LANGUAGE_STANDARD = gnu11;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 14.0;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
SDKROOT = iphoneos;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_OPTIMIZATION_LEVEL = "-O";
VALIDATE_PRODUCT = YES;
};
name = Release;
};
388BF03A283CC49E005CE271 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_TEAM = "";
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_FILE = demo/Info.plist;
INFOPLIST_KEY_NSCameraUsageDescription = "Test ZXing";
INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;
INFOPLIST_KEY_UILaunchStoryboardName = LaunchScreen;
INFOPLIST_KEY_UIMainStoryboardFile = Main;
INFOPLIST_KEY_UISupportedInterfaceOrientations = UIInterfaceOrientationPortrait;
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
IPHONEOS_DEPLOYMENT_TARGET = 13.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = "com.zxing-cpp.ios.demo-${SAMPLE_CODE_DISAMBIGUATOR}";
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
SAMPLE_CODE_DISAMBIGUATOR = "${DEVELOPMENT_TEAM}";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Debug;
};
388BF03B283CC49E005CE271 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_TEAM = "";
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_FILE = demo/Info.plist;
INFOPLIST_KEY_NSCameraUsageDescription = "Test ZXing";
INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;
INFOPLIST_KEY_UILaunchStoryboardName = LaunchScreen;
INFOPLIST_KEY_UIMainStoryboardFile = Main;
INFOPLIST_KEY_UISupportedInterfaceOrientations = UIInterfaceOrientationPortrait;
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
IPHONEOS_DEPLOYMENT_TARGET = 13.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = "com.zxing-cpp.ios.demo-${SAMPLE_CODE_DISAMBIGUATOR}";
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
SAMPLE_CODE_DISAMBIGUATOR = "${DEVELOPMENT_TEAM}";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
388BF020283CC49D005CE271 /* Build configuration list for PBXProject "demo" */ = {
isa = XCConfigurationList;
buildConfigurations = (
388BF037283CC49E005CE271 /* Debug */,
388BF038283CC49E005CE271 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
388BF039283CC49E005CE271 /* Build configuration list for PBXNativeTarget "demo" */ = {
isa = XCConfigurationList;
buildConfigurations = (
388BF03A283CC49E005CE271 /* Debug */,
388BF03B283CC49E005CE271 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
/* Begin XCSwiftPackageProductDependency section */
5EFA4B732ADF0F35000132A0 /* ZXingCpp */ = {
isa = XCSwiftPackageProductDependency;
productName = ZXingCpp;
};
/* End XCSwiftPackageProductDependency section */
};
rootObject = 388BF01D283CC49D005CE271 /* Project object */;
}
```
|
/content/code_sandbox/wrappers/ios/demo/demo.xcodeproj/project.pbxproj
|
unknown
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 5,122
|
```kotlin
pluginManagement {
repositories {
mavenLocal()
gradlePluginPortal()
google()
mavenCentral()
}
}
plugins {
id("org.gradle.toolchains.foojay-resolver-convention") version "0.5.0"
}
dependencyResolutionManagement {
repositories {
google()
mavenCentral()
}
}
rootProject.name = "zxing-cpp"
```
|
/content/code_sandbox/wrappers/kn/settings.gradle.kts
|
kotlin
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 82
|
```xml
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="20037" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="yt5-A2-Fye">
<device id="retina6_1" orientation="portrait" appearance="light"/>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="20020"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="System colors in document resources" minToolsVersion="11.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--Read-->
<scene sceneID="tne-QT-ifu">
<objects>
<viewController id="BYZ-38-t0r" customClass="ViewController" customModule="demo" customModuleProvider="target" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
<rect key="frame" x="0.0" y="0.0" width="414" height="896"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<viewLayoutGuide key="safeArea" id="6Tk-OE-BBY"/>
<color key="backgroundColor" systemColor="systemBackgroundColor"/>
</view>
<navigationItem key="navigationItem" title="Read" id="FJL-kY-V3h">
<barButtonItem key="rightBarButtonItem" title="Write" id="cOY-Rz-7Sx">
<connections>
<segue destination="NS1-KJ-jgd" kind="show" id="kWB-XI-rqf"/>
</connections>
</barButtonItem>
</navigationItem>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="1047.8260869565217" y="137.94642857142856"/>
</scene>
<!--Write-->
<scene sceneID="8Q2-Vq-Rob">
<objects>
<viewController id="NS1-KJ-jgd" customClass="WriteViewController" customModule="demo" customModuleProvider="target" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="II3-kA-EKz">
<rect key="frame" x="0.0" y="0.0" width="414" height="896"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<textField opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="left" contentVerticalAlignment="center" borderStyle="roundedRect" placeholder="Type to generate code" minimumFontSize="17" translatesAutoresizingMaskIntoConstraints="NO" id="AYU-Al-DLc">
<rect key="frame" x="20" y="108" width="374" height="34"/>
<fontDescription key="fontDescription" type="system" pointSize="14"/>
<textInputTraits key="textInputTraits"/>
<connections>
<action selector="textFieldChanged:" destination="NS1-KJ-jgd" eventType="editingChanged" id="06Y-mH-LeN"/>
</connections>
</textField>
<imageView clipsSubviews="YES" userInteractionEnabled="NO" contentMode="scaleAspectFit" horizontalHuggingPriority="251" verticalHuggingPriority="251" translatesAutoresizingMaskIntoConstraints="NO" id="9ev-u1-fcI">
<rect key="frame" x="87" y="182" width="240" height="240"/>
<constraints>
<constraint firstAttribute="width" constant="240" id="BXF-wO-RlT"/>
<constraint firstAttribute="width" secondItem="9ev-u1-fcI" secondAttribute="height" multiplier="1:1" id="hse-Cr-0Zv"/>
</constraints>
</imageView>
</subviews>
<viewLayoutGuide key="safeArea" id="esr-8S-vwU"/>
<color key="backgroundColor" systemColor="systemBackgroundColor"/>
<constraints>
<constraint firstItem="9ev-u1-fcI" firstAttribute="top" secondItem="AYU-Al-DLc" secondAttribute="bottom" constant="40" id="GYN-Ow-aWc"/>
<constraint firstItem="9ev-u1-fcI" firstAttribute="centerX" secondItem="esr-8S-vwU" secondAttribute="centerX" id="dtl-Nu-gKp"/>
<constraint firstItem="AYU-Al-DLc" firstAttribute="top" secondItem="esr-8S-vwU" secondAttribute="top" constant="20" id="fKy-vm-mKO"/>
<constraint firstItem="esr-8S-vwU" firstAttribute="trailing" secondItem="AYU-Al-DLc" secondAttribute="trailing" constant="20" id="hk7-7R-Sd5"/>
<constraint firstItem="AYU-Al-DLc" firstAttribute="leading" secondItem="esr-8S-vwU" secondAttribute="leading" constant="20" id="mvP-qH-VeG"/>
</constraints>
</view>
<navigationItem key="navigationItem" title="Write" id="zdR-J6-ZO8"/>
<connections>
<outlet property="imageView" destination="9ev-u1-fcI" id="5NL-Mg-JRd"/>
</connections>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="n6S-jS-clP" userLabel="First Responder" customClass="UIResponder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="1839.1304347826087" y="137.94642857142856"/>
</scene>
<!--Navigation Controller-->
<scene sceneID="8xG-zr-hYL">
<objects>
<navigationController automaticallyAdjustsScrollViewInsets="NO" id="yt5-A2-Fye" sceneMemberID="viewController">
<toolbarItems/>
<navigationBar key="navigationBar" contentMode="scaleToFill" id="LMB-hf-Xg8">
<rect key="frame" x="0.0" y="44" width="414" height="44"/>
<autoresizingMask key="autoresizingMask"/>
</navigationBar>
<nil name="viewControllers"/>
<connections>
<segue destination="BYZ-38-t0r" kind="relationship" relationship="rootViewController" id="8AK-79-EBZ"/>
</connections>
</navigationController>
<placeholder placeholderIdentifier="IBFirstResponder" id="zqG-ca-UiG" userLabel="First Responder" customClass="UIResponder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="137.68115942028987" y="137.94642857142856"/>
</scene>
</scenes>
<resources>
<systemColor name="systemBackgroundColor">
<color white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
</systemColor>
</resources>
</document>
```
|
/content/code_sandbox/wrappers/ios/demo/demo/Base.lproj/Main.storyboard
|
xml
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 1,711
|
```batchfile
@rem
@rem
@rem
@rem path_to_url
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
```
|
/content/code_sandbox/wrappers/kn/gradlew.bat
|
batchfile
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 590
|
```kotlin
import io.github.isning.gradle.plugins.cmake.params.CustomCMakeParams
import io.github.isning.gradle.plugins.cmake.params.entries.CustomCMakeCacheEntries
import io.github.isning.gradle.plugins.cmake.params.entries.asCMakeParams
import io.github.isning.gradle.plugins.cmake.params.entries.platform.ModifiablePlatformEntriesImpl
import io.github.isning.gradle.plugins.cmake.params.entries.plus
import io.github.isning.gradle.plugins.cmake.params.plus
import io.github.isning.gradle.plugins.kn.krossCompile.invoke
import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget
import java.util.*
plugins {
alias(libs.plugins.kotlinMultiplatform)
alias(libs.plugins.krossCompile)
`maven-publish`
signing
}
group = "io.github.zxing-cpp"
version = "2.2.1"
Properties().apply {
rootProject.file("local.properties").takeIf { it.exists() && it.isFile }?.let { load(it.reader()) }
}.onEach { (key, value) ->
if (key is String) ext[key] = value
}
val hostOs = System.getProperty("os.name")
repositories {
mavenCentral()
google()
}
kotlin {
val androidTargets = {
listOf(
androidNativeArm32(),
androidNativeArm64(),
androidNativeX86(),
androidNativeX64(),
)
}
val appleTargets = {
listOf(
iosX64(),
iosArm64(),
iosSimulatorArm64(),
macosX64(),
macosArm64(),
watchosX64(),
watchosArm32(),
watchosArm64(),
watchosSimulatorArm64(),
tvosX64(),
tvosArm64(),
tvosSimulatorArm64(),
)
}
val linuxTargets = {
listOf(
linuxX64(),
linuxArm64(),
)
}
// TODO: Linking failed, keep up with path_to_url
// val windowsTargets = {
// listOf(
// mingwX64(),
// )
// }
val enabledTargetList = mutableListOf<KotlinNativeTarget>()
enabledTargetList.addAll(androidTargets())
enabledTargetList.addAll(linuxTargets())
// TODO: Linking failed, keep up with path_to_url
// enabledTargetList.addAll(windowsTargets())
if (hostOs == "Mac OS X") enabledTargetList.addAll(appleTargets())
}
krossCompile {
libraries {
val cmakeDir = project.layout.buildDirectory.dir("cmake").get().asFile.absolutePath
val zxingCpp by creating {
sourceDir = file("../../core").absolutePath
outputPath = ""
libraryArtifactNames = listOf("libZXing.a")
cinterop {
val buildDir = "$cmakeDir/{libraryName}/{targetName}"
packageName = "zxingcpp.cinterop"
includeDirs.from(buildDir)
headers = listOf("$sourceDir/src/ZXingC.h")
compilerOpts += "-DZXING_EXPERIMENTAL_API=ON"
}
cmake.apply {
val buildDir = "$cmakeDir/{projectName}/{targetName}"
configParams {
this.buildDir = buildDir
}
configParams += (ModifiablePlatformEntriesImpl().apply {
buildType = "Release"
buildSharedLibs = false
} + CustomCMakeCacheEntries(
mapOf(
"ZXING_READERS" to "ON",
"ZXING_WRITERS" to "NEW",
"ZXING_EXPERIMENTAL_API" to "ON",
"ZXING_USE_BUNDLED_ZINT" to "ON",
"ZXING_C_API" to "ON",
)
)).asCMakeParams
buildParams {
this.buildDir = buildDir
config = "Release"
}
buildParams += CustomCMakeParams(listOf("-j16"))
}
androidNativeX64.ndk()
androidNativeX86.ndk()
androidNativeArm32.ndk()
androidNativeArm64.ndk()
// TODO: Find a way to build linux targets with cxx20. Detail: path_to_url#discussion_r1485701269
linuxX64.konan {
cmake {
configParams += CustomCMakeCacheEntries(
mapOf(
"CMAKE_CXX_STANDARD" to "17",
)
).asCMakeParams
}
}
linuxArm64.konan {
cmake {
configParams += CustomCMakeCacheEntries(
mapOf(
"CMAKE_CXX_STANDARD" to "17",
)
).asCMakeParams
}
}
// TODO: Linking failed, keep up with path_to_url
// mingwX64.konan()
if (hostOs == "Mac OS X") {
iosX64.xcode()
iosArm64.xcode()
iosSimulatorArm64.xcode()
macosX64.xcode()
macosArm64.xcode()
watchosX64.xcode()
watchosArm32.xcode()
watchosArm64.xcode()
watchosSimulatorArm64.xcode()
tvosX64.xcode()
tvosArm64.xcode()
tvosSimulatorArm64.xcode()
}
}
}
}
publishing {
publications.withType<MavenPublication>().all {
artifactId = artifactId.replace(project.name, "kotlin-native")
groupId = project.group.toString()
version = project.version.toString()
pom {
name = "zxing-cpp"
description = "Wrapper for zxing-cpp barcode image processing library"
url = "path_to_url"
licenses {
license {
url = "path_to_url"
}
}
developers {
developer {
id = "zxing-cpp"
name = "zxing-cpp community"
email = "zxingcpp@gmail.com"
}
}
scm {
connection = "scm:git:git://github.com/zxing-cpp/zxing-cpp.git"
developerConnection = "scm:git:git://github.com/zxing-cpp/zxing-cpp.git"
url = "path_to_url"
}
}
}
repositories {
maven {
name = "sonatype"
val releasesRepoUrl = "path_to_url"
val snapshotsRepoUrl = "path_to_url"
setUrl(if (version.toString().endsWith("SNAPSHOT")) snapshotsRepoUrl else releasesRepoUrl)
credentials {
val ossrhUsername: String? by project
val ossrhPassword: String? by project
username = ossrhUsername
password = ossrhPassword
}
}
}
}
signing {
val signingKey: String? by project
val signingPassword: String? by project
if (signingKey != null && signingPassword != null) {
useInMemoryPgpKeys(signingKey, signingPassword)
sign(publishing.publications)
}
}
```
|
/content/code_sandbox/wrappers/kn/build.gradle.kts
|
kotlin
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 1,495
|
```ini
kotlin.code.style=official
kotlin.mpp.enableCInteropCommonization=true
```
|
/content/code_sandbox/wrappers/kn/gradle.properties
|
ini
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 18
|
```toml
[versions]
kotlin = "1.9.22"
krossCompile = "0.1.9"
[libraries]
[plugins]
kotlinMultiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" }
krossCompile = { id = "io.github.isning.gradle.plugins.kn.krossCompile", version.ref = "krossCompile" }
```
|
/content/code_sandbox/wrappers/kn/gradle/libs.versions.toml
|
toml
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 83
|
```ini
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
```
|
/content/code_sandbox/wrappers/kn/gradle/wrapper/gradle-wrapper.properties
|
ini
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 54
|
```kotlin
/*
*/
package zxingcpp
import cnames.structs.ZXing_CreatorOptions
import cnames.structs.ZXing_WriterOptions
import kotlinx.cinterop.*
import zxingcpp.cinterop.*
import kotlin.experimental.ExperimentalNativeApi
import kotlin.native.ref.createCleaner
// TODO: Remove this annotation when the API is stable
@RequiresOptIn(level = RequiresOptIn.Level.ERROR, message = "The Writer API is experimental and may change in the future.")
@Retention(AnnotationRetention.BINARY)
annotation class ExperimentalWriterApi
class BarcodeWritingException(message: String?) : Exception("Failed to write barcode: $message")
@ExperimentalWriterApi
@OptIn(ExperimentalForeignApi::class)
open class CreatorOptions(format: BarcodeFormat) {
var format: BarcodeFormat
get() = ZXing_CreatorOptions_getFormat(cValue).parseIntoBarcodeFormat().first()
set(value) = ZXing_CreatorOptions_setFormat(cValue, value.rawValue)
var readerInit: Boolean
get() = ZXing_CreatorOptions_getReaderInit(cValue)
set(value) = ZXing_CreatorOptions_setReaderInit(cValue, value)
var forceSquareDataMatrix: Boolean
get() = ZXing_CreatorOptions_getForceSquareDataMatrix(cValue)
set(value) = ZXing_CreatorOptions_setForceSquareDataMatrix(cValue, value)
var ecLevel: String
get() = ZXing_CreatorOptions_getEcLevel(cValue)?.toKStringNullPtrHandledAndFree() ?: ""
set(value) = ZXing_CreatorOptions_setEcLevel(cValue, value)
val cValue: CValuesRef<ZXing_CreatorOptions>? = ZXing_CreatorOptions_new(format.rawValue)
@Suppress("unused")
@OptIn(ExperimentalNativeApi::class)
private val cleaner = createCleaner(cValue) { ZXing_CreatorOptions_delete(it) }
}
@ExperimentalWriterApi
@OptIn(ExperimentalForeignApi::class)
open class WriterOptions {
var scale: Int
get() = ZXing_WriterOptions_getScale(cValue)
set(value) = ZXing_WriterOptions_setScale(cValue, value)
var sizeHint: Int
get() = ZXing_WriterOptions_getSizeHint(cValue)
set(value) = ZXing_WriterOptions_setSizeHint(cValue, value)
var rotate: Int
get() = ZXing_WriterOptions_getRotate(cValue)
set(value) = ZXing_WriterOptions_setRotate(cValue, value)
var withHRT: Boolean
get() = ZXing_WriterOptions_getWithHRT(cValue)
set(value) = ZXing_WriterOptions_setWithHRT(cValue, value)
var withQuietZones: Boolean
get() = ZXing_WriterOptions_getWithQuietZones(cValue)
set(value) = ZXing_WriterOptions_setWithQuietZones(cValue, value)
val cValue: CValuesRef<ZXing_WriterOptions>? = ZXing_WriterOptions_new()
@Suppress("unused")
@OptIn(ExperimentalNativeApi::class)
private val cleaner = createCleaner(cValue) { ZXing_WriterOptions_delete(it) }
}
```
|
/content/code_sandbox/wrappers/kn/src/nativeMain/kotlin/zxingcpp/BarcodeWriter.kt
|
kotlin
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 675
|
```unknown
#!/bin/sh
#
#
#
# path_to_url
#
# Unless required by applicable law or agreed to in writing, software
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions $var, ${var}, ${var:-default}, ${var+SET},
# ${var#prefix}, ${var%suffix}, and $( cmd );
# * compound commands having a testable exit status, especially case;
# * various built-in commands including command, set, and ulimit.
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# path_to_url
# within the Gradle project.
#
# You can find Gradle at path_to_url
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
```
|
/content/code_sandbox/wrappers/kn/gradlew
|
unknown
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 1,929
|
```kotlin
/*
*/
package zxingcpp
import cnames.structs.ZXing_Barcode
import cnames.structs.ZXing_Barcodes
import kotlinx.cinterop.*
import zxingcpp.cinterop.*
import zxingcpp.cinterop.ZXing_ContentType.*
import kotlin.experimental.ExperimentalNativeApi
import kotlin.native.ref.createCleaner
@OptIn(ExperimentalForeignApi::class)
enum class ContentType(internal val cValue: ZXing_ContentType) {
Text(ZXing_ContentType_Text),
Binary(ZXing_ContentType_Binary),
Mixed(ZXing_ContentType_Mixed),
GS1(ZXing_ContentType_GS1),
ISO15434(ZXing_ContentType_ISO15434),
UnknownECI(ZXing_ContentType_UnknownECI);
}
@OptIn(ExperimentalForeignApi::class)
fun ZXing_ContentType.toKObject(): ContentType {
return ContentType.entries.first { it.cValue == this }
}
data class PointI(
val x: Int,
val y: Int
)
@OptIn(ExperimentalForeignApi::class)
fun ZXing_PointI.toKObject(): PointI = PointI(x, y)
data class Position(
val topLeft: PointI,
val topRight: PointI,
val bottomRight: PointI,
val bottomLeft: PointI,
)
@OptIn(ExperimentalForeignApi::class)
fun ZXing_Position.toKObject(): Position = Position(
topLeft.toKObject(),
topRight.toKObject(),
bottomRight.toKObject(),
bottomLeft.toKObject(),
)
class BarcodeConstructionException(message: String?) : Exception("Failed to construct barcode: $message")
@OptIn(ExperimentalForeignApi::class)
class Barcode(val cValue: CValuesRef<ZXing_Barcode>) {
@ExperimentalWriterApi
constructor(text: String, opts: CreatorOptions) : this(
ZXing_CreateBarcodeFromText(text, text.length, opts.cValue)
?: throw BarcodeConstructionException(ZXing_LastErrorMsg()?.toKStringNullPtrHandledAndFree())
)
@ExperimentalWriterApi
constructor(text: String, format: BarcodeFormat) : this(text, CreatorOptions(format))
@ExperimentalWriterApi
constructor(bytes: ByteArray, opts: CreatorOptions) : this(
ZXing_CreateBarcodeFromBytes(bytes.refTo(0), bytes.size, opts.cValue)
?: throw BarcodeConstructionException(ZXing_LastErrorMsg()?.toKStringNullPtrHandledAndFree())
)
@ExperimentalWriterApi
constructor(bytes: ByteArray, format: BarcodeFormat) : this(bytes, CreatorOptions(format))
val isValid: Boolean
get() = ZXing_Barcode_isValid(cValue)
val errorMsg: String? by lazy {
ZXing_Barcode_errorMsg(cValue)?.toKStringNullPtrHandledAndFree()
}
val format: BarcodeFormat by lazy {
ZXing_Barcode_format(cValue).parseIntoBarcodeFormat().first { it != BarcodeFormat.None }
}
val contentType: ContentType by lazy {
ZXing_Barcode_contentType(cValue).toKObject()
}
val bytes: ByteArray? by lazy {
memScoped {
val len = alloc<IntVar>()
(ZXing_Barcode_bytes(cValue, len.ptr)?.run {
readBytes(len.value).also { ZXing_free(this) }
} ?: throw OutOfMemoryError()).takeUnless { it.isEmpty() }
}
}
val bytesECI: ByteArray? by lazy {
memScoped {
val len = alloc<IntVar>()
(ZXing_Barcode_bytesECI(cValue, len.ptr)?.run {
readBytes(len.value).also { ZXing_free(this) }
} ?: throw OutOfMemoryError()).takeUnless { it.isEmpty() }
}
}
val text: String? by lazy {
ZXing_Barcode_text(cValue)?.toKStringNullPtrHandledAndFree()
}
val ecLevel: String? by lazy {
ZXing_Barcode_ecLevel(cValue)?.toKStringNullPtrHandledAndFree()
}
val symbologyIdentifier: String? by lazy {
ZXing_Barcode_symbologyIdentifier(cValue)?.toKStringNullPtrHandledAndFree()
}
val position: Position by lazy {
ZXing_Barcode_position(cValue).useContents { toKObject() }
}
val orientation: Int
get() = ZXing_Barcode_orientation(cValue)
val hasECI: Boolean
get() = ZXing_Barcode_hasECI(cValue)
val isInverted: Boolean
get() = ZXing_Barcode_isInverted(cValue)
val isMirrored: Boolean
get() = ZXing_Barcode_isMirrored(cValue)
val lineCount: Int
get() = ZXing_Barcode_lineCount(cValue)
@Suppress("unused")
@OptIn(ExperimentalNativeApi::class)
private val cleaner = createCleaner(cValue) { ZXing_Barcode_delete(it) }
override fun toString(): String {
return "Barcode(" +
"cValue=$cValue, " +
"bytes=${bytes?.contentToString()}, " +
"bytesECI=${bytesECI?.contentToString()}, " +
"lineCount=$lineCount, " +
"isMirrored=$isMirrored, " +
"isInverted=$isInverted, " +
"hasECI=$hasECI, " +
"orientation=$orientation, " +
"position=$position, " +
"symbologyIdentifier=$symbologyIdentifier, " +
"ecLevel=$ecLevel, " +
"text=$text, " +
"contentType=$contentType, " +
"format=$format, " +
"errorMsg=$errorMsg, " +
"isValid=$isValid" +
")"
}
}
@OptIn(ExperimentalForeignApi::class)
@ExperimentalWriterApi
fun Barcode.toSVG(opts: WriterOptions? = null): String = cValue.usePinned {
ZXing_WriteBarcodeToSVG(it.get(), opts?.cValue)?.toKStringNullPtrHandledAndFree()
?: throw BarcodeWritingException(ZXing_LastErrorMsg()?.toKStringNullPtrHandledAndFree())
}
@OptIn(ExperimentalForeignApi::class)
@ExperimentalWriterApi
fun Barcode.toImage(opts: WriterOptions? = null): Image = cValue.usePinned {
ZXing_WriteBarcodeToImage(it.get(), opts?.cValue)?.toKObject()
?: throw BarcodeWritingException(ZXing_LastErrorMsg()?.toKStringNullPtrHandledAndFree())
}
@OptIn(ExperimentalForeignApi::class)
fun CValuesRef<ZXing_Barcode>.toKObject(): Barcode = Barcode(this)
@OptIn(ExperimentalForeignApi::class)
fun CValuesRef<ZXing_Barcodes>.toKObject(): List<Barcode> = mutableListOf<Barcode>().apply {
for (i in 0..<ZXing_Barcodes_size(this@toKObject))
ZXing_Barcodes_move(this@toKObject, i)?.toKObject()?.let { add(it) }
}.toList()
```
|
/content/code_sandbox/wrappers/kn/src/nativeMain/kotlin/zxingcpp/Barcode.kt
|
kotlin
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 1,506
|
```kotlin
/*
*/
package zxingcpp
import cnames.structs.ZXing_ReaderOptions
import kotlinx.cinterop.*
import zxingcpp.cinterop.*
import zxingcpp.cinterop.ZXing_Binarizer.*
import zxingcpp.cinterop.ZXing_EanAddOnSymbol.*
import zxingcpp.cinterop.ZXing_TextMode.*
import kotlin.experimental.ExperimentalNativeApi
import kotlin.native.ref.createCleaner
@OptIn(ExperimentalForeignApi::class)
internal fun CPointer<ByteVar>?.toKStringNullPtrHandledAndFree(): String? = (this ?: throw OutOfMemoryError()).run {
toKString().also { ZXing_free(this) }.ifEmpty { null }
}
@OptIn(ExperimentalForeignApi::class)
class BarcodeReader : ReaderOptions() {
@Throws(BarcodeReadingException::class)
fun read(imageView: ImageView): List<Barcode> = Companion.read(imageView, this)
companion object {
@Throws(BarcodeReadingException::class)
fun read(imageView: ImageView, opts: ReaderOptions? = null): List<Barcode> =
ZXing_ReadBarcodes(imageView.cValue, opts?.cValue)?.let { cValues -> cValues.toKObject().also { ZXing_Barcodes_delete(cValues) } }
?: throw BarcodeReadingException(ZXing_LastErrorMsg()?.toKStringNullPtrHandledAndFree())
}
}
class BarcodeReadingException(message: String?) : Exception("Failed to read barcodes: $message")
@OptIn(ExperimentalForeignApi::class)
open class ReaderOptions {
var tryHarder: Boolean
get() = ZXing_ReaderOptions_getTryHarder(cValue)
set(value) = ZXing_ReaderOptions_setTryHarder(cValue, value)
var tryRotate: Boolean
get() = ZXing_ReaderOptions_getTryRotate(cValue)
set(value) = ZXing_ReaderOptions_setTryRotate(cValue, value)
var tryDownscale: Boolean
get() = ZXing_ReaderOptions_getTryDownscale(cValue)
set(value) = ZXing_ReaderOptions_setTryDownscale(cValue, value)
var tryInvert: Boolean
get() = ZXing_ReaderOptions_getTryInvert(cValue)
set(value) = ZXing_ReaderOptions_setTryInvert(cValue, value)
var isPure: Boolean
get() = ZXing_ReaderOptions_getIsPure(cValue)
set(value) = ZXing_ReaderOptions_setIsPure(cValue, value)
var returnErrors: Boolean
get() = ZXing_ReaderOptions_getReturnErrors(cValue)
set(value) = ZXing_ReaderOptions_setReturnErrors(cValue, value)
var binarizer: Binarizer
get() = Binarizer.fromCValue(ZXing_ReaderOptions_getBinarizer(cValue))
set(value) = ZXing_ReaderOptions_setBinarizer(cValue, value.cValue)
var formats: Set<BarcodeFormat>
get() = ZXing_ReaderOptions_getFormats(cValue).parseIntoBarcodeFormat()
set(value) = ZXing_ReaderOptions_setFormats(cValue, value.toValue())
var eanAddOnSymbol: EanAddOnSymbol
get() = EanAddOnSymbol.fromCValue(ZXing_ReaderOptions_getEanAddOnSymbol(cValue))
set(value) = ZXing_ReaderOptions_setEanAddOnSymbol(cValue, value.cValue)
var textMode: TextMode
get() = TextMode.fromCValue(ZXing_ReaderOptions_getTextMode(cValue))
set(value) = ZXing_ReaderOptions_setTextMode(cValue, value.cValue)
var minLineCount: Int
get() = ZXing_ReaderOptions_getMinLineCount(cValue)
set(value) = ZXing_ReaderOptions_setMinLineCount(cValue, value)
var maxNumberOfSymbols: Int
get() = ZXing_ReaderOptions_getMaxNumberOfSymbols(cValue)
set(value) = ZXing_ReaderOptions_setMaxNumberOfSymbols(cValue, value)
val cValue: CValuesRef<ZXing_ReaderOptions>? = ZXing_ReaderOptions_new()
@Suppress("unused")
@OptIn(ExperimentalNativeApi::class)
private val cleaner = createCleaner(cValue) { ZXing_ReaderOptions_delete(it) }
}
@OptIn(ExperimentalForeignApi::class)
enum class Binarizer(internal val cValue: ZXing_Binarizer) {
LocalAverage(ZXing_Binarizer_LocalAverage),
GlobalHistogram(ZXing_Binarizer_GlobalHistogram),
FixedThreshold(ZXing_Binarizer_FixedThreshold),
BoolCast(ZXing_Binarizer_BoolCast);
companion object {
fun fromCValue(cValue: ZXing_Binarizer): Binarizer {
return entries.first { it.cValue == cValue }
}
}
}
@OptIn(ExperimentalForeignApi::class)
enum class EanAddOnSymbol(internal val cValue: ZXing_EanAddOnSymbol) {
Ignore(ZXing_EanAddOnSymbol_Ignore),
Read(ZXing_EanAddOnSymbol_Read),
Require(ZXing_EanAddOnSymbol_Require);
companion object {
fun fromCValue(cValue: ZXing_EanAddOnSymbol): EanAddOnSymbol {
return entries.first { it.cValue == cValue }
}
}
}
@OptIn(ExperimentalForeignApi::class)
enum class TextMode(internal val cValue: ZXing_TextMode) {
Plain(ZXing_TextMode_Plain),
ECI(ZXing_TextMode_ECI),
HRI(ZXing_TextMode_HRI),
Hex(ZXing_TextMode_Hex),
Escaped(ZXing_TextMode_Escaped);
companion object {
fun fromCValue(cValue: ZXing_TextMode): TextMode {
return entries.first { it.cValue == cValue }
}
}
}
```
|
/content/code_sandbox/wrappers/kn/src/nativeMain/kotlin/zxingcpp/BarcodeReader.kt
|
kotlin
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 1,270
|
```kotlin
/*
*/
package zxingcpp
import kotlinx.cinterop.ExperimentalForeignApi
import zxingcpp.cinterop.*
@OptIn(ExperimentalForeignApi::class)
enum class BarcodeFormat(internal val rawValue: UInt) {
None(ZXing_BarcodeFormat_None),
Aztec(ZXing_BarcodeFormat_Aztec),
Codabar(ZXing_BarcodeFormat_Codabar),
Code39(ZXing_BarcodeFormat_Code39),
Code93(ZXing_BarcodeFormat_Code93),
Code128(ZXing_BarcodeFormat_Code128),
DataBar(ZXing_BarcodeFormat_DataBar),
DataBarExpanded(ZXing_BarcodeFormat_DataBarExpanded),
DataMatrix(ZXing_BarcodeFormat_DataMatrix),
DXFilmEdge(ZXing_BarcodeFormat_DXFilmEdge),
EAN8(ZXing_BarcodeFormat_EAN8),
EAN13(ZXing_BarcodeFormat_EAN13),
ITF(ZXing_BarcodeFormat_ITF),
MaxiCode(ZXing_BarcodeFormat_MaxiCode),
PDF417(ZXing_BarcodeFormat_PDF417),
QRCode(ZXing_BarcodeFormat_QRCode),
MicroQrCode(ZXing_BarcodeFormat_MicroQRCode),
RMQRCode(ZXing_BarcodeFormat_RMQRCode),
UPCA(ZXing_BarcodeFormat_UPCA),
UPCE(ZXing_BarcodeFormat_UPCE),
LinearCodes(ZXing_BarcodeFormat_LinearCodes),
MatrixCodes(ZXing_BarcodeFormat_MatrixCodes),
Any(ZXing_BarcodeFormat_Any),
Invalid(ZXing_BarcodeFormat_Invalid),
}
@OptIn(ExperimentalForeignApi::class)
fun ZXing_BarcodeFormat.parseIntoBarcodeFormat(): Set<BarcodeFormat> =
BarcodeFormat.entries.filter { this.or(it.rawValue) == this }.toSet()
@OptIn(ExperimentalForeignApi::class)
fun Iterable<BarcodeFormat>.toValue(): ZXing_BarcodeFormat =
this.map { it.rawValue }.reduce { acc, format -> acc.or(format) }
```
|
/content/code_sandbox/wrappers/kn/src/nativeMain/kotlin/zxingcpp/BarcodeFormat.kt
|
kotlin
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 425
|
```kotlin
/*
*/
import zxingcpp.*
import kotlin.experimental.ExperimentalNativeApi
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
class BarcodeReaderTest {
@Test
@OptIn(ExperimentalNativeApi::class)
fun `read barcode`() {
val data = your_sha256_hash110010100000".map {
if (it == '0') 255.toByte() else 0.toByte()
}
val iv = ImageView(data.toByteArray(), data.size, 1, ImageFormat.Lum)
val br = BarcodeReader().apply {
binarizer = Binarizer.BoolCast
}
val res = br.read(iv).firstOrNull()
val expected = "96385074"
assertNotNull(res)
assert(res.isValid)
assertEquals(BarcodeFormat.EAN8, res.format)
assertEquals(expected, res.text)
assertContentEquals(expected.encodeToByteArray(), res.bytes)
assert(!res.hasECI)
assertEquals(ContentType.Text, res.contentType)
assertEquals(0, res.orientation)
assertEquals(PointI(4, 0), res.position.topLeft)
assertEquals(1, res.lineCount)
}
@Test
@OptIn(ExperimentalNativeApi::class, ExperimentalWriterApi::class)
fun `create write and read barcode with text`() {
val text = "I have the best words."
val barcode = Barcode(text, BarcodeFormat.DataMatrix)
val image = barcode.toImage()
val res = BarcodeReader.read(image.toImageView()).firstOrNull()
assertNotNull(res)
assert(res.isValid)
assertEquals(BarcodeFormat.DataMatrix, res.format)
assertEquals(text, res.text)
assertContentEquals(text.encodeToByteArray(), res.bytes)
assert(!res.hasECI)
assertEquals(ContentType.Text, res.contentType)
assertEquals(0, res.orientation)
assertEquals(PointI(1, 1), res.position.topLeft)
assertEquals(0, res.lineCount)
}
@Test
@OptIn(ExperimentalNativeApi::class, ExperimentalWriterApi::class)
fun `create write and read barcode with bytes`() {
val text = "I have the best words."
val barcode = Barcode(text.encodeToByteArray(), BarcodeFormat.DataMatrix)
val image = barcode.toImage()
val res = BarcodeReader.read(image.toImageView()).firstOrNull()
assertNotNull(res)
assert(res.isValid)
assertEquals(BarcodeFormat.DataMatrix, res.format)
assertEquals(text, res.text)
assertContentEquals(text.encodeToByteArray(), res.bytes)
assert(res.hasECI)
assertEquals(ContentType.Binary, res.contentType)
assertEquals(0, res.orientation)
assertEquals(PointI(1, 1), res.position.topLeft)
assertEquals(0, res.lineCount)
}
}
```
|
/content/code_sandbox/wrappers/kn/src/nativeTest/kotlin/Test.kt
|
kotlin
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 587
|
```kotlin
/*
*/
package zxingcpp
import cnames.structs.ZXing_Image
import cnames.structs.ZXing_ImageView
import kotlinx.cinterop.*
import zxingcpp.cinterop.*
import kotlin.experimental.ExperimentalNativeApi
import kotlin.native.ref.createCleaner
@OptIn(ExperimentalForeignApi::class)
class ImageView(
val data: ByteArray,
val width: Int,
val height: Int,
val format: ImageFormat,
val rowStride: Int = 0,
val pixStride: Int = 0,
) {
private val pinnedData = data.pin()
val cValue: CPointer<ZXing_ImageView>? =
ZXing_ImageView_new_checked(
pinnedData.addressOf(0).reinterpret(),
data.size,
width,
height,
format.cValue,
rowStride,
pixStride
)
@Suppress("unused")
@OptIn(ExperimentalNativeApi::class)
private val cValueCleaner = createCleaner(cValue) { ZXing_ImageView_delete(it) }
@Suppress("unused")
@OptIn(ExperimentalNativeApi::class)
private val pinnedDataCleaner = createCleaner(pinnedData) { it.unpin() }
}
@OptIn(ExperimentalForeignApi::class)
enum class ImageFormat(internal val cValue: ZXing_ImageFormat) {
None(ZXing_ImageFormat_None),
Lum(ZXing_ImageFormat_Lum),
LumA(ZXing_ImageFormat_LumA),
RGB(ZXing_ImageFormat_RGB),
BGR(ZXing_ImageFormat_BGR),
RGBA(ZXing_ImageFormat_RGBA),
ARGB(ZXing_ImageFormat_ARGB),
BGRA(ZXing_ImageFormat_BGRA),
ABGR(ZXing_ImageFormat_ABGR)
}
@OptIn(ExperimentalForeignApi::class)
fun ZXing_ImageFormat.parseIntoImageFormat(): ImageFormat? =
ImageFormat.entries.firstOrNull { it.cValue == this }
@ExperimentalWriterApi
@OptIn(ExperimentalForeignApi::class)
class Image(val cValue: CValuesRef<ZXing_Image>) {
val data: ByteArray
get() = ZXing_Image_data(cValue)?.run {
readBytes(width * height).also { ZXing_free(this) }
}?.takeUnless { it.isEmpty() } ?: throw OutOfMemoryError()
val width: Int get() = ZXing_Image_width(cValue)
val height: Int get() = ZXing_Image_height(cValue)
val format: ImageFormat
get() = ZXing_Image_format(cValue).parseIntoImageFormat() ?: error(
"Unknown format ${ZXing_Image_format(cValue)} for image, " +
"this is an internal error, please report it to the library maintainers."
)
@Suppress("unused")
@OptIn(ExperimentalNativeApi::class)
val cValueCleaner = createCleaner(cValue) { ZXing_Image_delete(it) }
fun toImageView(): ImageView = ImageView(data, width, height, format)
}
@ExperimentalWriterApi
@OptIn(ExperimentalForeignApi::class)
fun CValuesRef<ZXing_Image>.toKObject(): Image = Image(this)
```
|
/content/code_sandbox/wrappers/kn/src/nativeMain/kotlin/zxingcpp/ImageView.kt
|
kotlin
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 666
|
```c
/*
*/
#include "ZXingC.h"
#include <stdio.h>
#include <stdlib.h>
#define STB_IMAGE_IMPLEMENTATION
#define STBI_NO_LINEAR // prevent dependency on -lm
#define STBI_NO_HDR
#include <stb_image.h>
int usage(char* pname)
{
fprintf(stderr, "Usage: %s FILE [FORMATS]\n", pname);
return 1;
}
bool parse_args(int argc, char** argv, char** filename, ZXing_BarcodeFormats* formats)
{
if (argc < 2)
return false;
*filename = argv[1];
if (argc >= 3) {
*formats = ZXing_BarcodeFormatsFromString(argv[2]);
if (*formats == ZXing_BarcodeFormat_Invalid) {
fprintf(stderr, "%s\n", ZXing_LastErrorMsg());
return false;
}
}
return true;
}
void printF(const char* fmt, char* text)
{
if (!text)
return;
if (*text)
printf(fmt, text);
ZXing_free(text);
}
#define CHECK(GOOD) \
if (!(GOOD)) { \
char* error = ZXing_LastErrorMsg(); \
fprintf(stderr, "CHECK(%s) failed: %s\n", #GOOD, error); \
ZXing_free(error); \
return 2; \
}
int main(int argc, char** argv)
{
int ret = 0;
char* filename = NULL;
ZXing_BarcodeFormats formats = ZXing_BarcodeFormat_None;
if (!parse_args(argc, argv, &filename, &formats))
return usage(argv[0]);
int width = 0;
int height = 0;
int channels = 0;
stbi_uc* data = stbi_load(filename, &width, &height, &channels, STBI_grey);
ZXing_ImageView* iv = NULL;
ZXing_Image* img = NULL;
if (data) {
iv = ZXing_ImageView_new(data, width, height, ZXing_ImageFormat_Lum, 0, 0);
CHECK(iv)
} else {
fprintf(stderr, "Could not read image '%s'\n", filename);
#if defined(ZXING_EXPERIMENTAL_API) && defined(ZXING_WRITERS)
if (formats == ZXing_BarcodeFormat_Invalid)
return 2;
fprintf(stderr, "Using '%s' as text input to create barcode\n", filename);
ZXing_CreatorOptions* cOpts = ZXing_CreatorOptions_new(formats);
CHECK(cOpts)
ZXing_Barcode* barcode = ZXing_CreateBarcodeFromText(filename, 0, cOpts);
CHECK(barcode)
img = ZXing_WriteBarcodeToImage(barcode, NULL);
CHECK(img)
ZXing_CreatorOptions_delete(cOpts);
ZXing_Barcode_delete(barcode);
#else
return 2;
#endif
}
ZXing_ReaderOptions* opts = ZXing_ReaderOptions_new();
ZXing_ReaderOptions_setTextMode(opts, ZXing_TextMode_HRI);
ZXing_ReaderOptions_setEanAddOnSymbol(opts, ZXing_EanAddOnSymbol_Ignore);
ZXing_ReaderOptions_setFormats(opts, formats);
ZXing_ReaderOptions_setReturnErrors(opts, true);
ZXing_Barcodes* barcodes = ZXing_ReadBarcodes(iv ? iv : (ZXing_ImageView*)img, opts);
CHECK(barcodes)
ZXing_ImageView_delete(iv);
ZXing_Image_delete(img);
ZXing_ReaderOptions_delete(opts);
stbi_image_free(data);
for (int i = 0, n = ZXing_Barcodes_size(barcodes); i < n; ++i) {
const ZXing_Barcode* barcode = ZXing_Barcodes_at(barcodes, i);
printF("Text : %s\n", ZXing_Barcode_text(barcode));
printF("BytesECI : %s\n", (char*)ZXing_Barcode_bytesECI(barcode, NULL));
printF("Format : %s\n", ZXing_BarcodeFormatToString(ZXing_Barcode_format(barcode)));
printF("Content : %s\n", ZXing_ContentTypeToString(ZXing_Barcode_contentType(barcode)));
printF("Identifier : %s\n", ZXing_Barcode_symbologyIdentifier(barcode));
printf("HasECI : %d\n", ZXing_Barcode_hasECI(barcode));
printF("EC Level : %s\n", ZXing_Barcode_ecLevel(barcode));
printF("Error : %s\n", ZXing_Barcode_errorMsg(barcode));
printF("Position : %s\n", ZXing_PositionToString(ZXing_Barcode_position(barcode)));
printf("Rotation : %d\n", ZXing_Barcode_orientation(barcode));
printf("IsMirrored : %d\n", ZXing_Barcode_isMirrored(barcode));
printf("IsInverted : %d\n", ZXing_Barcode_isInverted(barcode));
if (i < n-1)
printf("\n");
}
if (ZXing_Barcodes_size(barcodes) == 0)
printf("No barcode found\n");
ZXing_Barcodes_delete(barcodes);
return ret;
}
```
|
/content/code_sandbox/wrappers/c/ZXingCTest.c
|
c
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 1,138
|
```python
import sys
import zxingcpp
from PIL import Image
if len(sys.argv) < 3:
format, content = zxingcpp.BarcodeFormat.QRCode, "I have the best words."
else:
format, content = zxingcpp.barcode_format_from_str(sys.argv[1]), sys.argv[2]
# old writer API
img = zxingcpp.write_barcode(format, content, width=200, height=200)
Image.fromarray(img).save("test.png")
# new/experimental writer API
# barcode = zxingcpp.create_barcode(content, format, ec_level = "50%")
# img = barcode.to_image(size_hint = 500)
# Image.fromarray(img).save("test.png")
# svg = barcode.to_svg(with_hrt = True)
# with open("test.svg", "w") as svg_file:
# svg_file.write(svg)
```
|
/content/code_sandbox/wrappers/python/demo_writer.py
|
python
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 187
|
```cmake
macro(zxing_add_package_stb)
unset (STB_FOUND CACHE)
if (ZXING_DEPENDENCIES STREQUAL "AUTO")
find_package(PkgConfig)
pkg_check_modules (STB IMPORTED_TARGET stb)
elseif (ZXING_DEPENDENCIES STREQUAL "LOCAL")
find_package(PkgConfig REQUIRED)
pkg_check_modules (STB REQUIRED IMPORTED_TARGET stb)
endif()
if (NOT STB_FOUND)
include(FetchContent)
FetchContent_Declare (stb
GIT_REPOSITORY path_to_url
FetchContent_MakeAvailable (stb)
add_library(stb::stb INTERFACE IMPORTED)
target_include_directories(stb::stb INTERFACE ${stb_SOURCE_DIR})
else()
add_library(stb::stb ALIAS PkgConfig::STB)
endif()
endmacro()
macro(zxing_add_package name depname git_repo git_rev)
unset(${name}_FOUND CACHE) # see path_to_url#commitcomment-66464026
if (ZXING_DEPENDENCIES STREQUAL "AUTO")
find_package (${name} CONFIG)
elseif (ZXING_DEPENDENCIES STREQUAL "LOCAL")
find_package (${name} REQUIRED CONFIG)
endif()
if (NOT ${name}_FOUND)
include(FetchContent)
FetchContent_Declare (${depname}
GIT_REPOSITORY ${git_repo}
GIT_TAG ${git_rev})
if (${depname} STREQUAL "googletest")
# Prevent overriding the parent project's compiler/linker settings on Windows
set (gtest_force_shared_crt ON CACHE BOOL "" FORCE)
endif()
#FetchContent_MakeAvailable (${depname})
FetchContent_GetProperties(${depname})
if(NOT ${depname}_POPULATED)
FetchContent_Populate(${depname})
add_subdirectory(${${depname}_SOURCE_DIR} ${${depname}_BINARY_DIR} EXCLUDE_FROM_ALL) # prevent installing of dependencies
endif()
set (${name}_POPULATED TRUE) # this is supposed to be done in MakeAvailable but it seems not to?!?
endif()
endmacro()
```
|
/content/code_sandbox/wrappers/python/zxing.cmake
|
cmake
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 460
|
```python
import importlib.util
import unittest
import math
import platform
import zxingcpp
has_numpy = importlib.util.find_spec('numpy') is not None
has_pil = importlib.util.find_spec('PIL') is not None
has_cv2 = importlib.util.find_spec('cv2') is not None
BF = zxingcpp.BarcodeFormat
CT = zxingcpp.ContentType
class TestFormat(unittest.TestCase):
def test_format(self):
self.assertEqual(zxingcpp.barcode_format_from_str('qrcode'), BF.QRCode)
self.assertEqual(zxingcpp.barcode_formats_from_str('ITF, qrcode'), BF.ITF | BF.QRCode)
class TestReadWrite(unittest.TestCase):
def check_res(self, res, format, text):
self.assertTrue(res.valid)
self.assertEqual(res.format, format)
self.assertEqual(res.text, text)
self.assertEqual(res.bytes, bytes(text, 'utf-8'))
self.assertEqual(res.orientation, 0)
self.assertEqual(res.content_type, CT.Text)
def test_write_read_cycle(self):
format = BF.QRCode
text = "I have the best words."
img = zxingcpp.write_barcode(format, text)
res = zxingcpp.read_barcode(img)
self.check_res(res, format, text)
self.assertEqual(res.symbology_identifier, "]Q1")
# self.assertEqual(res.position.top_left.x, 4)
res = zxingcpp.read_barcode(img, formats=format)
self.check_res(res, format, text)
@unittest.skipIf(not hasattr(zxingcpp, 'create_barcode'), "skipping test for new create_barcode API")
def test_create_write_read_cycle(self):
format = BF.DataMatrix
text = "I have the best words."
img = zxingcpp.create_barcode(text, format).to_image()
res = zxingcpp.read_barcode(img)
self.check_res(res, format, text)
def test_write_read_oned_cycle(self):
format = BF.Code128
text = "I have the best words."
height = 50
width = 400
img = zxingcpp.write_barcode(format, text, width=width, height=height)
# self.assertEqual(img.shape[0], height)
# self.assertEqual(img.shape[1], width)
res = zxingcpp.read_barcode(img)
self.check_res(res, format, text)
# self.assertEqual(res.position.top_left.x, 61)
def test_write_read_multi_cycle(self):
format = BF.QRCode
text = "I have the best words."
img = zxingcpp.write_barcode(format, text)
res = zxingcpp.read_barcodes(img)[0]
self.check_res(res, format, text)
def test_write_read_bytes_cycle(self):
format = BF.QRCode
text = b"\1\2\3\4"
img = zxingcpp.write_barcode(format, text)
res = zxingcpp.read_barcode(img)
self.assertTrue(res.valid)
self.assertEqual(res.bytes, text)
self.assertEqual(res.content_type, CT.Binary)
@unittest.skipIf(not hasattr(zxingcpp, 'create_barcode'), "skipping test for new create_barcode API")
def test_create_write_read_bytes_cycle(self):
format = BF.DataMatrix
text = b"\1\2\3\4"
img = zxingcpp.create_barcode(text, format).to_image()
res = zxingcpp.read_barcode(img)
self.assertTrue(res.valid)
self.assertEqual(res.bytes, text)
self.assertEqual(res.content_type, CT.Binary)
@staticmethod
def zeroes(shape):
return memoryview(b"0" * math.prod(shape)).cast("B", shape=shape)
def test_failed_read_buffer(self):
res = zxingcpp.read_barcode(
self.zeroes((100, 100)), formats=BF.EAN8 | BF.Aztec, binarizer=zxingcpp.Binarizer.BoolCast
)
self.assertEqual(res, None)
@unittest.skipIf(not has_numpy, "need numpy for read/write tests")
def test_failed_read_numpy(self):
import numpy as np
res = zxingcpp.read_barcode(
np.zeros((100, 100), np.uint8), formats=BF.EAN8 | BF.Aztec, binarizer=zxingcpp.Binarizer.BoolCast
)
self.assertEqual(res, None)
def test_write_read_cycle_buffer(self):
format = BF.QRCode
text = "I have the best words."
img = zxingcpp.write_barcode(format, text)
self.check_res(zxingcpp.read_barcode(img), format, text)
@unittest.skipIf(not has_numpy or platform.system() == "Windows", "need numpy for read/write tests")
def test_write_read_cycle_numpy(self):
import numpy as np
format = BF.QRCode
text = "I have the best words."
img = zxingcpp.write_barcode(format, text, quiet_zone=10)
img = np.array(img)
self.check_res(zxingcpp.read_barcode(img), format, text)
self.check_res(zxingcpp.read_barcode(img[4:40,4:40]), format, text)
@unittest.skipIf(not has_pil, "need PIL for read/write tests")
def test_write_read_cycle_pil(self):
from PIL import Image
format = BF.QRCode
text = "I have the best words."
img = zxingcpp.write_barcode(format, text)
img = Image.fromarray(img, "L")
self.check_res(zxingcpp.read_barcode(img), format, text)
self.check_res(zxingcpp.read_barcode(img.convert("RGB")), format, text)
self.check_res(zxingcpp.read_barcode(img.convert("RGBA")), format, text)
self.check_res(zxingcpp.read_barcode(img.convert("1")), format, text)
self.check_res(zxingcpp.read_barcode(img.convert("CMYK")), format, text)
@unittest.skipIf(not has_cv2, "need cv2 for read/write tests")
def test_write_read_cycle_cv2(self):
import cv2, numpy
format = BF.QRCode
text = "I have the best words."
img = zxingcpp.write_barcode(format, text, quiet_zone=10)
img = cv2.cvtColor(numpy.array(img), cv2.COLOR_GRAY2BGR )
self.check_res(zxingcpp.read_barcode(img), format, text)
self.check_res(zxingcpp.read_barcode(img[4:40,4:40,:]), format, text)
def test_read_invalid_type(self):
self.assertRaisesRegex(
TypeError, "Invalid input: <class 'str'> does not support the buffer protocol.", zxingcpp.read_barcode, "foo"
)
def test_read_invalid_numpy_array_channels_buffer(self):
self.assertRaisesRegex(
ValueError, "Unsupported number of channels for buffer: 4", zxingcpp.read_barcode,
self.zeroes((100, 100, 4))
)
@unittest.skipIf(not has_numpy, "need numpy for read/write tests")
def test_read_invalid_numpy_array_channels_numpy(self):
import numpy as np
self.assertRaisesRegex(
ValueError, "Unsupported number of channels for buffer: 4", zxingcpp.read_barcode,
np.zeros((100, 100, 4), np.uint8)
)
if __name__ == '__main__':
unittest.main()
```
|
/content/code_sandbox/wrappers/python/test.py
|
python
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 1,623
|
```unknown
global-include CMakeLists.txt
include zxing.cpp
include zxing.cmake
graft core/
```
|
/content/code_sandbox/wrappers/python/MANIFEST.in
|
unknown
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 24
|
```python
import os
import platform
import subprocess
import sys
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext
# Adapted from here: path_to_url
class CMakeExtension(Extension):
def __init__(self, name, sourcedir=''):
Extension.__init__(self, name, sources=[])
self.sourcedir = os.path.abspath(sourcedir)
class CMakeBuild(build_ext):
def build_extension(self, ext):
extdir = os.path.abspath(os.path.dirname(self.get_ext_fullpath(ext.name)))
cmake_args = ['-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=' + extdir,
'-DPython3_EXECUTABLE=' + sys.executable,
'-DVERSION_INFO=' + self.distribution.get_version()]
cfg = 'Debug' if self.debug else 'Release'
build_args = ['--config', cfg,
'-j', '8']
if platform.system() == "Windows":
cmake_args += ['-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_{}={}'.format(cfg.upper(), extdir)]
if sys.maxsize > 2**32:
cmake_args += ['-A', 'x64']
else:
cmake_args += ['-A', 'Win32']
build_args += ['--', '/m']
else:
cmake_args += ['-DCMAKE_BUILD_TYPE=' + cfg]
if not os.path.exists(self.build_temp):
os.makedirs(self.build_temp)
subprocess.check_call(['cmake', ext.sourcedir] + cmake_args, cwd=self.build_temp)
subprocess.check_call(['cmake', '--build', '.'] + build_args, cwd=self.build_temp)
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setup(
name='zxing-cpp',
# setuptools_scm cannot be used because of the structure of the project until the following issues are solved:
# path_to_url
# path_to_url
# Because pip works on a copy of current directory in a temporary directory, the temporary directory does not hold
# the .git directory of the repo, so that setuptools_scm cannot guess the current version.
# use_scm_version={
# "root": "../..",
# "version_scheme": "guess-next-dev",
# "local_scheme": "no-local-version",
# "tag_regex": "v?([0-9]+.[0-9]+.[0-9]+)",
# },
version='2.2.0',
description='Python bindings for the zxing-cpp barcode library',
long_description=long_description,
long_description_content_type="text/markdown",
author='ZXing-C++ Community',
author_email='zxingcpp@gmail.com',
url='path_to_url
keywords=['barcode'],
classifiers=[
"Development Status :: 4 - Beta",
"Programming Language :: Python :: 3",
"Operating System :: OS Independent",
"Topic :: Multimedia :: Graphics",
],
python_requires=">=3.6",
ext_modules=[CMakeExtension('zxingcpp')],
cmdclass=dict(build_ext=CMakeBuild),
zip_safe=False,
)
```
|
/content/code_sandbox/wrappers/python/setup.py
|
python
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 673
|
```toml
[build-system]
requires = [
"setuptools>=42",
"setuptools_scm",
"wheel",
"cmake>=3.15",
"pybind11[global]",
]
build-backend = "setuptools.build_meta"
```
|
/content/code_sandbox/wrappers/python/pyproject.toml
|
toml
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 53
|
```python
import sys, zxingcpp
from PIL import Image
img = Image.open(sys.argv[1])
barcodes = zxingcpp.read_barcodes(img)
for barcode in barcodes:
print('Found barcode:'
f'\n Text: "{barcode.text}"'
f'\n Format: {barcode.format}'
f'\n Content: {barcode.content_type}'
f'\n Position: {barcode.position}')
if len(barcodes) == 0:
print("Could not find any barcode.")
```
|
/content/code_sandbox/wrappers/python/demo_reader.py
|
python
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 108
|
```toml
max_width = 135
hard_tabs = true
tab_spaces = 4
newline_style = "Auto"
use_small_heuristics = "Default"
fn_call_width = 100
attr_fn_like_width = 70
struct_lit_width = 18
struct_variant_width = 35
array_width = 100
chain_width = 100
single_line_if_else_max_width = 70
short_array_element_width_threshold = 10
fn_params_layout = "Tall"
edition = "2021"
```
|
/content/code_sandbox/wrappers/rust/rustfmt.toml
|
toml
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 107
|
```rust
use std::env;
fn main() -> miette::Result<()> {
if cfg!(feature = "bundled") {
// Builds the project in the directory located in `core`, installing it into $OUT_DIR
let mut dst = cmake::Config::new("core")
.define("BUILD_SHARED_LIBS", "OFF")
.define("ZXING_READERS", "ON")
.define("ZXING_WRITERS", "NEW")
.define("ZXING_EXPERIMENTAL_API", "ON")
.define("ZXING_C_API", "ON")
.define("ZXING_USE_BUNDLED_ZINT", "ON")
.define("CMAKE_CXX_STANDARD", "20")
.build();
dst.push("lib");
println!("cargo:rustc-link-search=native={}", dst.display());
println!("cargo:rustc-link-lib=static=ZXing");
if let Ok(target) = env::var("TARGET") {
if target.contains("apple") {
println!("cargo:rustc-link-lib=dylib=c++");
} else if target.contains("linux") {
println!("cargo:rustc-link-lib=dylib=stdc++");
}
}
} else if let Ok(lib_dir) = env::var("ZXING_CPP_LIB_DIR") {
println!("cargo:rustc-link-search=native={}", lib_dir);
println!("cargo:rustc-link-lib=dylib=ZXing");
} else {
// panic!("ZXing library not found. Use feature 'bundled' or set environment variabale ZXING_CPP_LIB_DIR.")
}
// manual bindings.rs generation:
// bindgen core/src/ZXingC.h -o src/bindings.rs --no-prepend-enum-name --merge-extern-blocks --use-core --no-doc-comments --no-layout-tests --with-derive-partialeq --allowlist-item "ZXing.*"
Ok(())
}
```
|
/content/code_sandbox/wrappers/rust/build.rs
|
rust
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 423
|
```rust
/*
*/
#[cfg(test)]
mod tests {
use crate::*;
#[test]
fn barcode_formats_from_str_valid() {
let formats = BarcodeFormats::from_str("qrcode,linearcodes").unwrap();
assert_eq!(formats, BarcodeFormat::QRCode | BarcodeFormat::LinearCodes);
}
#[test]
fn barcode_reader_new() {
let mut o1 = BarcodeReader::new();
assert_eq!(o1.get_formats(), BarcodeFormat::None);
assert_eq!(o1.get_try_harder(), true);
o1.set_formats(BarcodeFormat::EAN8);
assert_eq!(o1.get_formats(), BarcodeFormat::EAN8);
o1.set_try_harder(false);
assert_eq!(o1.get_try_harder(), false);
o1 = BarcodeReader::new().is_pure(true).text_mode(TextMode::Hex);
assert_eq!(o1.get_formats(), BarcodeFormat::None);
assert_eq!(o1.get_try_harder(), true);
assert_eq!(o1.get_is_pure(), true);
assert_eq!(o1.get_text_mode(), TextMode::Hex);
}
#[test]
fn barcode_creator_new() {
let mut o1 = BarcodeCreator::new(BarcodeFormat::QRCode);
assert_eq!(o1.get_reader_init(), false);
o1.set_reader_init(true);
assert_eq!(o1.get_reader_init(), true);
}
#[test]
#[should_panic]
fn barcode_formats_from_str_invalid() {
let _ = BarcodeFormats::from_str("qrcoder").unwrap();
}
#[test]
fn create_from_str() {
let str = "123456";
let res = create(BarcodeFormat::QRCode).ec_level("Q").from_str(str).unwrap();
assert_eq!(res.is_valid(), true);
assert_eq!(res.format(), BarcodeFormat::QRCode);
assert_eq!(res.text(), str);
assert_eq!(res.bytes(), str.as_bytes());
assert_eq!(res.has_eci(), false);
assert_eq!(res.content_type(), ContentType::Text);
assert!(matches!(res.error(), BarcodeError::None()));
assert_eq!(res.error().to_string(), "");
}
#[test]
fn create_from_slice() {
let data = [1, 2, 3, 4, 5];
let res = create(BarcodeFormat::QRCode).reader_init(true).from_slice(&data).unwrap();
assert_eq!(res.is_valid(), true);
assert_eq!(res.format(), BarcodeFormat::QRCode);
assert_eq!(res.bytes(), data);
assert_eq!(res.has_eci(), true);
// assert_eq!(res.reader_init(), true); // TODO
assert_eq!(res.content_type(), ContentType::Binary);
assert!(matches!(res.error(), BarcodeError::None()));
assert_eq!(res.error().to_string(), "");
}
#[test]
fn read_pure() {
let mut data = Vec::<u8>::new();
for v in your_sha256_hash110010100000".chars() {
data.push(if v == '0' { 255 } else { 0 });
}
let iv = ImageView::from_slice(&data, data.len(), 1, ImageFormat::Lum).unwrap();
let res = read().binarizer(Binarizer::BoolCast).from(&iv).unwrap();
let expected = "96385074";
assert_eq!(res.len(), 1);
assert_eq!(res[0].is_valid(), true);
assert_eq!(res[0].format(), BarcodeFormat::EAN8);
assert_eq!(res[0].text(), expected);
assert_eq!(res[0].bytes(), expected.as_bytes());
assert_eq!(res[0].has_eci(), false);
assert_eq!(res[0].content_type(), ContentType::Text);
assert_eq!(res[0].orientation(), 0);
assert_eq!(res[0].position().top_left, PointI { x: 4, y: 0 });
assert_eq!(res[0].line_count(), 1);
assert!(matches!(res[0].error(), BarcodeError::None()));
assert_eq!(res[0].error().to_string(), "");
}
}
```
|
/content/code_sandbox/wrappers/rust/src/tests.rs
|
rust
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 914
|
```c++
/*
*/
#include "BarcodeFormat.h"
// Reader
#include "ReadBarcode.h"
#include "ZXAlgorithms.h"
// Writer
#ifdef ZXING_EXPERIMENTAL_API
#include "WriteBarcode.h"
#else
#include "BitMatrix.h"
#include "Matrix.h"
#include "MultiFormatWriter.h"
#include <cstring>
#endif
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <optional>
#include <sstream>
#include <vector>
using namespace ZXing;
namespace py = pybind11;
using namespace pybind11::literals; // to bring in the `_a` literal
std::ostream& operator<<(std::ostream& os, const Position& points) {
for (const auto& p : points)
os << p.x << "x" << p.y << " ";
os.seekp(-1, os.cur);
os << '\0';
return os;
}
auto read_barcodes_impl(py::object _image, const BarcodeFormats& formats, bool try_rotate, bool try_downscale, TextMode text_mode,
Binarizer binarizer, bool is_pure, EanAddOnSymbol ean_add_on_symbol, bool return_errors,
uint8_t max_number_of_symbols = 0xff)
{
const auto opts = ReaderOptions()
.setFormats(formats)
.setTryRotate(try_rotate)
.setTryDownscale(try_downscale)
.setTextMode(text_mode)
.setBinarizer(binarizer)
.setIsPure(is_pure)
.setMaxNumberOfSymbols(max_number_of_symbols)
.setEanAddOnSymbol(ean_add_on_symbol)
.setReturnErrors(return_errors);
const auto _type = std::string(py::str(py::type::of(_image)));
py::buffer_info info;
ImageFormat imgfmt = ImageFormat::None;
try {
if (py::hasattr(_image, "__array_interface__")) {
if (_type.find("PIL.") != std::string::npos) {
_image.attr("load")();
const auto mode = _image.attr("mode").cast<std::string>();
if (mode == "L")
imgfmt = ImageFormat::Lum;
else if (mode == "RGB")
imgfmt = ImageFormat::RGB;
else if (mode == "RGBA")
imgfmt = ImageFormat::RGBA;
else {
// Unsupported mode in ImageFormat. Let's do conversion to L mode with PIL.
_image = _image.attr("convert")("L");
imgfmt = ImageFormat::Lum;
}
}
auto ai = _image.attr("__array_interface__").cast<py::dict>();
auto shape = ai["shape"].cast<std::vector<py::ssize_t>>();
auto typestr = ai["typestr"].cast<std::string>();
if (typestr != "|u1")
throw py::type_error("Incompatible __array_interface__ data type (" + typestr + "): expected a uint8_t array (|u1).");
if (ai.contains("data")) {
auto adata = ai["data"];
if (py::isinstance<py::buffer>(adata)) {
// PIL and our own __array_interface__ passes data as a buffer/bytes object
info = adata.cast<py::buffer>().request();
// PIL's bytes object has wrong dim/shape/strides info
if (info.ndim != Size(shape)) {
info.ndim = Size(shape);
info.shape = shape;
info.strides = py::detail::c_strides(shape, 1);
}
} else if (py::isinstance<py::tuple>(adata)) {
// numpy data is passed as a tuple
auto strides = py::detail::c_strides(shape, 1);
if (ai.contains("strides") && !ai["strides"].is_none())
strides = ai["strides"].cast<std::vector<py::ssize_t>>();
auto data_ptr = reinterpret_cast<void*>(adata.cast<py::tuple>()[0].cast<py::size_t>());
info = py::buffer_info(data_ptr, 1, "B", Size(shape), shape, strides);
} else {
throw py::type_error("No way to get data from __array_interface__");
}
} else {
info = _image.cast<py::buffer>().request();
}
} else {
info = _image.cast<py::buffer>().request();
}
#if PYBIND11_VERSION_HEX > 0x02080000 // py::raise_from is available starting from 2.8.0
} catch (py::error_already_set &e) {
py::raise_from(e, PyExc_TypeError, ("Invalid input: " + _type + " does not support the buffer protocol.").c_str());
throw py::error_already_set();
#endif
} catch (...) {
throw py::type_error("Invalid input: " + _type + " does not support the buffer protocol.");
}
if (info.format != py::format_descriptor<uint8_t>::format())
throw py::type_error("Incompatible buffer format '" + info.format + "': expected a uint8_t array.");
if (info.ndim != 2 && info.ndim != 3)
throw py::type_error("Incompatible buffer dimension " + std::to_string(info.ndim) + " (needs to be 2 or 3).");
const auto height = narrow_cast<int>(info.shape[0]);
const auto width = narrow_cast<int>(info.shape[1]);
const auto channels = info.ndim == 2 ? 1 : narrow_cast<int>(info.shape[2]);
const auto rowStride = narrow_cast<int>(info.strides[0]);
const auto pixStride = narrow_cast<int>(info.strides[1]);
if (imgfmt == ImageFormat::None) {
// Assume grayscale or BGR image depending on channels number
if (channels == 1)
imgfmt = ImageFormat::Lum;
else if (channels == 3)
imgfmt = ImageFormat::BGR;
else
throw py::value_error("Unsupported number of channels for buffer: " + std::to_string(channels));
}
const auto bytes = static_cast<uint8_t*>(info.ptr);
// Disables the GIL during zxing processing (restored automatically upon completion)
py::gil_scoped_release release;
return ReadBarcodes({bytes, width, height, imgfmt, rowStride, pixStride}, opts);
}
std::optional<Barcode> read_barcode(py::object _image, const BarcodeFormats& formats, bool try_rotate, bool try_downscale,
TextMode text_mode, Binarizer binarizer, bool is_pure, EanAddOnSymbol ean_add_on_symbol,
bool return_errors)
{
auto res = read_barcodes_impl(_image, formats, try_rotate, try_downscale, text_mode, binarizer, is_pure, ean_add_on_symbol,
return_errors, 1);
return res.empty() ? std::nullopt : std::optional(res.front());
}
Barcodes read_barcodes(py::object _image, const BarcodeFormats& formats, bool try_rotate, bool try_downscale, TextMode text_mode,
Binarizer binarizer, bool is_pure, EanAddOnSymbol ean_add_on_symbol, bool return_errors)
{
return read_barcodes_impl(_image, formats, try_rotate, try_downscale, text_mode, binarizer, is_pure, ean_add_on_symbol,
return_errors);
}
#ifdef ZXING_EXPERIMENTAL_API
Barcode create_barcode(py::object content, BarcodeFormat format, std::string ec_level)
{
auto cOpts = CreatorOptions(format).ecLevel(ec_level);
auto data = py::cast<std::string>(content);
if (py::isinstance<py::str>(content))
return CreateBarcodeFromText(data, cOpts);
else if (py::isinstance<py::bytes>(content))
return CreateBarcodeFromBytes(data, cOpts);
else
throw py::type_error("Invalid input: only 'str' and 'bytes' supported.");
}
Image write_barcode_to_image(Barcode barcode, int size_hint, bool with_hrt, bool with_quiet_zones)
{
return WriteBarcodeToImage(barcode, WriterOptions().sizeHint(size_hint).withHRT(with_hrt).withQuietZones(with_quiet_zones));
}
std::string write_barcode_to_svg(Barcode barcode, int size_hint, bool with_hrt, bool with_quiet_zones)
{
return WriteBarcodeToSVG(barcode, WriterOptions().sizeHint(size_hint).withHRT(with_hrt).withQuietZones(with_quiet_zones));
}
#endif
Image write_barcode(BarcodeFormat format, py::object content, int width, int height, int quiet_zone, int ec_level)
{
#ifdef ZXING_EXPERIMENTAL_API
auto barcode = create_barcode(content, format, std::to_string(ec_level));
return write_barcode_to_image(barcode, std::max(width, height), false, quiet_zone != 0);
#else
CharacterSet encoding [[maybe_unused]];
if (py::isinstance<py::str>(content))
encoding = CharacterSet::UTF8;
else if (py::isinstance<py::bytes>(content))
encoding = CharacterSet::BINARY;
else
throw py::type_error("Invalid input: only 'str' and 'bytes' supported.");
auto writer = MultiFormatWriter(format).setEncoding(encoding).setMargin(quiet_zone).setEccLevel(ec_level);
auto bits = writer.encode(py::cast<std::string>(content), width, height);
auto bitmap = ToMatrix<uint8_t>(bits);
Image res(bitmap.width(), bitmap.height());
memcpy(const_cast<uint8_t*>(res.data()), bitmap.data(), bitmap.size());
return res;
#endif
}
PYBIND11_MODULE(zxingcpp, m)
{
m.doc() = "python bindings for zxing-cpp";
// forward declaration of BarcodeFormats to fix BarcodeFormat function header typings
// see path_to_url
py::class_<BarcodeFormats> pyBarcodeFormats(m, "BarcodeFormats");
py::enum_<BarcodeFormat>(m, "BarcodeFormat", py::arithmetic{}, "Enumeration of zxing supported barcode formats")
.value("Aztec", BarcodeFormat::Aztec)
.value("Codabar", BarcodeFormat::Codabar)
.value("Code39", BarcodeFormat::Code39)
.value("Code93", BarcodeFormat::Code93)
.value("Code128", BarcodeFormat::Code128)
.value("DataMatrix", BarcodeFormat::DataMatrix)
.value("EAN8", BarcodeFormat::EAN8)
.value("EAN13", BarcodeFormat::EAN13)
.value("ITF", BarcodeFormat::ITF)
.value("MaxiCode", BarcodeFormat::MaxiCode)
.value("PDF417", BarcodeFormat::PDF417)
.value("QRCode", BarcodeFormat::QRCode)
.value("MicroQRCode", BarcodeFormat::MicroQRCode)
.value("RMQRCode", BarcodeFormat::RMQRCode)
.value("DataBar", BarcodeFormat::DataBar)
.value("DataBarExpanded", BarcodeFormat::DataBarExpanded)
.value("DXFilmEdge", BarcodeFormat::DXFilmEdge)
.value("UPCA", BarcodeFormat::UPCA)
.value("UPCE", BarcodeFormat::UPCE)
// use upper case 'NONE' because 'None' is a reserved identifier in python
.value("NONE", BarcodeFormat::None)
.value("LinearCodes", BarcodeFormat::LinearCodes)
.value("MatrixCodes", BarcodeFormat::MatrixCodes)
.export_values()
// see path_to_url
.def("__or__", [](BarcodeFormat f1, BarcodeFormat f2){ return f1 | f2; });
pyBarcodeFormats
.def("__repr__", py::overload_cast<BarcodeFormats>(static_cast<std::string(*)(BarcodeFormats)>(ToString)))
.def("__str__", py::overload_cast<BarcodeFormats>(static_cast<std::string(*)(BarcodeFormats)>(ToString)))
.def("__eq__", [](BarcodeFormats f1, BarcodeFormats f2){ return f1 == f2; })
.def("__or__", [](BarcodeFormats fs, BarcodeFormat f){ return fs | f; })
.def(py::init<BarcodeFormat>());
py::implicitly_convertible<BarcodeFormat, BarcodeFormats>();
py::enum_<Binarizer>(m, "Binarizer", "Enumeration of binarizers used before decoding images")
.value("BoolCast", Binarizer::BoolCast)
.value("FixedThreshold", Binarizer::FixedThreshold)
.value("GlobalHistogram", Binarizer::GlobalHistogram)
.value("LocalAverage", Binarizer::LocalAverage)
.export_values();
py::enum_<EanAddOnSymbol>(m, "EanAddOnSymbol", "Enumeration of options for EAN-2/5 add-on symbols check")
.value("Ignore", EanAddOnSymbol::Ignore, "Ignore any Add-On symbol during read/scan")
.value("Read", EanAddOnSymbol::Read, "Read EAN-2/EAN-5 Add-On symbol if found")
.value("Require", EanAddOnSymbol::Require, "Require EAN-2/EAN-5 Add-On symbol to be present")
.export_values();
py::enum_<ContentType>(m, "ContentType", "Enumeration of content types")
.value("Text", ContentType::Text)
.value("Binary", ContentType::Binary)
.value("Mixed", ContentType::Mixed)
.value("GS1", ContentType::GS1)
.value("ISO15434", ContentType::ISO15434)
.value("UnknownECI", ContentType::UnknownECI)
.export_values();
py::enum_<TextMode>(m, "TextMode", "")
.value("Plain", TextMode::Plain, "bytes() transcoded to unicode based on ECI info or guessed charset (the default mode prior to 2.0)")
.value("ECI", TextMode::ECI, "standard content following the ECI protocol with every character set ECI segment transcoded to unicode")
.value("HRI", TextMode::HRI, "Human Readable Interpretation (dependent on the ContentType)")
.value("Hex", TextMode::Hex, "bytes() transcoded to ASCII string of HEX values")
.value("Escaped", TextMode::Escaped, "Use the EscapeNonGraphical() function (e.g. ASCII 29 will be transcoded to '<GS>'")
.export_values();
py::class_<PointI>(m, "Point", "Represents the coordinates of a point in an image")
.def_readonly("x", &PointI::x,
":return: horizontal coordinate of the point\n"
":rtype: int")
.def_readonly("y", &PointI::y,
":return: vertical coordinate of the point\n"
":rtype: int");
py::class_<Position>(m, "Position", "The position of a decoded symbol")
.def_property_readonly("top_left", &Position::topLeft,
":return: coordinate of the symbol's top-left corner\n"
":rtype: zxingcpp.Point")
.def_property_readonly("top_right", &Position::topRight,
":return: coordinate of the symbol's top-right corner\n"
":rtype: zxingcpp.Point")
.def_property_readonly("bottom_left", &Position::bottomLeft,
":return: coordinate of the symbol's bottom-left corner\n"
":rtype: zxingcpp.Point")
.def_property_readonly("bottom_right", &Position::bottomRight,
":return: coordinate of the symbol's bottom-right corner\n"
":rtype: zxingcpp.Point")
.def("__str__", [](Position pos) {
std::ostringstream oss;
oss << pos;
return oss.str();
});
py::enum_<Error::Type>(m, "ErrorType", "")
.value("None", Error::Type::None, "No error")
.value("Format", Error::Type::Format, "Data format error")
.value("Checksum", Error::Type::Checksum, "Checksum error")
.value("Unsupported", Error::Type::Unsupported, "Unsupported content error")
.export_values();
py::class_<Error>(m, "Error", "Barcode reading error")
.def_property_readonly("type", &Error::type,
":return: Error type\n"
":rtype: zxingcpp.ErrorType")
.def_property_readonly("message", &Error::msg,
":return: Error message\n"
":rtype: str")
.def("__str__", [](Error e) { return ToString(e); });
py::class_<Barcode>(m, "Barcode", "The Barcode class")
.def_property_readonly("valid", &Barcode::isValid,
":return: whether or not barcode is valid (i.e. a symbol was found and decoded)\n"
":rtype: bool")
.def_property_readonly("text", [](const Barcode& res) { return res.text(); },
":return: text of the decoded symbol (see also TextMode parameter)\n"
":rtype: str")
.def_property_readonly("bytes", [](const Barcode& res) { return py::bytes(res.bytes().asString()); },
":return: uninterpreted bytes of the decoded symbol\n"
":rtype: bytes")
.def_property_readonly("format", &Barcode::format,
":return: decoded symbol format\n"
":rtype: zxingcpp.BarcodeFormat")
.def_property_readonly("symbology_identifier", &Barcode::symbologyIdentifier,
":return: decoded symbology idendifier\n"
":rtype: str")
.def_property_readonly("ec_level", &Barcode::ecLevel,
":return: error correction level of the symbol (empty string if not applicable)\n"
":rtype: str")
.def_property_readonly("content_type", &Barcode::contentType,
":return: content type of symbol\n"
":rtype: zxingcpp.ContentType")
.def_property_readonly("position", &Barcode::position,
":return: position of the decoded symbol\n"
":rtype: zxingcpp.Position")
.def_property_readonly("orientation", &Barcode::orientation,
":return: orientation (in degree) of the decoded symbol\n"
":rtype: int")
.def_property_readonly(
"error", [](const Barcode& res) { return res.error() ? std::optional(res.error()) : std::nullopt; },
":return: Error code or None\n"
":rtype: zxingcpp.Error")
#ifdef ZXING_EXPERIMENTAL_API
.def("to_image", &write_barcode_to_image,
py::arg("size_hint") = 0,
py::arg("with_hrt") = false,
py::arg("with_quiet_zones") = true)
.def("to_svg", &write_barcode_to_svg,
py::arg("size_hint") = 0,
py::arg("with_hrt") = false,
py::arg("with_quiet_zones") = true)
#endif
;
m.attr("Result") = m.attr("Barcode"); // alias to deprecated name for the Barcode class
m.def("barcode_format_from_str", &BarcodeFormatFromString,
py::arg("str"),
"Convert string to BarcodeFormat\n\n"
":type str: str\n"
":param str: string representing barcode format\n"
":return: corresponding barcode format\n"
":rtype: zxingcpp.BarcodeFormat");
m.def("barcode_formats_from_str", &BarcodeFormatsFromString,
py::arg("str"),
"Convert string to BarcodeFormats\n\n"
":type str: str\n"
":param str: string representing a list of barcodes formats\n"
":return: corresponding barcode formats\n"
":rtype: zxingcpp.BarcodeFormats");
m.def("read_barcode", &read_barcode,
py::arg("image"),
py::arg("formats") = BarcodeFormats{},
py::arg("try_rotate") = true,
py::arg("try_downscale") = true,
py::arg("text_mode") = TextMode::HRI,
py::arg("binarizer") = Binarizer::LocalAverage,
py::arg("is_pure") = false,
py::arg("ean_add_on_symbol") = EanAddOnSymbol::Ignore,
py::arg("return_errors") = false,
"Read (decode) a barcode from a numpy BGR or grayscale image array or from a PIL image.\n\n"
":type image: buffer|numpy.ndarray|PIL.Image.Image\n"
":param image: The image object to decode. The image can be either:\n"
" - a buffer with the correct shape, use .cast on memory view to convert\n"
" - a numpy array containing image either in grayscale (1 byte per pixel) or BGR mode (3 bytes per pixel)\n"
" - a PIL Image\n"
":type formats: zxing.BarcodeFormat|zxing.BarcodeFormats\n"
":param formats: the format(s) to decode. If ``None``, decode all formats.\n"
":type try_rotate: bool\n"
":param try_rotate: if ``True`` (the default), decoder searches for barcodes in any direction; \n"
" if ``False``, it will not search for 90 / 270 rotated barcodes.\n"
":type try_downscale: bool\n"
":param try_downscale: if ``True`` (the default), decoder also scans downscaled versions of the input; \n"
" if ``False``, it will only search in the resolution provided.\n"
":type text_mode: zxing.TextMode\n"
":param text_mode: specifies the TextMode that governs how the raw bytes content is transcoded to text.\n"
" Defaults to :py:attr:`zxing.TextMode.HRI`."
":type binarizer: zxing.Binarizer\n"
":param binarizer: the binarizer used to convert image before decoding barcodes.\n"
" Defaults to :py:attr:`zxing.Binarizer.LocalAverage`."
":type is_pure: bool\n"
":param is_pure: Set to True if the input contains nothing but a perfectly aligned barcode (generated image).\n"
" Speeds up detection in that case. Default is False."
":type ean_add_on_symbol: zxing.EanAddOnSymbol\n"
":param ean_add_on_symbol: Specify whether to Ignore, Read or Require EAN-2/5 add-on symbols while scanning \n"
" EAN/UPC codes. Default is ``Ignore``.\n"
":type return_errors: bool\n"
":param return_errors: Set to True to return the barcodes with errors as well (e.g. checksum errors); see ``Barcode.error``.\n"
" Default is False."
":rtype: zxingcpp.Barcode\n"
":return: a Barcode if found, None otherwise"
);
m.def("read_barcodes", &read_barcodes,
py::arg("image"),
py::arg("formats") = BarcodeFormats{},
py::arg("try_rotate") = true,
py::arg("try_downscale") = true,
py::arg("text_mode") = TextMode::HRI,
py::arg("binarizer") = Binarizer::LocalAverage,
py::arg("is_pure") = false,
py::arg("ean_add_on_symbol") = EanAddOnSymbol::Ignore,
py::arg("return_errors") = false,
"Read (decode) multiple barcodes from a numpy BGR or grayscale image array or from a PIL image.\n\n"
":type image: buffer|numpy.ndarray|PIL.Image.Image\n"
":param image: The image object to decode. The image can be either:\n"
" - a buffer with the correct shape, use .cast on memory view to convert\n"
" - a numpy array containing image either in grayscale (1 byte per pixel) or BGR mode (3 bytes per pixel)\n"
" - a PIL Image\n"
":type formats: zxing.BarcodeFormat|zxing.BarcodeFormats\n"
":param formats: the format(s) to decode. If ``None``, decode all formats.\n"
":type try_rotate: bool\n"
":param try_rotate: if ``True`` (the default), decoder searches for barcodes in any direction; \n"
" if ``False``, it will not search for 90 / 270 rotated barcodes.\n"
":type try_downscale: bool\n"
":param try_downscale: if ``True`` (the default), decoder also scans downscaled versions of the input; \n"
" if ``False``, it will only search in the resolution provided.\n"
":type text_mode: zxing.TextMode\n"
":param text_mode: specifies the TextMode that governs how the raw bytes content is transcoded to text.\n"
" Defaults to :py:attr:`zxing.TextMode.HRI`."
":type binarizer: zxing.Binarizer\n"
":param binarizer: the binarizer used to convert image before decoding barcodes.\n"
" Defaults to :py:attr:`zxing.Binarizer.LocalAverage`."
":type is_pure: bool\n"
":param is_pure: Set to True if the input contains nothing but a perfectly aligned barcode (generated image).\n"
" Speeds up detection in that case. Default is False."
":type ean_add_on_symbol: zxing.EanAddOnSymbol\n"
":param ean_add_on_symbol: Specify whether to Ignore, Read or Require EAN-2/5 add-on symbols while scanning \n"
" EAN/UPC codes. Default is ``Ignore``.\n"
":type return_errors: bool\n"
":param return_errors: Set to True to return the barcodes with errors as well (e.g. checksum errors); see ``Barcode.error``.\n"
" Default is False.\n"
":rtype: list[zxingcpp.Barcode]\n"
":return: a list of Barcodes, the list is empty if none is found"
);
py::class_<Image>(m, "Image", py::buffer_protocol())
.def_property_readonly(
"__array_interface__",
[](const Image& m) {
return py::dict("version"_a = 3, "data"_a = m, "shape"_a = py::make_tuple(m.height(), m.width()), "typestr"_a = "|u1");
})
.def_property_readonly("shape", [](const Image& m) { return py::make_tuple(m.height(), m.width()); })
.def_buffer([](const Image& m) -> py::buffer_info {
return {
const_cast<uint8_t*>(m.data()), // Pointer to buffer
sizeof(uint8_t), // Size of one scalar
py::format_descriptor<uint8_t>::format(), // Python struct-style format descriptor
2, // Number of dimensions
{m.height(), m.width()}, // Buffer dimensions
{m.rowStride(), m.pixStride()}, // Strides (in bytes) for each index
true // read-only
};
});
#ifdef ZXING_EXPERIMENTAL_API
m.def("create_barcode", &create_barcode,
py::arg("content"),
py::arg("format"),
py::arg("ec_level") = ""
);
m.def("write_barcode_to_image", &write_barcode_to_image,
py::arg("barcode"),
py::arg("size_hint") = 0,
py::arg("with_hrt") = false,
py::arg("with_quiet_zones") = true
);
m.def("write_barcode_to_svg", &write_barcode_to_svg,
py::arg("barcode"),
py::arg("size_hint") = 0,
py::arg("with_hrt") = false,
py::arg("with_quiet_zones") = true
);
#endif
m.attr("Bitmap") = m.attr("Image"); // alias to deprecated name for the Image class
m.def("write_barcode", &write_barcode,
py::arg("format"),
py::arg("text"),
py::arg("width") = 0,
py::arg("height") = 0,
py::arg("quiet_zone") = -1,
py::arg("ec_level") = -1,
"Write (encode) a text into a barcode and return 8-bit grayscale bitmap buffer\n\n"
":type format: zxing.BarcodeFormat\n"
":param format: format of the barcode to create\n"
":type text: str|bytes\n"
":param text: the text/content of the barcode. A str is encoded as utf8 text and bytes as binary data\n"
":type width: int\n"
":param width: width (in pixels) of the barcode to create. If undefined (or set to 0), barcode will be\n"
" created with the minimum possible width\n"
":type height: int\n"
":param height: height (in pixels) of the barcode to create. If undefined (or set to 0), barcode will be\n"
" created with the minimum possible height\n"
":type quiet_zone: int\n"
":param quiet_zone: minimum size (in pixels) of the quiet zone around barcode. If undefined (or set to -1), \n"
" the minimum quiet zone of respective barcode is used."
":type ec_level: int\n"
":param ec_level: error correction level of the barcode (Used for Aztec, PDF417, and QRCode only).\n"
":rtype: zxingcpp.Bitmap\n"
);
}
```
|
/content/code_sandbox/wrappers/python/zxing.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 6,750
|
```rust
/*
*/
#![allow(unknown_lints)] // backward compatibility
#![allow(unused_unsafe)]
#![allow(clippy::useless_transmute)]
#![allow(clippy::redundant_closure_call)]
#![allow(clippy::missing_transmute_annotations)] // introduced in 1.79
mod tests;
#[allow(dead_code)]
#[allow(non_camel_case_types)]
#[allow(non_snake_case)]
#[allow(non_upper_case_globals)]
mod bindings {
include!("bindings.rs");
}
use bindings::*;
use flagset::{flags, FlagSet};
use paste::paste;
use std::ffi::{c_char, c_int, c_uint, c_void, CStr, CString, NulError};
use std::fmt::{Display, Formatter};
use std::marker::PhantomData;
use std::mem::transmute;
use std::rc::Rc;
use thiserror::Error;
#[derive(Error, Debug)]
pub enum Error {
#[error("{0}")]
InvalidInput(String),
#[error("NulError from CString::new")]
NulError(#[from] NulError),
//
// #[error("data store disconnected")]
// IOError(#[from] std::io::Error),
// #[error("the data for key `{0}` is not available")]
// Redaction(String),
// #[error("invalid header (expected {expected:?}, found {found:?})")]
// InvalidHeader {
// expected: String,
// found: String,
// },
// #[error("unknown data store error")]
// Unknown,
}
// see path_to_url
impl From<std::convert::Infallible> for Error {
fn from(_: std::convert::Infallible) -> Self {
unreachable!()
}
}
fn c2r_str(str: *mut c_char) -> String {
let mut res = String::new();
if !str.is_null() {
unsafe { res = CStr::from_ptr(str).to_string_lossy().to_string() };
unsafe { ZXing_free(str as *mut c_void) };
}
res
}
fn c2r_vec(buf: *mut u8, len: c_int) -> Vec<u8> {
let mut res = Vec::<u8>::new();
if !buf.is_null() && len > 0 {
unsafe { res = std::slice::from_raw_parts(buf, len as usize).to_vec() };
unsafe { ZXing_free(buf as *mut c_void) };
}
res
}
fn last_error() -> Error {
match unsafe { ZXing_LastErrorMsg().as_mut() } {
None => panic!("Internal error: ZXing_LastErrorMsg() returned NULL"),
Some(error) => Error::InvalidInput(c2r_str(error)),
}
}
macro_rules! last_error_or {
($expr:expr) => {
match unsafe { ZXing_LastErrorMsg().as_mut() } {
None => Ok($expr),
Some(error) => Err(Error::InvalidInput(c2r_str(error))),
}
};
}
macro_rules! last_error_if_null_or {
($ptr:ident, $expr:expr) => {
match $ptr.is_null() {
true => Err(last_error()),
false => Ok($expr),
}
};
}
macro_rules! make_zxing_class {
($r_class:ident, $c_class:ident) => {
paste! {
pub struct $r_class(*mut $c_class);
impl Drop for $r_class {
fn drop(&mut self) {
unsafe { [<$c_class _delete>](self.0) }
}
}
}
};
}
macro_rules! make_zxing_class_with_default {
($r_class:ident, $c_class:ident) => {
make_zxing_class!($r_class, $c_class);
paste! {
impl $r_class {
pub fn new() -> Self {
unsafe { $r_class([<$c_class _new>]()) }
}
}
impl Default for $r_class {
fn default() -> Self {
Self::new()
}
}
}
};
}
macro_rules! getter {
($class:ident, $c_name:ident, $r_name:ident, $conv:expr, $type:ty) => {
pub fn $r_name(&self) -> $type {
paste! { unsafe { $conv([<ZXing_ $class _ $c_name>](self.0)) } }
}
};
($class:ident, $c_name:ident, $conv:expr, $type:ty) => {
paste! { getter! { $class, $c_name, [<$c_name:snake>], $conv, $type } }
};
}
macro_rules! property {
($class:ident, $c_name:ident, $r_name:ident, String) => {
pub fn $r_name(self, v: impl AsRef<str>) -> Self {
let cstr = CString::new(v.as_ref()).unwrap();
paste! { unsafe { [<ZXing_ $class _set $c_name>](self.0, cstr.as_ptr()) } };
self
}
paste! {
pub fn [<set_ $r_name>](&mut self, v : impl AsRef<str>) -> &mut Self {
let cstr = CString::new(v.as_ref()).unwrap();
unsafe { [<ZXing_ $class _set $c_name>](self.0, cstr.as_ptr()) };
self
}
pub fn [<get_ $r_name>](&self) -> String {
unsafe { c2r_str([<ZXing_ $class _get $c_name>](self.0)) }
}
}
};
($class:ident, $c_name:ident, $r_name:ident, $type:ty) => {
pub fn $r_name(self, v: impl Into<$type>) -> Self {
paste! { unsafe { [<ZXing_ $class _set $c_name>](self.0, transmute(v.into())) } };
self
}
paste! {
pub fn [<set_ $r_name>](&mut self, v : impl Into<$type>) -> &mut Self {
unsafe { [<ZXing_ $class _set $c_name>](self.0, transmute(v.into())) };
self
}
pub fn [<get_ $r_name>](&self) -> $type {
unsafe { transmute([<ZXing_ $class _get $c_name>](self.0)) }
}
}
};
($class:ident, $c_name:ident, $type:ty) => {
paste! { property! { $class, $c_name, [<$c_name:snake>], $type } }
};
}
macro_rules! make_zxing_enum {
($name:ident { $($field:ident),* }) => {
#[repr(u32)]
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum $name {
$($field = paste! { [<ZXing_ $name _ $field>] },)*
}
}
}
macro_rules! make_zxing_flags {
($name:ident { $($field:ident),* }) => {
flags! {
#[repr(u32)]
pub enum $name: c_uint {
$($field = paste! { [<ZXing_ $name _ $field>] },)*
}
}
}
}
#[rustfmt::skip] // workaround for broken #[rustfmt::skip::macros(make_zxing_enum)]
make_zxing_enum!(ImageFormat { Lum, LumA, RGB, BGR, RGBA, ARGB, BGRA, ABGR });
#[rustfmt::skip]
make_zxing_enum!(ContentType { Text, Binary, Mixed, GS1, ISO15434, UnknownECI });
#[rustfmt::skip]
make_zxing_enum!(Binarizer { LocalAverage, GlobalHistogram, FixedThreshold, BoolCast });
#[rustfmt::skip]
make_zxing_enum!(TextMode { Plain, ECI, HRI, Hex, Escaped });
#[rustfmt::skip]
make_zxing_enum!(EanAddOnSymbol { Ignore, Read, Require });
#[rustfmt::skip]
make_zxing_flags!(BarcodeFormat {
None, Aztec, Codabar, Code39, Code93, Code128, DataBar, DataBarExpanded, DataMatrix, EAN8, EAN13, ITF,
MaxiCode, PDF417, QRCode, UPCA, UPCE, MicroQRCode, RMQRCode, DXFilmEdge, LinearCodes, MatrixCodes, Any
});
impl Display for BarcodeFormat {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", unsafe { c2r_str(ZXing_BarcodeFormatToString(BarcodeFormats::from(*self).bits())) })
}
}
impl Display for ContentType {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", unsafe { c2r_str(ZXing_ContentTypeToString(transmute(*self))) })
}
}
pub type BarcodeFormats = FlagSet<BarcodeFormat>;
pub trait FromStr: Sized {
fn from_str(str: impl AsRef<str>) -> Result<Self, Error>;
}
impl FromStr for BarcodeFormat {
fn from_str(str: impl AsRef<str>) -> Result<BarcodeFormat, Error> {
let cstr = CString::new(str.as_ref())?;
let res = unsafe { BarcodeFormats::new_unchecked(ZXing_BarcodeFormatFromString(cstr.as_ptr())) };
match res.bits() {
u32::MAX => last_error_or!(BarcodeFormat::None),
_ => Ok(res.into_iter().last().unwrap()),
}
}
}
impl FromStr for BarcodeFormats {
fn from_str(str: impl AsRef<str>) -> Result<BarcodeFormats, Error> {
let cstr = CString::new(str.as_ref())?;
let res = unsafe { BarcodeFormats::new_unchecked(ZXing_BarcodeFormatsFromString(cstr.as_ptr())) };
match res.bits() {
u32::MAX => last_error_or!(BarcodeFormats::default()),
0 => Ok(BarcodeFormats::full()),
_ => Ok(res),
}
}
}
#[derive(Debug, PartialEq)]
struct ImageViewOwner<'a>(*mut ZXing_ImageView, PhantomData<&'a u8>);
impl Drop for ImageViewOwner<'_> {
fn drop(&mut self) {
unsafe { ZXing_ImageView_delete(self.0) }
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct ImageView<'a>(Rc<ImageViewOwner<'a>>);
impl<'a> From<&'a ImageView<'a>> for ImageView<'a> {
fn from(img: &'a ImageView) -> Self {
img.clone()
}
}
impl<'a> ImageView<'a> {
fn try_into_int<T: TryInto<c_int>>(val: T) -> Result<c_int, Error> {
val.try_into().map_err(|_| Error::InvalidInput("Could not convert Integer into c_int.".to_string()))
}
/// Constructs an ImageView from a raw pointer and the width/height (in pixels)
/// and row_stride/pix_stride (in bytes).
///
/// # Safety
///
/// The memory gets accessed inside the c++ library at random places between
/// `ptr` and `ptr + height * row_stride` or `ptr + width * pix_stride`.
/// Note that both the stride values could be negative, e.g. if the image
/// view is rotated.
pub unsafe fn from_ptr<T: TryInto<c_int>, U: TryInto<c_int>>(
ptr: *const u8,
width: T,
height: T,
format: ImageFormat,
row_stride: U,
pix_stride: U,
) -> Result<Self, Error> {
let iv = ZXing_ImageView_new(
ptr,
Self::try_into_int(width)?,
Self::try_into_int(height)?,
format as ZXing_ImageFormat,
Self::try_into_int(row_stride)?,
Self::try_into_int(pix_stride)?,
);
last_error_if_null_or!(iv, ImageView(Rc::new(ImageViewOwner(iv, PhantomData))))
}
pub fn from_slice<T: TryInto<c_int>>(data: &'a [u8], width: T, height: T, format: ImageFormat) -> Result<Self, Error> {
unsafe {
let iv = ZXing_ImageView_new_checked(
data.as_ptr(),
data.len() as c_int,
Self::try_into_int(width)?,
Self::try_into_int(height)?,
format as ZXing_ImageFormat,
0,
0,
);
last_error_if_null_or!(iv, ImageView(Rc::new(ImageViewOwner(iv, PhantomData))))
}
}
pub fn cropped(self, left: i32, top: i32, width: i32, height: i32) -> Self {
unsafe { ZXing_ImageView_crop((self.0).0, left, top, width, height) }
self
}
pub fn rotated(self, degree: i32) -> Self {
unsafe { ZXing_ImageView_rotate((self.0).0, degree) }
self
}
}
#[cfg(feature = "image")]
use image;
#[cfg(feature = "image")]
impl<'a> From<&'a image::GrayImage> for ImageView<'a> {
fn from(img: &'a image::GrayImage) -> Self {
ImageView::from_slice(img.as_ref(), img.width(), img.height(), ImageFormat::Lum).unwrap()
}
}
#[cfg(feature = "image")]
impl<'a> TryFrom<&'a image::DynamicImage> for ImageView<'a> {
type Error = Error;
fn try_from(img: &'a image::DynamicImage) -> Result<Self, Error> {
let format = match img {
image::DynamicImage::ImageLuma8(_) => Some(ImageFormat::Lum),
image::DynamicImage::ImageLumaA8(_) => Some(ImageFormat::LumA),
image::DynamicImage::ImageRgb8(_) => Some(ImageFormat::RGB),
image::DynamicImage::ImageRgba8(_) => Some(ImageFormat::RGBA),
_ => None,
};
match format {
Some(format) => Ok(ImageView::from_slice(img.as_bytes(), img.width(), img.height(), format)?),
None => Err(Error::InvalidInput("Invalid image format (must be either luma8|lumaA8|rgb8|rgba8)".to_string())),
}
}
}
make_zxing_class!(Image, ZXing_Image);
impl Image {
getter!(Image, width, transmute, i32);
getter!(Image, height, transmute, i32);
getter!(Image, format, transmute, ImageFormat);
pub fn data(&self) -> Vec<u8> {
let ptr = unsafe { ZXing_Image_data(self.0) };
if ptr.is_null() {
Vec::<u8>::new()
} else {
unsafe { std::slice::from_raw_parts(ptr, (self.width() * self.height()) as usize).to_vec() }
}
}
}
#[cfg(feature = "image")]
impl From<&Image> for image::GrayImage {
fn from(img: &Image) -> image::GrayImage {
image::GrayImage::from_vec(img.width() as u32, img.height() as u32, img.data()).unwrap()
}
}
#[derive(Error, Debug, PartialEq)]
pub enum BarcodeError {
#[error("")]
None(),
#[error("{0}")]
Checksum(String),
#[error("{0}")]
Format(String),
#[error("{0}")]
Unsupported(String),
}
pub type PointI = ZXing_PointI;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct Position {
pub top_left: PointI,
pub top_right: PointI,
pub bottom_right: PointI,
pub bottom_left: PointI,
}
impl Display for PointI {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}x{}", self.x, self.y)
}
}
impl Display for Position {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", unsafe {
c2r_str(ZXing_PositionToString(*(self as *const Position as *const ZXing_Position)))
})
}
}
make_zxing_class!(Barcode, ZXing_Barcode);
impl Barcode {
getter!(Barcode, isValid, transmute, bool);
getter!(Barcode, format, (|f| BarcodeFormats::new(f).unwrap().into_iter().last().unwrap()), BarcodeFormat);
getter!(Barcode, contentType, transmute, ContentType);
getter!(Barcode, text, c2r_str, String);
getter!(Barcode, ecLevel, c2r_str, String);
getter!(Barcode, symbologyIdentifier, c2r_str, String);
getter!(Barcode, position, transmute, Position);
getter!(Barcode, orientation, transmute, i32);
getter!(Barcode, hasECI, has_eci, transmute, bool);
getter!(Barcode, isInverted, transmute, bool);
getter!(Barcode, isMirrored, transmute, bool);
getter!(Barcode, lineCount, transmute, i32);
pub fn bytes(&self) -> Vec<u8> {
let mut len: c_int = 0;
unsafe { c2r_vec(ZXing_Barcode_bytes(self.0, &mut len), len) }
}
pub fn bytes_eci(&self) -> Vec<u8> {
let mut len: c_int = 0;
unsafe { c2r_vec(ZXing_Barcode_bytesECI(self.0, &mut len), len) }
}
pub fn error(&self) -> BarcodeError {
let error_type = unsafe { ZXing_Barcode_errorType(self.0) };
let error_msg = unsafe { c2r_str(ZXing_Barcode_errorMsg(self.0)) };
#[allow(non_upper_case_globals)]
match error_type {
ZXing_ErrorType_None => BarcodeError::None(),
ZXing_ErrorType_Format => BarcodeError::Format(error_msg),
ZXing_ErrorType_Checksum => BarcodeError::Checksum(error_msg),
ZXing_ErrorType_Unsupported => BarcodeError::Unsupported(error_msg),
_ => panic!("Internal error: invalid ZXing_ErrorType"),
}
}
pub fn to_svg_with(&self, opts: &BarcodeWriter) -> Result<String, Error> {
let str = unsafe { ZXing_WriteBarcodeToSVG(self.0, opts.0) };
last_error_if_null_or!(str, c2r_str(str))
}
pub fn to_svg(&self) -> Result<String, Error> {
self.to_svg_with(&BarcodeWriter::default())
}
pub fn to_image_with(&self, opts: &BarcodeWriter) -> Result<Image, Error> {
let img = unsafe { ZXing_WriteBarcodeToImage(self.0, opts.0) };
last_error_if_null_or!(img, Image(img))
}
pub fn to_image(&self) -> Result<Image, Error> {
self.to_image_with(&BarcodeWriter::default())
}
}
make_zxing_class_with_default!(BarcodeReader, ZXing_ReaderOptions);
impl BarcodeReader {
property!(ReaderOptions, TryHarder, bool);
property!(ReaderOptions, TryRotate, bool);
property!(ReaderOptions, TryInvert, bool);
property!(ReaderOptions, TryDownscale, bool);
property!(ReaderOptions, IsPure, bool);
property!(ReaderOptions, ReturnErrors, bool);
property!(ReaderOptions, Formats, BarcodeFormats);
property!(ReaderOptions, TextMode, TextMode);
property!(ReaderOptions, Binarizer, Binarizer);
property!(ReaderOptions, EanAddOnSymbol, EanAddOnSymbol);
property!(ReaderOptions, MaxNumberOfSymbols, i32);
property!(ReaderOptions, MinLineCount, i32);
pub fn from<'a, IV>(&self, image: IV) -> Result<Vec<Barcode>, Error>
where
IV: TryInto<ImageView<'a>>,
IV::Error: Into<Error>,
{
let iv_: ImageView = image.try_into().map_err(Into::into)?;
unsafe {
let results = ZXing_ReadBarcodes((iv_.0).0, self.0);
if !results.is_null() {
let size = ZXing_Barcodes_size(results);
let mut vec = Vec::<Barcode>::with_capacity(size as usize);
for i in 0..size {
vec.push(Barcode(ZXing_Barcodes_move(results, i)));
}
ZXing_Barcodes_delete(results);
Ok(vec)
} else {
Err(last_error())
}
}
}
}
make_zxing_class!(BarcodeCreator, ZXing_CreatorOptions);
impl BarcodeCreator {
pub fn new(format: BarcodeFormat) -> Self {
unsafe { BarcodeCreator(ZXing_CreatorOptions_new(BarcodeFormats::from(format).bits())) }
}
property!(CreatorOptions, ReaderInit, bool);
property!(CreatorOptions, ForceSquareDataMatrix, bool);
property!(CreatorOptions, EcLevel, String);
pub fn from_str(&self, str: impl AsRef<str>) -> Result<Barcode, Error> {
let cstr = CString::new(str.as_ref())?;
let bc = unsafe { ZXing_CreateBarcodeFromText(cstr.as_ptr(), 0, self.0) };
last_error_if_null_or!(bc, Barcode(bc))
}
pub fn from_slice(&self, data: impl AsRef<[u8]>) -> Result<Barcode, Error> {
let data = data.as_ref();
let bc = unsafe { ZXing_CreateBarcodeFromBytes(data.as_ptr() as *const c_void, data.len() as i32, self.0) };
last_error_if_null_or!(bc, Barcode(bc))
}
}
make_zxing_class_with_default!(BarcodeWriter, ZXing_WriterOptions);
impl BarcodeWriter {
property!(WriterOptions, Scale, i32);
property!(WriterOptions, SizeHint, i32);
property!(WriterOptions, Rotate, i32);
property!(WriterOptions, WithHRT, with_hrt, bool);
property!(WriterOptions, WithQuietZones, bool);
}
pub fn read() -> BarcodeReader {
BarcodeReader::default()
}
pub fn create(format: BarcodeFormat) -> BarcodeCreator {
BarcodeCreator::new(format)
}
pub fn write() -> BarcodeWriter {
BarcodeWriter::default()
}
```
|
/content/code_sandbox/wrappers/rust/src/lib.rs
|
rust
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 4,942
|
```rust
/*
*/
use image;
use std::fs;
use zxingcpp::*;
fn main() -> anyhow::Result<()> {
let text = std::env::args().nth(1).expect("no input text provided");
let format = std::env::args().nth(2).expect("no format provided");
let filename = std::env::args().nth(3).expect("no output file name provided");
let create_barcode = create(BarcodeFormat::from_str(format)?);
let bc = create_barcode.from_str(text)?;
if filename.ends_with(".svg") {
fs::write(filename, bc.to_svg_with(&write().with_hrt(true))?).expect("Unable to write file");
} else {
image::GrayImage::from(&bc.to_image_with(&write().scale(4))?).save(filename)?;
}
Ok(())
}
```
|
/content/code_sandbox/wrappers/rust/examples/demo_writer.rs
|
rust
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 177
|
```rust
/*
*/
use zxingcpp::*;
fn main() -> anyhow::Result<()> {
let filename = std::env::args().nth(1).expect("no image file name provided");
let formats = std::env::args().nth(2);
let fast = std::env::args().nth(3).is_some();
let image = image::open(&filename)?;
#[cfg(not(feature = "image"))]
let lum_img = image.into_luma8();
#[cfg(not(feature = "image"))]
let iv = ImageView::from_slice(&lum_img, lum_img.width(), lum_img.height(), ImageFormat::Lum)?;
let formats = BarcodeFormats::from_str(formats.unwrap_or_default())?;
let read_barcodes = BarcodeReader::new()
.formats(formats)
.try_harder(!fast)
.try_invert(!fast)
.try_rotate(!fast)
.try_downscale(!fast)
.return_errors(true);
#[cfg(feature = "image")]
let barcodes = read_barcodes.from(&image)?;
#[cfg(not(feature = "image"))]
let barcodes = read_barcodes.from(iv)?;
if barcodes.is_empty() {
println!("No barcode found.");
} else {
for barcode in barcodes {
println!("Text: {}", barcode.text());
println!("Bytes: {:?}", barcode.bytes());
println!("Format: {}", barcode.format());
println!("Content: {}", barcode.content_type());
println!("Identifier: {}", barcode.symbology_identifier());
println!("EC Level: {}", barcode.ec_level());
println!("Error: {}", barcode.error());
println!("Rotation: {}", barcode.orientation());
println!("Position: {}", barcode.position());
println!();
}
}
Ok(())
}
```
|
/content/code_sandbox/wrappers/rust/examples/demo_reader.rs
|
rust
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 375
|
```rust
/* automatically generated by rust-bindgen 0.69.2 */
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct ZXing_Barcode {
_unused: [u8; 0],
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct ZXing_Barcodes {
_unused: [u8; 0],
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct ZXing_ImageView {
_unused: [u8; 0],
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct ZXing_Image {
_unused: [u8; 0],
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct ZXing_ReaderOptions {
_unused: [u8; 0],
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct ZXing_CreatorOptions {
_unused: [u8; 0],
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct ZXing_WriterOptions {
_unused: [u8; 0],
}
pub const ZXing_ImageFormat_None: ZXing_ImageFormat = 0;
pub const ZXing_ImageFormat_Lum: ZXing_ImageFormat = 16777216;
pub const ZXing_ImageFormat_LumA: ZXing_ImageFormat = 33554432;
pub const ZXing_ImageFormat_RGB: ZXing_ImageFormat = 50331906;
pub const ZXing_ImageFormat_BGR: ZXing_ImageFormat = 50462976;
pub const ZXing_ImageFormat_RGBA: ZXing_ImageFormat = 67109122;
pub const ZXing_ImageFormat_ARGB: ZXing_ImageFormat = 67174915;
pub const ZXing_ImageFormat_BGRA: ZXing_ImageFormat = 67240192;
pub const ZXing_ImageFormat_ABGR: ZXing_ImageFormat = 67305985;
pub type ZXing_ImageFormat = ::core::ffi::c_uint;
pub const ZXing_BarcodeFormat_None: ZXing_BarcodeFormat = 0;
pub const ZXing_BarcodeFormat_Aztec: ZXing_BarcodeFormat = 1;
pub const ZXing_BarcodeFormat_Codabar: ZXing_BarcodeFormat = 2;
pub const ZXing_BarcodeFormat_Code39: ZXing_BarcodeFormat = 4;
pub const ZXing_BarcodeFormat_Code93: ZXing_BarcodeFormat = 8;
pub const ZXing_BarcodeFormat_Code128: ZXing_BarcodeFormat = 16;
pub const ZXing_BarcodeFormat_DataBar: ZXing_BarcodeFormat = 32;
pub const ZXing_BarcodeFormat_DataBarExpanded: ZXing_BarcodeFormat = 64;
pub const ZXing_BarcodeFormat_DataMatrix: ZXing_BarcodeFormat = 128;
pub const ZXing_BarcodeFormat_EAN8: ZXing_BarcodeFormat = 256;
pub const ZXing_BarcodeFormat_EAN13: ZXing_BarcodeFormat = 512;
pub const ZXing_BarcodeFormat_ITF: ZXing_BarcodeFormat = 1024;
pub const ZXing_BarcodeFormat_MaxiCode: ZXing_BarcodeFormat = 2048;
pub const ZXing_BarcodeFormat_PDF417: ZXing_BarcodeFormat = 4096;
pub const ZXing_BarcodeFormat_QRCode: ZXing_BarcodeFormat = 8192;
pub const ZXing_BarcodeFormat_UPCA: ZXing_BarcodeFormat = 16384;
pub const ZXing_BarcodeFormat_UPCE: ZXing_BarcodeFormat = 32768;
pub const ZXing_BarcodeFormat_MicroQRCode: ZXing_BarcodeFormat = 65536;
pub const ZXing_BarcodeFormat_RMQRCode: ZXing_BarcodeFormat = 131072;
pub const ZXing_BarcodeFormat_DXFilmEdge: ZXing_BarcodeFormat = 262144;
pub const ZXing_BarcodeFormat_LinearCodes: ZXing_BarcodeFormat = 313214;
pub const ZXing_BarcodeFormat_MatrixCodes: ZXing_BarcodeFormat = 211073;
pub const ZXing_BarcodeFormat_Any: ZXing_BarcodeFormat = 524287;
pub const ZXing_BarcodeFormat_Invalid: ZXing_BarcodeFormat = 4294967295;
pub type ZXing_BarcodeFormat = ::core::ffi::c_uint;
pub use self::ZXing_BarcodeFormat as ZXing_BarcodeFormats;
pub const ZXing_ContentType_Text: ZXing_ContentType = 0;
pub const ZXing_ContentType_Binary: ZXing_ContentType = 1;
pub const ZXing_ContentType_Mixed: ZXing_ContentType = 2;
pub const ZXing_ContentType_GS1: ZXing_ContentType = 3;
pub const ZXing_ContentType_ISO15434: ZXing_ContentType = 4;
pub const ZXing_ContentType_UnknownECI: ZXing_ContentType = 5;
pub type ZXing_ContentType = ::core::ffi::c_uint;
pub const ZXing_ErrorType_None: ZXing_ErrorType = 0;
pub const ZXing_ErrorType_Format: ZXing_ErrorType = 1;
pub const ZXing_ErrorType_Checksum: ZXing_ErrorType = 2;
pub const ZXing_ErrorType_Unsupported: ZXing_ErrorType = 3;
pub type ZXing_ErrorType = ::core::ffi::c_uint;
#[repr(C)]
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct ZXing_PointI {
pub x: ::core::ffi::c_int,
pub y: ::core::ffi::c_int,
}
#[repr(C)]
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct ZXing_Position {
pub topLeft: ZXing_PointI,
pub topRight: ZXing_PointI,
pub bottomRight: ZXing_PointI,
pub bottomLeft: ZXing_PointI,
}
pub const ZXing_Binarizer_LocalAverage: ZXing_Binarizer = 0;
pub const ZXing_Binarizer_GlobalHistogram: ZXing_Binarizer = 1;
pub const ZXing_Binarizer_FixedThreshold: ZXing_Binarizer = 2;
pub const ZXing_Binarizer_BoolCast: ZXing_Binarizer = 3;
pub type ZXing_Binarizer = ::core::ffi::c_uint;
pub const ZXing_EanAddOnSymbol_Ignore: ZXing_EanAddOnSymbol = 0;
pub const ZXing_EanAddOnSymbol_Read: ZXing_EanAddOnSymbol = 1;
pub const ZXing_EanAddOnSymbol_Require: ZXing_EanAddOnSymbol = 2;
pub type ZXing_EanAddOnSymbol = ::core::ffi::c_uint;
pub const ZXing_TextMode_Plain: ZXing_TextMode = 0;
pub const ZXing_TextMode_ECI: ZXing_TextMode = 1;
pub const ZXing_TextMode_HRI: ZXing_TextMode = 2;
pub const ZXing_TextMode_Hex: ZXing_TextMode = 3;
pub const ZXing_TextMode_Escaped: ZXing_TextMode = 4;
pub type ZXing_TextMode = ::core::ffi::c_uint;
extern "C" {
pub fn ZXing_ImageView_new(
data: *const u8,
width: ::core::ffi::c_int,
height: ::core::ffi::c_int,
format: ZXing_ImageFormat,
rowStride: ::core::ffi::c_int,
pixStride: ::core::ffi::c_int,
) -> *mut ZXing_ImageView;
pub fn ZXing_ImageView_new_checked(
data: *const u8,
size: ::core::ffi::c_int,
width: ::core::ffi::c_int,
height: ::core::ffi::c_int,
format: ZXing_ImageFormat,
rowStride: ::core::ffi::c_int,
pixStride: ::core::ffi::c_int,
) -> *mut ZXing_ImageView;
pub fn ZXing_ImageView_delete(iv: *mut ZXing_ImageView);
pub fn ZXing_ImageView_crop(
iv: *mut ZXing_ImageView,
left: ::core::ffi::c_int,
top: ::core::ffi::c_int,
width: ::core::ffi::c_int,
height: ::core::ffi::c_int,
);
pub fn ZXing_ImageView_rotate(iv: *mut ZXing_ImageView, degree: ::core::ffi::c_int);
pub fn ZXing_Image_delete(img: *mut ZXing_Image);
pub fn ZXing_Image_data(img: *const ZXing_Image) -> *const u8;
pub fn ZXing_Image_width(img: *const ZXing_Image) -> ::core::ffi::c_int;
pub fn ZXing_Image_height(img: *const ZXing_Image) -> ::core::ffi::c_int;
pub fn ZXing_Image_format(img: *const ZXing_Image) -> ZXing_ImageFormat;
pub fn ZXing_BarcodeFormatsFromString(str_: *const ::core::ffi::c_char) -> ZXing_BarcodeFormats;
pub fn ZXing_BarcodeFormatFromString(str_: *const ::core::ffi::c_char) -> ZXing_BarcodeFormat;
pub fn ZXing_BarcodeFormatToString(format: ZXing_BarcodeFormat) -> *mut ::core::ffi::c_char;
pub fn ZXing_ContentTypeToString(type_: ZXing_ContentType) -> *mut ::core::ffi::c_char;
pub fn ZXing_PositionToString(position: ZXing_Position) -> *mut ::core::ffi::c_char;
pub fn ZXing_Barcode_isValid(barcode: *const ZXing_Barcode) -> bool;
pub fn ZXing_Barcode_errorType(barcode: *const ZXing_Barcode) -> ZXing_ErrorType;
pub fn ZXing_Barcode_errorMsg(barcode: *const ZXing_Barcode) -> *mut ::core::ffi::c_char;
pub fn ZXing_Barcode_format(barcode: *const ZXing_Barcode) -> ZXing_BarcodeFormat;
pub fn ZXing_Barcode_contentType(barcode: *const ZXing_Barcode) -> ZXing_ContentType;
pub fn ZXing_Barcode_bytes(barcode: *const ZXing_Barcode, len: *mut ::core::ffi::c_int) -> *mut u8;
pub fn ZXing_Barcode_bytesECI(barcode: *const ZXing_Barcode, len: *mut ::core::ffi::c_int) -> *mut u8;
pub fn ZXing_Barcode_text(barcode: *const ZXing_Barcode) -> *mut ::core::ffi::c_char;
pub fn ZXing_Barcode_ecLevel(barcode: *const ZXing_Barcode) -> *mut ::core::ffi::c_char;
pub fn ZXing_Barcode_symbologyIdentifier(barcode: *const ZXing_Barcode) -> *mut ::core::ffi::c_char;
pub fn ZXing_Barcode_position(barcode: *const ZXing_Barcode) -> ZXing_Position;
pub fn ZXing_Barcode_orientation(barcode: *const ZXing_Barcode) -> ::core::ffi::c_int;
pub fn ZXing_Barcode_hasECI(barcode: *const ZXing_Barcode) -> bool;
pub fn ZXing_Barcode_isInverted(barcode: *const ZXing_Barcode) -> bool;
pub fn ZXing_Barcode_isMirrored(barcode: *const ZXing_Barcode) -> bool;
pub fn ZXing_Barcode_lineCount(barcode: *const ZXing_Barcode) -> ::core::ffi::c_int;
pub fn ZXing_Barcode_delete(barcode: *mut ZXing_Barcode);
pub fn ZXing_Barcodes_delete(barcodes: *mut ZXing_Barcodes);
pub fn ZXing_Barcodes_size(barcodes: *const ZXing_Barcodes) -> ::core::ffi::c_int;
pub fn ZXing_Barcodes_at(barcodes: *const ZXing_Barcodes, i: ::core::ffi::c_int) -> *const ZXing_Barcode;
pub fn ZXing_Barcodes_move(barcodes: *mut ZXing_Barcodes, i: ::core::ffi::c_int) -> *mut ZXing_Barcode;
pub fn ZXing_ReaderOptions_new() -> *mut ZXing_ReaderOptions;
pub fn ZXing_ReaderOptions_delete(opts: *mut ZXing_ReaderOptions);
pub fn ZXing_ReaderOptions_setTryHarder(opts: *mut ZXing_ReaderOptions, tryHarder: bool);
pub fn ZXing_ReaderOptions_setTryRotate(opts: *mut ZXing_ReaderOptions, tryRotate: bool);
pub fn ZXing_ReaderOptions_setTryInvert(opts: *mut ZXing_ReaderOptions, tryInvert: bool);
pub fn ZXing_ReaderOptions_setTryDownscale(opts: *mut ZXing_ReaderOptions, tryDownscale: bool);
pub fn ZXing_ReaderOptions_setIsPure(opts: *mut ZXing_ReaderOptions, isPure: bool);
pub fn ZXing_ReaderOptions_setReturnErrors(opts: *mut ZXing_ReaderOptions, returnErrors: bool);
pub fn ZXing_ReaderOptions_setFormats(opts: *mut ZXing_ReaderOptions, formats: ZXing_BarcodeFormats);
pub fn ZXing_ReaderOptions_setBinarizer(opts: *mut ZXing_ReaderOptions, binarizer: ZXing_Binarizer);
pub fn ZXing_ReaderOptions_setEanAddOnSymbol(opts: *mut ZXing_ReaderOptions, eanAddOnSymbol: ZXing_EanAddOnSymbol);
pub fn ZXing_ReaderOptions_setTextMode(opts: *mut ZXing_ReaderOptions, textMode: ZXing_TextMode);
pub fn ZXing_ReaderOptions_setMinLineCount(opts: *mut ZXing_ReaderOptions, n: ::core::ffi::c_int);
pub fn ZXing_ReaderOptions_setMaxNumberOfSymbols(opts: *mut ZXing_ReaderOptions, n: ::core::ffi::c_int);
pub fn ZXing_ReaderOptions_getTryHarder(opts: *const ZXing_ReaderOptions) -> bool;
pub fn ZXing_ReaderOptions_getTryRotate(opts: *const ZXing_ReaderOptions) -> bool;
pub fn ZXing_ReaderOptions_getTryInvert(opts: *const ZXing_ReaderOptions) -> bool;
pub fn ZXing_ReaderOptions_getTryDownscale(opts: *const ZXing_ReaderOptions) -> bool;
pub fn ZXing_ReaderOptions_getIsPure(opts: *const ZXing_ReaderOptions) -> bool;
pub fn ZXing_ReaderOptions_getReturnErrors(opts: *const ZXing_ReaderOptions) -> bool;
pub fn ZXing_ReaderOptions_getFormats(opts: *const ZXing_ReaderOptions) -> ZXing_BarcodeFormats;
pub fn ZXing_ReaderOptions_getBinarizer(opts: *const ZXing_ReaderOptions) -> ZXing_Binarizer;
pub fn ZXing_ReaderOptions_getEanAddOnSymbol(opts: *const ZXing_ReaderOptions) -> ZXing_EanAddOnSymbol;
pub fn ZXing_ReaderOptions_getTextMode(opts: *const ZXing_ReaderOptions) -> ZXing_TextMode;
pub fn ZXing_ReaderOptions_getMinLineCount(opts: *const ZXing_ReaderOptions) -> ::core::ffi::c_int;
pub fn ZXing_ReaderOptions_getMaxNumberOfSymbols(opts: *const ZXing_ReaderOptions) -> ::core::ffi::c_int;
pub fn ZXing_ReadBarcode(iv: *const ZXing_ImageView, opts: *const ZXing_ReaderOptions) -> *mut ZXing_Barcode;
pub fn ZXing_ReadBarcodes(iv: *const ZXing_ImageView, opts: *const ZXing_ReaderOptions) -> *mut ZXing_Barcodes;
pub fn ZXing_CreatorOptions_new(format: ZXing_BarcodeFormat) -> *mut ZXing_CreatorOptions;
pub fn ZXing_CreatorOptions_delete(opts: *mut ZXing_CreatorOptions);
pub fn ZXing_CreatorOptions_setFormat(opts: *mut ZXing_CreatorOptions, format: ZXing_BarcodeFormat);
pub fn ZXing_CreatorOptions_getFormat(opts: *const ZXing_CreatorOptions) -> ZXing_BarcodeFormat;
pub fn ZXing_CreatorOptions_setReaderInit(opts: *mut ZXing_CreatorOptions, readerInit: bool);
pub fn ZXing_CreatorOptions_getReaderInit(opts: *const ZXing_CreatorOptions) -> bool;
pub fn ZXing_CreatorOptions_setForceSquareDataMatrix(opts: *mut ZXing_CreatorOptions, forceSquareDataMatrix: bool);
pub fn ZXing_CreatorOptions_getForceSquareDataMatrix(opts: *const ZXing_CreatorOptions) -> bool;
pub fn ZXing_CreatorOptions_setEcLevel(opts: *mut ZXing_CreatorOptions, ecLevel: *const ::core::ffi::c_char);
pub fn ZXing_CreatorOptions_getEcLevel(opts: *const ZXing_CreatorOptions) -> *mut ::core::ffi::c_char;
pub fn ZXing_WriterOptions_new() -> *mut ZXing_WriterOptions;
pub fn ZXing_WriterOptions_delete(opts: *mut ZXing_WriterOptions);
pub fn ZXing_WriterOptions_setScale(opts: *mut ZXing_WriterOptions, scale: ::core::ffi::c_int);
pub fn ZXing_WriterOptions_getScale(opts: *const ZXing_WriterOptions) -> ::core::ffi::c_int;
pub fn ZXing_WriterOptions_setSizeHint(opts: *mut ZXing_WriterOptions, sizeHint: ::core::ffi::c_int);
pub fn ZXing_WriterOptions_getSizeHint(opts: *const ZXing_WriterOptions) -> ::core::ffi::c_int;
pub fn ZXing_WriterOptions_setRotate(opts: *mut ZXing_WriterOptions, rotate: ::core::ffi::c_int);
pub fn ZXing_WriterOptions_getRotate(opts: *const ZXing_WriterOptions) -> ::core::ffi::c_int;
pub fn ZXing_WriterOptions_setWithHRT(opts: *mut ZXing_WriterOptions, withHRT: bool);
pub fn ZXing_WriterOptions_getWithHRT(opts: *const ZXing_WriterOptions) -> bool;
pub fn ZXing_WriterOptions_setWithQuietZones(opts: *mut ZXing_WriterOptions, withQuietZones: bool);
pub fn ZXing_WriterOptions_getWithQuietZones(opts: *const ZXing_WriterOptions) -> bool;
pub fn ZXing_CreateBarcodeFromText(
data: *const ::core::ffi::c_char,
size: ::core::ffi::c_int,
opts: *const ZXing_CreatorOptions,
) -> *mut ZXing_Barcode;
pub fn ZXing_CreateBarcodeFromBytes(
data: *const ::core::ffi::c_void,
size: ::core::ffi::c_int,
opts: *const ZXing_CreatorOptions,
) -> *mut ZXing_Barcode;
pub fn ZXing_WriteBarcodeToSVG(barcode: *const ZXing_Barcode, opts: *const ZXing_WriterOptions) -> *mut ::core::ffi::c_char;
pub fn ZXing_WriteBarcodeToImage(barcode: *const ZXing_Barcode, opts: *const ZXing_WriterOptions) -> *mut ZXing_Image;
pub fn ZXing_LastErrorMsg() -> *mut ::core::ffi::c_char;
pub fn ZXing_free(ptr: *mut ::core::ffi::c_void);
}
```
|
/content/code_sandbox/wrappers/rust/src/bindings.rs
|
rust
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 4,138
|
```kotlin
pluginManagement {
repositories {
gradlePluginPortal()
google()
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
mavenCentral()
google()
}
}
include(":app")
include(":zxingcpp")
rootProject.name = "zxing-cpp"
```
|
/content/code_sandbox/wrappers/android/settings.gradle.kts
|
kotlin
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 70
|
```kotlin
plugins {
base
alias(libs.plugins.android.application) apply false
alias(libs.plugins.android.library) apply false
alias(libs.plugins.kotlin.android) apply false
}
tasks.named<Delete>("clean") {
val buildDirs = allprojects.map { it.layout.buildDirectory.asFile }
delete(buildDirs)
}
```
|
/content/code_sandbox/wrappers/android/build.gradle.kts
|
kotlin
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 70
|
```batchfile
@rem
@rem
@rem
@rem path_to_url
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
```
|
/content/code_sandbox/wrappers/android/gradlew.bat
|
batchfile
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 618
|
```ini
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# path_to_url
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# path_to_url#sec:decoupled_projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app"s APK
# path_to_url
android.useAndroidX=true
# Kotlin code style for this project: "official" or "obsolete":
kotlin.code.style=official
```
|
/content/code_sandbox/wrappers/android/gradle.properties
|
ini
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 212
|
```toml
[versions]
androidGradlePlugin = "8.2.2"
androidCompileSdk = "34"
androidMinSdk = "21"
androidTargetSdk = "33"
androidx-appcompat = "1.6.1"
androidx-camera = "1.3.1"
androidx-core = "1.12.0"
androidx-constraintLayout = "2.1.4"
android-material = "1.11.0-rc01"
kotlin = "1.9.10"
zxing-core = "3.5.3"
[libraries]
androidx-appcompat = { module = "androidx.appcompat:appcompat", version.ref = "androidx-appcompat" }
androidx-camera-core = { module = "androidx.camera:camera-core", version.ref = "androidx-camera" }
androidx-camera-camera2 = { module = "androidx.camera:camera-camera2", version.ref = "androidx-camera" }
androidx-camera-lifecycle = { module = "androidx.camera:camera-lifecycle", version.ref = "androidx-camera" }
androidx-camera-view = { module = "androidx.camera:camera-view", version.ref = "androidx-camera" }
androidx-constraintlayout = { module = "androidx.constraintlayout:constraintlayout", version.ref = "androidx-constraintLayout" }
androidx-core = { module = "androidx.core:core-ktx", version.ref = "androidx-core" }
android-material = { module = "com.google.android.material:material", version.ref = "android-material" }
zxing-core = { module = "com.google.zxing:core", version.ref = "zxing-core" }
[plugins]
android-application = { id = "com.android.application", version.ref = "androidGradlePlugin" }
android-library = { id = "com.android.library", version.ref = "androidGradlePlugin" }
kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }
```
|
/content/code_sandbox/wrappers/android/gradle/libs.versions.toml
|
toml
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 417
|
```ini
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.3-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
```
|
/content/code_sandbox/wrappers/android/gradle/wrapper/gradle-wrapper.properties
|
ini
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 66
|
```kotlin
plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.kotlin.android)
}
android {
namespace = "zxingcpp.app"
defaultConfig {
applicationId = "io.github.zxingcpp.app"
compileSdk = libs.versions.androidCompileSdk.get().toInt()
minSdk = 26 // for the adaptive icons. TODO: remove adaptive icons and lower to API 21
targetSdk = libs.versions.androidTargetSdk.get().toInt()
versionCode = 1
versionName = "1.0"
}
buildFeatures {
viewBinding = true
}
buildTypes {
release {
isMinifyEnabled = false
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = "1.8"
}
lint {
disable.add("UnsafeExperimentalUsageError")
}
}
dependencies {
implementation(project(":zxingcpp"))
implementation(libs.androidx.appcompat)
implementation(libs.androidx.constraintlayout)
implementation(libs.androidx.core)
implementation(libs.androidx.camera.camera2)
implementation(libs.androidx.camera.lifecycle)
implementation(libs.androidx.camera.view)
implementation(libs.android.material)
// Java "upstream" version of zxing (to compare performance)
implementation(libs.zxing.core)
}
```
|
/content/code_sandbox/wrappers/android/app/build.gradle.kts
|
kotlin
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 328
|
```qmake
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.kts.
#
# For more details, see
# path_to_url
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
```
|
/content/code_sandbox/wrappers/android/app/proguard-rules.pro
|
qmake
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 157
|
```unknown
#!/bin/sh
#
#
#
# path_to_url
#
# Unless required by applicable law or agreed to in writing, software
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions $var, ${var}, ${var:-default}, ${var+SET},
# ${var#prefix}, ${var%suffix}, and $( cmd );
# * compound commands having a testable exit status, especially case;
# * various built-in commands including command, set, and ulimit.
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# path_to_url
# within the Gradle project.
#
# You can find Gradle at path_to_url
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (path_to_url
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
```
|
/content/code_sandbox/wrappers/android/gradlew
|
unknown
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 2,081
|
```xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="path_to_url">
<!-- Declare features -->
<uses-feature android:name="android.hardware.camera" />
<!-- Declare permissions -->
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="false"
android:label="@string/app_name"
android:icon="@mipmap/ic_launcher_round"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name="zxingcpp.app.MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
```
|
/content/code_sandbox/wrappers/android/app/src/main/AndroidManifest.xml
|
xml
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 207
|
```xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="path_to_url"
xmlns:app="path_to_url"
xmlns:tools="path_to_url"
android:id="@+id/camera_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.camera.view.PreviewView
android:id="@+id/viewFinder"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:scaleType="fitCenter" />
<com.example.zxingcppdemo.PreviewOverlay
android:id="@+id/overlay"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<TextView
android:id="@+id/result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/margin_large"
android:background="#65000000"
android:shadowColor="@android:color/black"
android:shadowRadius="6"
android:text="@string/unknown"
android:textAllCaps="false"
android:textAppearance="@style/TextAppearance.AppCompat.Medium.Inverse"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/fps"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/margin_xsmall"
android:layout_marginEnd="@dimen/margin_xsmall"
android:background="#65000000"
android:shadowColor="@android:color/black"
android:shadowRadius="6"
android:text="@string/unknown"
android:textAllCaps="false"
android:textAppearance="@style/TextAppearance.AppCompat.Small.Inverse"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<!-- Camera control buttons -->
<ImageButton
android:id="@+id/capture"
android:layout_width="@dimen/shutter_button_size"
android:layout_height="@dimen/shutter_button_size"
android:layout_marginBottom="@dimen/shutter_button_margin"
android:background="@drawable/ic_shutter"
android:contentDescription="@string/capture_button_alt"
android:scaleType="fitCenter"
android:visibility="visible"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent" />
<com.google.android.material.chip.ChipGroup
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:scaleX="-1"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent">
<com.google.android.material.chip.Chip
android:id="@+id/java"
style="@style/ChipR"
android:text="Java" />
<com.google.android.material.chip.Chip
android:id="@+id/qrcode"
style="@style/ChipR"
android:text="QRCode" />
<com.google.android.material.chip.Chip
android:id="@+id/tryHarder"
style="@style/ChipR"
android:text="tryHarder" />
<com.google.android.material.chip.Chip
android:id="@+id/tryRotate"
style="@style/ChipR"
android:text="tryRotate" />
<com.google.android.material.chip.Chip
android:id="@+id/tryInvert"
style="@style/ChipR"
android:text="tryInvert" />
<com.google.android.material.chip.Chip
android:id="@+id/tryDownscale"
style="@style/ChipR"
android:text="tryDownscale" />
<com.google.android.material.chip.Chip
android:id="@+id/multiSymbol"
style="@style/ChipR"
android:text="multiSymbol" />
<com.google.android.material.chip.Chip
android:id="@+id/crop"
style="@style/ChipR"
android:text="crop" />
<com.google.android.material.chip.Chip
android:id="@+id/torch"
style="@style/ChipR"
android:text="Torch" />
<com.google.android.material.chip.Chip
android:id="@+id/pause"
style="@style/ChipR"
android:text="pause" />
</com.google.android.material.chip.ChipGroup>
</androidx.constraintlayout.widget.ConstraintLayout>
```
|
/content/code_sandbox/wrappers/android/app/src/main/res/layout/activity_camera.xml
|
xml
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 1,052
|
```xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="path_to_url"
xmlns:app="path_to_url"
xmlns:tools="path_to_url"
android:id="@+id/camera_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.camera.view.PreviewView
android:id="@+id/viewFinder"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:scaleType="fitCenter" />
<com.example.zxingcppdemo.PreviewOverlay
android:id="@+id/overlay"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<TextView
android:id="@+id/result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/margin_large"
android:background="#65000000"
android:shadowColor="@android:color/black"
android:shadowRadius="6"
android:text="@string/unknown"
android:textAllCaps="false"
android:textAppearance="@style/TextAppearance.AppCompat.Medium.Inverse"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/fps"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/margin_xsmall"
android:layout_marginEnd="@dimen/margin_xsmall"
android:background="#65000000"
android:shadowColor="@android:color/black"
android:shadowRadius="6"
android:text="@string/unknown"
android:textAllCaps="false"
android:textAppearance="@style/TextAppearance.AppCompat.Small.Inverse"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageButton
android:id="@+id/capture"
android:layout_width="@dimen/shutter_button_size"
android:layout_height="@dimen/shutter_button_size"
android:layout_marginEnd="@dimen/shutter_button_margin"
android:background="@drawable/ic_shutter"
android:contentDescription="@string/capture_button_alt"
android:scaleType="fitCenter"
android:visibility="visible"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.google.android.material.chip.ChipGroup
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent">
<com.google.android.material.chip.Chip
android:id="@+id/java"
style="@style/Chip"
android:text="Java" />
<com.google.android.material.chip.Chip
android:id="@+id/qrcode"
style="@style/Chip"
android:text="QRCode" />
<com.google.android.material.chip.Chip
android:id="@+id/tryHarder"
style="@style/Chip"
android:text="tryHarder" />
<com.google.android.material.chip.Chip
android:id="@+id/tryRotate"
style="@style/Chip"
android:text="tryRotate" />
<com.google.android.material.chip.Chip
android:id="@+id/tryInvert"
style="@style/Chip"
android:text="tryInvert" />
<com.google.android.material.chip.Chip
android:id="@+id/tryDownscale"
style="@style/Chip"
android:text="tryDownscale" />
<com.google.android.material.chip.Chip
android:id="@+id/multiSymbol"
style="@style/Chip"
android:text="multiSymbol" />
<com.google.android.material.chip.Chip
android:id="@+id/crop"
style="@style/Chip"
android:text="crop" />
<com.google.android.material.chip.Chip
android:id="@+id/torch"
style="@style/Chip"
android:text="Torch" />
<com.google.android.material.chip.Chip
android:id="@+id/pause"
style="@style/Chip"
android:text="pause" />
</com.google.android.material.chip.ChipGroup>
</androidx.constraintlayout.widget.ConstraintLayout>
```
|
/content/code_sandbox/wrappers/android/app/src/main/res/layout-land/activity_camera.xml
|
xml
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 1,028
|
```xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="path_to_url"
xmlns:app="path_to_url"
xmlns:tools="path_to_url"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
```
|
/content/code_sandbox/wrappers/android/app/src/main/res/layout/activity_main.xml
|
xml
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 161
|
```xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="ic_launcher_background">#C8C8C8</color>
</resources>
```
|
/content/code_sandbox/wrappers/android/app/src/main/res/values/ic_launcher_background.xml
|
xml
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 39
|
```xml
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="path_to_url">
<background android:drawable="@color/ic_launcher_background"/>
<foreground android:drawable="@drawable/ic_launcher_foreground"/>
</adaptive-icon>
```
|
/content/code_sandbox/wrappers/android/app/src/main/res/mipmap-anydpi/ic_launcher_round.xml
|
xml
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 55
|
```xml
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="path_to_url">
<background android:drawable="@color/ic_launcher_background"/>
<foreground android:drawable="@drawable/ic_launcher_foreground"/>
</adaptive-icon>
```
|
/content/code_sandbox/wrappers/android/app/src/main/res/mipmap-anydpi/ic_launcher.xml
|
xml
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 55
|
```xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="AppTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar">
<item name="android:immersive">true</item>
<item name="android:windowFullscreen">true</item>
<item name="android:windowTranslucentStatus">true</item>
<item name="android:windowTranslucentNavigation">true</item>
</style>
<style name="Chip" parent="Widget.MaterialComponents.Chip.Entry">
<item name="android:checkable">true</item>
<item name="chipSurfaceColor">#A0FFFFFF</item>
<item name="chipMinTouchTargetSize">42dp</item>
<item name="closeIconVisible">false</item>
<item name="android:layout_width">110dp</item>
<item name="android:layout_height">wrap_content</item>
</style>
<style name="ChipR" parent="Chip">
<item name="android:scaleX">-1</item>
</style>
<string name="app_name">zxing-cpp</string>
<string name="capture_button_alt">Capture</string>
<string name="unknown">UNKNOWN</string>
<dimen name="margin_xsmall">16dp</dimen>
<dimen name="margin_small">32dp</dimen>
<dimen name="margin_medium">48dp</dimen>
<dimen name="margin_large">64dp</dimen>
<dimen name="margin_xlarge">92dp</dimen>
<dimen name="spacing_small">4dp</dimen>
<dimen name="spacing_medium">8dp</dimen>
<dimen name="spacing_large">16dp</dimen>
<dimen name="shutter_button_size">64dp</dimen>
<dimen name="shutter_button_margin">80dp</dimen>
</resources>
```
|
/content/code_sandbox/wrappers/android/app/src/main/res/values/values.xml
|
xml
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 437
|
```xml
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="path_to_url"
android:width="24dp"
android:height="24dp"
android:viewportWidth="74"
android:viewportHeight="74">
<path
android:fillColor="#FFFFFF"
android:fillType="evenOdd"
android:pathData="M73.1,37C73.1,17.0637 56.9373,0.9 37,0.9C17.0627,0.9 0.9,17.0637 0.9,37C0.9,56.9373 17.0627,73.1 37,73.1C56.9373,73.1 73.1,56.9373 73.1,37"
android:strokeWidth="1"
android:strokeColor="#00000000" />
<path
android:fillColor="#CFD7DB"
android:fillType="evenOdd"
android:pathData="M67.4,37C67.4,53.7895 53.7895,67.4 37,67.4C20.2105,67.4 6.6,53.7895 6.6,37C6.6,20.2105 20.2105,6.6 37,6.6C53.7895,6.6 67.4,20.2105 67.4,37"
android:strokeWidth="1"
android:strokeColor="#00000000" />
</vector>
```
|
/content/code_sandbox/wrappers/android/app/src/main/res/drawable/ic_shutter_normal.xml
|
xml
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 356
|
```xml
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="path_to_url"
android:width="108dp"
android:height="108dp"
android:tint="#1E1E1E"
android:viewportWidth="108"
android:viewportHeight="108">
<group
android:scaleX="2.2185"
android:scaleY="2.2185"
android:translateX="27.378"
android:translateY="27.378">
<path
android:fillColor="@android:color/white"
android:pathData="M9.5,6.5v3h-3v-3H9.5M11,5H5v6h6V5L11,5zM9.5,14.5v3h-3v-3H9.5M11,13H5v6h6V13L11,13zM17.5,6.5v3h-3v-3H17.5M19,5h-6v6h6V5L19,5zM13,13h1.5v1.5H13V13zM14.5,14.5H16V16h-1.5V14.5zM16,13h1.5v1.5H16V13zM13,16h1.5v1.5H13V16zM14.5,17.5H16V19h-1.5V17.5zM16,16h1.5v1.5H16V16zM17.5,14.5H19V16h-1.5V14.5zM17.5,17.5H19V19h-1.5V17.5zM22,7h-2V4h-3V2h5V7zM22,22v-5h-2v3h-3v2H22zM2,22h5v-2H4v-3H2V22zM2,2v5h2V4h3V2H2z" />
</group>
</vector>
```
|
/content/code_sandbox/wrappers/android/app/src/main/res/drawable/ic_launcher_foreground.xml
|
xml
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 473
|
```xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="path_to_url">
<item android:drawable="@drawable/ic_shutter_pressed" android:state_pressed="true" />
<item android:drawable="@drawable/ic_shutter_pressed" android:state_focused="true" />
<item android:drawable="@drawable/ic_shutter_normal" />
</selector>
```
|
/content/code_sandbox/wrappers/android/app/src/main/res/drawable/ic_shutter.xml
|
xml
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 85
|
```xml
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="path_to_url"
android:width="24dp"
android:height="24dp"
android:viewportWidth="74"
android:viewportHeight="74">
<path
android:fillColor="#FFFFFF"
android:fillType="evenOdd"
android:pathData="M73.1,37C73.1,17.0637 56.9373,0.9 37,0.9C17.0627,0.9 0.9,17.0637 0.9,37C0.9,56.9373 17.0627,73.1 37,73.1C56.9373,73.1 73.1,56.9373 73.1,37"
android:strokeWidth="1"
android:strokeColor="#00000000" />
<path
android:fillColor="#58A0C4"
android:fillType="evenOdd"
android:pathData="M67.4,37C67.4,53.7895 53.7895,67.4 37,67.4C20.2105,67.4 6.6,53.7895 6.6,37C6.6,20.2105 20.2105,6.6 37,6.6C53.7895,6.6 67.4,20.2105 67.4,37"
android:strokeWidth="1"
android:strokeColor="#00000000" />
</vector>
```
|
/content/code_sandbox/wrappers/android/app/src/main/res/drawable/ic_shutter_pressed.xml
|
xml
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 357
|
```xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="path_to_url"
android:shape="rectangle">
<stroke
android:width="3dp"
android:color="#80FFFFFF" />
<solid android:color="@android:color/transparent" />
</shape>
```
|
/content/code_sandbox/wrappers/android/app/src/main/res/drawable/shape_rectangle.xml
|
xml
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 70
|
```kotlin
/*
*/
package com.example.zxingcppdemo
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Path
import android.graphics.PointF
import android.graphics.Rect
import android.util.AttributeSet
import android.view.View
import androidx.camera.core.ImageProxy
import kotlin.math.max
import kotlin.math.min
class PreviewOverlay constructor(context: Context, attributeSet: AttributeSet?) :
View(context, attributeSet) {
private val paintPath = Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.STROKE
color = 0xff00ff00.toInt()
strokeWidth = 2 * context.resources.displayMetrics.density
}
private val paintRect = Paint().apply {
style = Paint.Style.STROKE
color = 0x80ffffff.toInt()
strokeWidth = 3 * context.resources.displayMetrics.density
}
private val path = Path()
private var cropRect = Rect()
private var rotation = 0
private var s: Float = 0f
private var o: Float = 0f
fun update(viewFinder: View, image: ImageProxy, points: List<List<PointF>>) {
cropRect = image.cropRect
rotation = image.imageInfo.rotationDegrees
s = min(viewFinder.width, viewFinder.height).toFloat() / image.height
o = (max(viewFinder.width, viewFinder.height) - (image.width * s).toInt()).toFloat() / 2
path.apply {
rewind()
points.forEach {
if (!it.isEmpty()) {
val last = it.last()
moveTo(last.x, last.y)
for (p in it) {
lineTo(p.x, p.y)
}
}
}
}
invalidate()
}
override fun onDraw(canvas: Canvas) {
canvas.apply {
// draw the cropRect, which is relative to the original image orientation
save()
if (rotation == 90) {
translate(width.toFloat(), 0f)
rotate(rotation.toFloat())
}
translate(o, 0f)
scale(s, s)
drawRect(cropRect, paintRect)
restore()
// draw the path, which is relative to the (centered) rotated cropRect
when (rotation) {
0, 180 -> translate(o + cropRect.left * s, cropRect.top * s)
90 -> translate(cropRect.top * s, o + cropRect.left * s)
}
scale(s, s)
drawPath(path, paintPath)
}
}
}
```
|
/content/code_sandbox/wrappers/android/app/src/main/java/zxingcpp/app/PreviewOverlay.kt
|
kotlin
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 561
|
```qmake
-keep class zxingcpp.** { *; }
```
|
/content/code_sandbox/wrappers/android/zxingcpp/consumer-rules.pro
|
qmake
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 13
|
```kotlin
plugins {
alias(libs.plugins.android.library)
alias(libs.plugins.kotlin.android)
id("maven-publish")
id("signing")
}
android {
namespace = "zxingcpp"
// ndk version 25 is known to support c++20 (see #386)
// ndkVersion = "25.1.8937393"
defaultConfig {
compileSdk = libs.versions.androidCompileSdk.get().toInt()
minSdk = libs.versions.androidMinSdk.get().toInt()
ndk {
// speed up build: compile only arm versions
// abiFilters += listOf("armeabi-v7a", "arm64-v8a")
}
externalNativeBuild {
cmake {
arguments("-DCMAKE_BUILD_TYPE=RelWithDebInfo", "-DANDROID_ARM_NEON=ON", "-DBUILD_WRITERS=OFF")
}
}
consumerProguardFiles("consumer-rules.pro")
}
compileOptions {
sourceCompatibility(JavaVersion.VERSION_1_8)
targetCompatibility(JavaVersion.VERSION_1_8)
}
kotlinOptions {
jvmTarget = "1.8"
}
externalNativeBuild {
cmake {
path(file("src/main/cpp/CMakeLists.txt"))
}
}
lint {
disable.add("UnsafeExperimentalUsageError")
}
}
kotlin {
explicitApi()
}
dependencies {
implementation(libs.androidx.camera.core)
}
group = "io.github.zxing-cpp"
version = "2.2.0"
val javadocJar by tasks.registering(Jar::class) {
archiveClassifier.set("javadoc")
}
publishing {
publications {
register<MavenPublication>("release") {
artifactId = "android"
groupId = project.group.toString()
version = project.version.toString()
afterEvaluate {
from(components["release"])
}
artifact(javadocJar.get())
pom {
name = "zxing-cpp"
description = "Wrapper for zxing-cpp barcode image processing library"
url = "path_to_url"
licenses {
license {
url = "path_to_url"
}
}
developers {
developer {
id = "zxing-cpp"
name = "zxing-cpp community"
email = "zxingcpp@gmail.com"
}
}
scm {
connection = "scm:git:git://github.com/zxing-cpp/zxing-cpp.git"
developerConnection = "scm:git:git://github.com/zxing-cpp/zxing-cpp.git"
url = "path_to_url"
}
}
}
}
repositories {
maven {
name = "sonatype"
val releasesRepoUrl = "path_to_url"
val snapshotsRepoUrl = "path_to_url"
setUrl(if (version.toString().endsWith("SNAPSHOT")) snapshotsRepoUrl else releasesRepoUrl)
credentials {
val ossrhUsername: String? by project
val ossrhPassword: String? by project
username = ossrhUsername
password = ossrhPassword
}
}
}
}
signing {
val signingKey: String? by project
val signingPassword: String? by project
useInMemoryPgpKeys(signingKey, signingPassword)
sign(publishing.publications)
}
```
|
/content/code_sandbox/wrappers/android/zxingcpp/build.gradle.kts
|
kotlin
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 713
|
```xml
<?xml version="1.0" encoding="utf-8"?>
<manifest />
```
|
/content/code_sandbox/wrappers/android/zxingcpp/src/main/AndroidManifest.xml
|
xml
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 18
|
```kotlin
/*
*/
package zxingcpp.app
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.graphics.ImageFormat
import android.graphics.PointF
import android.graphics.Rect
import android.graphics.YuvImage
import android.hardware.camera2.CaptureRequest
import android.media.AudioManager
import android.media.MediaActionSound
import android.media.ToneGenerator
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.view.View
import androidx.annotation.OptIn
import androidx.appcompat.app.AppCompatActivity
import androidx.camera.camera2.interop.Camera2CameraControl
import androidx.camera.camera2.interop.CaptureRequestOptions
import androidx.camera.camera2.interop.ExperimentalCamera2Interop
import androidx.camera.core.AspectRatio
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.ImageProxy
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.graphics.toPointF
import androidx.lifecycle.LifecycleOwner
import com.google.zxing.BarcodeFormat
import com.google.zxing.BinaryBitmap
import com.google.zxing.DecodeHintType
import com.google.zxing.MultiFormatReader
import com.google.zxing.PlanarYUVLuminanceSource
import com.google.zxing.common.HybridBinarizer
import java.io.ByteArrayOutputStream
import java.io.File
import java.util.concurrent.Executors
import zxingcpp.app.databinding.ActivityCameraBinding
import zxingcpp.BarcodeReader
import zxingcpp.BarcodeReader.Format.*
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityCameraBinding
private val executor = Executors.newSingleThreadExecutor()
private val permissions = mutableListOf(Manifest.permission.CAMERA)
private val permissionsRequestCode = 1
private val beeper = ToneGenerator(AudioManager.STREAM_NOTIFICATION, 50)
private var lastText = String()
private var doSaveImage: Boolean = false
init {
// On R or higher, this permission has no effect. See:
// path_to_url#WRITE_EXTERNAL_STORAGE
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityCameraBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.capture.setOnClickListener {
// Disable all camera controls
it.isEnabled = false
doSaveImage = true
// Re-enable camera controls
it.isEnabled = true
}
}
private fun ImageProxy.toJpeg(): ByteArray {
// This converts the ImageProxy (from the imageAnalysis Use Case)
// to a ByteArray (compressed as JPEG) for then to be saved for debugging purposes
// This is the closest representation of the image that is passed to the
// decoding algorithm.
val yBuffer = planes[0].buffer // Y
val vuBuffer = planes[2].buffer // VU
val ySize = yBuffer.remaining()
val vuSize = vuBuffer.remaining()
val nv21 = ByteArray(ySize + vuSize)
yBuffer.get(nv21, 0, ySize)
vuBuffer.get(nv21, ySize, vuSize)
val yuvImage = YuvImage(nv21, ImageFormat.NV21, this.width, this.height, null)
val out = ByteArrayOutputStream()
yuvImage.compressToJpeg(Rect(0, 0, yuvImage.width, yuvImage.height), 90, out)
return out.toByteArray()
}
private fun saveImage(image: ImageProxy) {
try {
val currentMillis = System.currentTimeMillis().toString()
val filename =
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
.toString() + "/" + currentMillis + "_ZXingCpp.jpg"
File(filename).outputStream().use { out ->
out.write(image.toJpeg())
}
MediaActionSound().play(MediaActionSound.SHUTTER_CLICK)
} catch (e: Exception) {
beeper.startTone(ToneGenerator.TONE_CDMA_SOFT_ERROR_LITE) //Fail Tone
}
}
@OptIn(ExperimentalCamera2Interop::class)
private fun bindCameraUseCases() = binding.viewFinder.post {
val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
cameraProviderFuture.addListener({
// Set up the view finder use case to display camera preview
val preview = Preview.Builder()
.setTargetAspectRatio(AspectRatio.RATIO_16_9)
.build()
// Set up the image analysis use case which will process frames in real time
val imageAnalysis = ImageAnalysis.Builder()
.setTargetAspectRatio(AspectRatio.RATIO_16_9) // -> 1280x720
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
.build()
var frameCounter = 0
var lastFpsTimestamp = System.currentTimeMillis()
var runtimes: Long = 0
var runtime2: Long = 0
val readerJava = MultiFormatReader()
val readerCpp = BarcodeReader()
// Create a new camera selector each time, enforcing lens facing
val cameraSelector =
CameraSelector.Builder().requireLensFacing(CameraSelector.LENS_FACING_BACK).build()
// Camera provider is now guaranteed to be available
val cameraProvider = cameraProviderFuture.get()
// Apply declared configs to CameraX using the same lifecycle owner
cameraProvider.unbindAll()
val camera = cameraProvider.bindToLifecycle(
this as LifecycleOwner, cameraSelector, preview, imageAnalysis
)
// Reduce exposure time to decrease effect of motion blur
val camera2 = Camera2CameraControl.from(camera.cameraControl)
camera2.captureRequestOptions = CaptureRequestOptions.Builder()
.setCaptureRequestOption(CaptureRequest.SENSOR_SENSITIVITY, 1600)
.setCaptureRequestOption(CaptureRequest.CONTROL_AE_EXPOSURE_COMPENSATION, -8)
.build()
// Use the camera object to link our preview use case with the view
preview.setSurfaceProvider(binding.viewFinder.surfaceProvider)
imageAnalysis.setAnalyzer(executor, ImageAnalysis.Analyzer { image ->
// Early exit: image analysis is in paused state
if (binding.pause.isChecked) {
image.close()
return@Analyzer
}
if (doSaveImage) {
doSaveImage = false
saveImage(image)
}
val cropSize = image.height / 3 * 2
val cropRect = if (binding.crop.isChecked)
Rect(
(image.width - cropSize) / 2,
(image.height - cropSize) / 2,
(image.width - cropSize) / 2 + cropSize,
(image.height - cropSize) / 2 + cropSize
)
else
Rect(0, 0, image.width, image.height)
image.setCropRect(cropRect)
val startTime = System.currentTimeMillis()
var resultText: String
val resultPoints = mutableListOf<List<PointF>>()
if (binding.java.isChecked) {
val yPlane = image.planes[0]
val yBuffer = yPlane.buffer
val yStride = yPlane.rowStride
val data = ByteArray(yBuffer.remaining())
yBuffer.get(data, 0, data.size)
image.close()
val hints = mutableMapOf<DecodeHintType, Any>()
if (binding.qrcode.isChecked)
hints[DecodeHintType.POSSIBLE_FORMATS] = arrayListOf(BarcodeFormat.QR_CODE)
if (binding.tryHarder.isChecked)
hints[DecodeHintType.TRY_HARDER] = true
if (binding.tryInvert.isChecked)
hints[DecodeHintType.ALSO_INVERTED] = true
resultText = try {
val bitmap = BinaryBitmap(
HybridBinarizer(
PlanarYUVLuminanceSource(
data,
yStride,
image.height,
cropRect.left,
cropRect.top,
cropRect.width(),
cropRect.height(),
false
)
)
)
val result = readerJava.decode(bitmap, hints)
result?.let { "${it.barcodeFormat}: ${it.text}" } ?: ""
} catch (e: Throwable) {
if (e.toString() != "com.google.zxing.NotFoundException") e.toString() else ""
}
} else {
readerCpp.options.apply {
formats = if (binding.qrcode.isChecked) setOf(QR_CODE, MICRO_QR_CODE, RMQR_CODE) else setOf()
tryHarder = binding.tryHarder.isChecked
tryRotate = binding.tryRotate.isChecked
tryInvert = binding.tryInvert.isChecked
tryDownscale = binding.tryDownscale.isChecked
maxNumberOfSymbols = if (binding.multiSymbol.isChecked) 255 else 1
}
resultText = try {
image.use {
readerCpp.read(it)
}.joinToString("\n") { result ->
result.position.let {
resultPoints.add(listOf(
it.topLeft, it.topRight, it.bottomRight, it.bottomLeft
).map { p ->
p.toPointF()
})
}
"${result.format} (${result.contentType}): ${
if (result.contentType != BarcodeReader.ContentType.BINARY) {
result.text
} else {
result.bytes!!.joinToString(separator = "") { v -> "%02x".format(v) }
}
}"
}
} catch (e: Throwable) {
e.message ?: "Error"
}
}
runtimes += System.currentTimeMillis() - startTime
runtime2 += readerCpp.lastReadTime
var infoText: String? = null
if (++frameCounter == 15) {
val now = System.currentTimeMillis()
val fps = 1000 * frameCounter.toDouble() / (now - lastFpsTimestamp)
infoText = "Time: %2d/%2d ms, FPS: %.02f, (%dx%d)".format(
runtimes / frameCounter, runtime2 / frameCounter, fps, image.width, image.height
)
lastFpsTimestamp = now
frameCounter = 0
runtimes = 0
runtime2 = 0
}
camera.cameraControl.enableTorch(binding.torch.isChecked)
showResult(resultText, infoText, resultPoints, image)
})
}, ContextCompat.getMainExecutor(this))
}
private fun showResult(
resultText: String,
fpsText: String?,
points: List<List<PointF>>,
image: ImageProxy
) =
binding.viewFinder.post {
// Update the text and UI
binding.result.text = resultText
binding.result.visibility = View.VISIBLE
binding.overlay.update(binding.viewFinder, image, points)
if (fpsText != null)
binding.fps.text = fpsText
if (resultText.isNotEmpty() && lastText != resultText) {
lastText = resultText
beeper.startTone(ToneGenerator.TONE_PROP_BEEP)
}
}
override fun onResume() {
super.onResume()
// Request permissions each time the app resumes, since they can be revoked at any time
if (!hasPermissions(this)) {
ActivityCompat.requestPermissions(
this,
permissions.toTypedArray(),
permissionsRequestCode
)
} else {
bindCameraUseCases()
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray,
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == permissionsRequestCode && hasPermissions(this)) {
bindCameraUseCases()
} else {
finish() // If we don't have the required permissions, we can't run
}
}
private fun hasPermissions(context: Context) = permissions.all {
ContextCompat.checkSelfPermission(context, it) == PackageManager.PERMISSION_GRANTED
}
}
```
|
/content/code_sandbox/wrappers/android/app/src/main/java/zxingcpp/app/MainActivity.kt
|
kotlin
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 2,631
|
```kotlin
/*
*/
package zxingcpp
import android.graphics.Bitmap
import android.graphics.ImageFormat
import android.graphics.Point
import android.graphics.Rect
import android.os.Build
import androidx.camera.core.ImageProxy
import java.nio.ByteBuffer
public class BarcodeReader(public var options: Options = Options()) {
private val supportedYUVFormats: List<Int> =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
listOf(ImageFormat.YUV_420_888, ImageFormat.YUV_422_888, ImageFormat.YUV_444_888)
} else {
listOf(ImageFormat.YUV_420_888)
}
init {
System.loadLibrary("zxingcpp_android")
}
// Enumerates barcode formats known to this package.
// Note that this has to be kept synchronized with native (C++/JNI) side.
public enum class Format {
NONE, AZTEC, CODABAR, CODE_39, CODE_93, CODE_128, DATA_BAR, DATA_BAR_EXPANDED,
DATA_MATRIX, DX_FILM_EDGE, EAN_8, EAN_13, ITF, MAXICODE, PDF_417, QR_CODE, MICRO_QR_CODE, RMQR_CODE, UPC_A, UPC_E
}
public enum class ContentType {
TEXT, BINARY, MIXED, GS1, ISO15434, UNKNOWN_ECI
}
public enum class Binarizer {
LOCAL_AVERAGE, GLOBAL_HISTOGRAM, FIXED_THRESHOLD, BOOL_CAST
}
public enum class EanAddOnSymbol {
IGNORE, READ, REQUIRE
}
public enum class TextMode {
PLAIN, ECI, HRI, HEX, ESCAPED
}
public enum class ErrorType {
FORMAT, CHECKSUM, UNSUPPORTED
}
public data class Options(
var formats: Set<Format> = setOf(),
var tryHarder: Boolean = false,
var tryRotate: Boolean = false,
var tryInvert: Boolean = false,
var tryDownscale: Boolean = false,
var isPure: Boolean = false,
var binarizer: Binarizer = Binarizer.LOCAL_AVERAGE,
var downscaleFactor: Int = 3,
var downscaleThreshold: Int = 500,
var minLineCount: Int = 2,
var maxNumberOfSymbols: Int = 0xff,
var tryCode39ExtendedMode: Boolean = true,
@Deprecated("See path_to_url")
var validateCode39CheckSum: Boolean = false,
@Deprecated("See path_to_url")
var validateITFCheckSum: Boolean = false,
@Deprecated("See path_to_url")
var returnCodabarStartEnd: Boolean = false,
var returnErrors: Boolean = false,
var eanAddOnSymbol: EanAddOnSymbol = EanAddOnSymbol.IGNORE,
var textMode: TextMode = TextMode.HRI,
)
public data class Error(
val type: ErrorType,
val message: String
)
public data class Position(
val topLeft: Point,
val topRight: Point,
val bottomRight: Point,
val bottomLeft: Point,
val orientation: Double
)
public data class Result(
val format: Format,
val bytes: ByteArray?,
val text: String?,
val contentType: ContentType,
val position: Position,
val orientation: Int,
val ecLevel: String?,
val symbologyIdentifier: String?,
val sequenceSize: Int,
val sequenceIndex: Int,
val sequenceId: String?,
val readerInit: Boolean,
val lineCount: Int,
val error: Error?,
)
public val lastReadTime : Int = 0 // runtime of last read call in ms (for debugging purposes only)
public fun read(image: ImageProxy): List<Result> {
check(image.format in supportedYUVFormats) {
"Invalid image format: ${image.format}. Must be one of: $supportedYUVFormats"
}
return readYBuffer(
image.planes[0].buffer,
image.planes[0].rowStride,
image.cropRect.left,
image.cropRect.top,
image.cropRect.width(),
image.cropRect.height(),
image.imageInfo.rotationDegrees,
options
)
}
public fun read(
bitmap: Bitmap, cropRect: Rect = Rect(), rotation: Int = 0
): List<Result> {
return readBitmap(
bitmap, cropRect.left, cropRect.top, cropRect.width(), cropRect.height(), rotation, options
)
}
private external fun readYBuffer(
yBuffer: ByteBuffer, rowStride: Int, left: Int, top: Int, width: Int, height: Int, rotation: Int, options: Options
): List<Result>
private external fun readBitmap(
bitmap: Bitmap, left: Int, top: Int, width: Int, height: Int, rotation: Int, options: Options
): List<Result>
}
```
|
/content/code_sandbox/wrappers/android/zxingcpp/src/main/java/zxingcpp/BarcodeReader.kt
|
kotlin
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 1,085
|
```cmake
# Based on the Qt 5 processor detection code, so should be very accurate
# path_to_url
# Currently handles ARM (v5, v6, v7, v8), ARM64, x86 (32/64), ia64, and ppc (32/64)
# Regarding POWER/PowerPC, just as is noted in the Qt source,
# "There are many more known variants/revisions that we do not handle/detect."
set(archdetect_c_code "
#if defined(__arm__) || defined(__TARGET_ARCH_ARM) || defined(_M_ARM) || defined(_M_ARM64) || defined(__aarch64__) || defined(__ARM64__)
#if defined(__aarch64__) || defined(__ARM64__) || defined(_M_ARM64)
#error cmake_ARCH ARM64
#else
#error cmake_ARCH ARM
#endif
#elif defined(__x86_64) || defined(__x86_64__) || defined(__amd64) || defined(_M_X64)
#error cmake_ARCH x64
#elif defined(__ia64) || defined(__ia64__) || defined(_M_IA64)
#error cmake_ARCH ia64
#elif defined(__i386) || defined(__i386__) || defined(_M_IX86)
#error cmake_ARCH x86
#else
#error cmake_ARCH unknown
#endif
")
# Set ppc_support to TRUE before including this file or ppc and ppc64
# will be treated as invalid architectures since they are no longer supported by Apple
message (STATUS ${CMAKE_GENERATOR})
function(get_target_architecture output_var)
if (MSVC AND (${CMAKE_GENERATOR} MATCHES "X64$"))
set (ARCH x64)
elseif (MSVC AND (${CMAKE_GENERATOR} MATCHES "ARM$"))
set (ARCH ARM)
elseif (MSVC AND (${CMAKE_GENERATOR} MATCHES "ARM64$"))
set (ARCH ARM64)
else()
file(WRITE "${CMAKE_BINARY_DIR}/arch.c" "${archdetect_c_code}")
enable_language(C)
# Detect the architecture in a rather creative way...
# This compiles a small C program which is a series of ifdefs that selects a
# particular #error preprocessor directive whose message string contains the
# target architecture. The program will always fail to compile (both because
# file is not a valid C program, and obviously because of the presence of the
# #error preprocessor directives... but by exploiting the preprocessor in this
# way, we can detect the correct target architecture even when cross-compiling,
# since the program itself never needs to be run (only the compiler/preprocessor)
try_run(
run_result_unused
compile_result_unused
"${CMAKE_BINARY_DIR}"
"${CMAKE_BINARY_DIR}/arch.c"
COMPILE_OUTPUT_VARIABLE ARCH
)
# Parse the architecture name from the compiler output
string(REGEX MATCH "cmake_ARCH ([a-zA-Z0-9_]+)" ARCH "${ARCH}")
# Get rid of the value marker leaving just the architecture name
string(REPLACE "cmake_ARCH " "" ARCH "${ARCH}")
# If we are compiling with an unknown architecture this variable should
# already be set to "unknown" but in the case that it's empty (i.e. due
# to a typo in the code), then set it to unknown
if (NOT ARCH AND MSVC)
set (ARCH x86)
endif()
endif()
set(${output_var} "${ARCH}" PARENT_SCOPE)
endfunction()
```
|
/content/code_sandbox/wrappers/winrt/TargetArch.cmake
|
cmake
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 767
|
```batchfile
@echo off
set CMAKE_EXE="C:\Program Files\CMake\bin\cmake.exe"
rem Path to folder where the result should be copied to
rem This should be the path to the folder containing SDKManifest.xml
set DESTINATION="%~dp0\UAP\v0.8.0.0\ExtensionSDKs\ZXingWinRT\1.0.0.0"
pushd %DESTINATION%
set DESTINATION=%CD%
popd
set BUILD_LOC=%~dp0..\..\build_uwp_x86
md %BUILD_LOC%
pushd %BUILD_LOC%
%CMAKE_EXE% -G "Visual Studio 15 2017" -A Win32 -DCMAKE_SYSTEM_NAME=WindowsStore -DCMAKE_SYSTEM_VERSION=10.0 -DEXTENSION_SDK_OUTPUT="%DESTINATION%" ..\wrappers\winrt
%CMAKE_EXE% --build . --config Release
%CMAKE_EXE% --build . --config RelWithDebInfo
popd
rd /s /q %BUILD_LOC%
set BUILD_LOC=%~dp0..\..\build_uwp_x64
md %BUILD_LOC%
pushd %BUILD_LOC%
%CMAKE_EXE% -G "Visual Studio 15 2017" -A x64 -DCMAKE_SYSTEM_NAME=WindowsStore -DCMAKE_SYSTEM_VERSION=10.0 -DEXTENSION_SDK_OUTPUT="%DESTINATION%" ..\wrappers\winrt
%CMAKE_EXE% --build . --config Release
%CMAKE_EXE% --build . --config RelWithDebInfo
popd
rd /s /q %BUILD_LOC%
set BUILD_LOC=%~dp0..\..\build_uwp_arm
md %BUILD_LOC%
pushd %BUILD_LOC%
%CMAKE_EXE% -G "Visual Studio 15 2017" -A ARM -DCMAKE_SYSTEM_NAME=WindowsStore -DCMAKE_SYSTEM_VERSION=10.0 -DEXTENSION_SDK_OUTPUT="%DESTINATION%" ..\wrappers\winrt
%CMAKE_EXE% --build . --config Release
%CMAKE_EXE% --build . --config RelWithDebInfo
popd
rd /s /q %BUILD_LOC%
set BUILD_LOC=%~dp0..\..\build_uwp_arm64
md %BUILD_LOC%
pushd %BUILD_LOC%
%CMAKE_EXE% -G "Visual Studio 15 2017" -A ARM64 -DCMAKE_SYSTEM_NAME=WindowsStore -DCMAKE_SYSTEM_VERSION=10.0 -DEXTENSION_SDK_OUTPUT="%DESTINATION%" ..\wrappers\winrt
%CMAKE_EXE% --build . --config Release
%CMAKE_EXE% --build . --config RelWithDebInfo
popd
rd /s /q %BUILD_LOC%
```
|
/content/code_sandbox/wrappers/winrt/BuildWinCom.bat
|
batchfile
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 582
|
```c++
/*
*/
#include "ReadBarcode.h"
#include <android/bitmap.h>
#include <android/log.h>
#include <chrono>
#include <exception>
#include <stdexcept>
#include <string>
#include <string_view>
using namespace ZXing;
using namespace std::string_literals;
#define PACKAGE "zxingcpp/BarcodeReader$"
#define ZX_LOG_TAG "zxingcpp"
#define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, ZX_LOG_TAG, __VA_ARGS__)
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, ZX_LOG_TAG, __VA_ARGS__)
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN, ZX_LOG_TAG, __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, ZX_LOG_TAG, __VA_ARGS__)
static const char* JavaBarcodeFormatName(BarcodeFormat format)
{
// These have to be the names of the enum constants in the kotlin code.
switch (format) {
case BarcodeFormat::None: return "NONE";
case BarcodeFormat::Aztec: return "AZTEC";
case BarcodeFormat::Codabar: return "CODABAR";
case BarcodeFormat::Code39: return "CODE_39";
case BarcodeFormat::Code93: return "CODE_93";
case BarcodeFormat::Code128: return "CODE_128";
case BarcodeFormat::DataMatrix: return "DATA_MATRIX";
case BarcodeFormat::EAN8: return "EAN_8";
case BarcodeFormat::EAN13: return "EAN_13";
case BarcodeFormat::ITF: return "ITF";
case BarcodeFormat::MaxiCode: return "MAXICODE";
case BarcodeFormat::PDF417: return "PDF_417";
case BarcodeFormat::QRCode: return "QR_CODE";
case BarcodeFormat::MicroQRCode: return "MICRO_QR_CODE";
case BarcodeFormat::RMQRCode: return "RMQR_CODE";
case BarcodeFormat::DataBar: return "DATA_BAR";
case BarcodeFormat::DataBarExpanded: return "DATA_BAR_EXPANDED";
case BarcodeFormat::DXFilmEdge: return "DX_FILM_EDGE";
case BarcodeFormat::UPCA: return "UPC_A";
case BarcodeFormat::UPCE: return "UPC_E";
default: throw std::invalid_argument("Invalid BarcodeFormat");
}
}
static const char* JavaContentTypeName(ContentType contentType)
{
// These have to be the names of the enum constants in the kotlin code.
switch (contentType) {
case ContentType::Text: return "TEXT";
case ContentType::Binary: return "BINARY";
case ContentType::Mixed: return "MIXED";
case ContentType::GS1: return "GS1";
case ContentType::ISO15434: return "ISO15434";
case ContentType::UnknownECI: return "UNKNOWN_ECI";
default: throw std::invalid_argument("Invalid contentType");
}
}
static const char* JavaErrorTypeName(Error::Type errorType)
{
// These have to be the names of the enum constants in the kotlin code.
switch (errorType) {
case Error::Type::Format: return "FORMAT";
case Error::Type::Checksum: return "CHECKSUM";
case Error::Type::Unsupported: return "UNSUPPORTED";
default: throw std::invalid_argument("Invalid errorType");
}
}
inline constexpr auto hash(std::string_view sv)
{
unsigned int hash = 5381;
for (unsigned char c : sv)
hash = ((hash << 5) + hash) ^ c;
return hash;
}
inline constexpr auto operator "" _h(const char* str, size_t len){ return hash({str, len}); }
static EanAddOnSymbol EanAddOnSymbolFromString(std::string_view name)
{
switch (hash(name)) {
case "IGNORE"_h : return EanAddOnSymbol::Ignore;
case "READ"_h : return EanAddOnSymbol::Read;
case "REQUIRE"_h : return EanAddOnSymbol::Require;
default: throw std::invalid_argument("Invalid eanAddOnSymbol name");
}
}
static Binarizer BinarizerFromString(std::string_view name)
{
switch (hash(name)) {
case "LOCAL_AVERAGE"_h : return Binarizer::LocalAverage;
case "GLOBAL_HISTOGRAM"_h : return Binarizer::GlobalHistogram;
case "FIXED_THRESHOLD"_h : return Binarizer::FixedThreshold;
case "BOOL_CAST"_h : return Binarizer::BoolCast;
default: throw std::invalid_argument("Invalid binarizer name");
}
}
static TextMode TextModeFromString(std::string_view name)
{
switch (hash(name)) {
case "PLAIN"_h : return TextMode::Plain;
case "ECI"_h : return TextMode::ECI;
case "HRI"_h : return TextMode::HRI;
case "HEX"_h : return TextMode::Hex;
case "ESCAPED"_h : return TextMode::Escaped;
default: throw std::invalid_argument("Invalid textMode name");
}
}
static jstring ThrowJavaException(JNIEnv* env, const char* message)
{
// if (env->ExceptionCheck())
// return 0;
jclass cls = env->FindClass("java/lang/RuntimeException");
env->ThrowNew(cls, message);
return nullptr;
}
jstring C2JString(JNIEnv* env, const std::string& str)
{
return env->NewStringUTF(str.c_str());
}
std::string J2CString(JNIEnv* env, jstring str)
{
// Buffer size must be in bytes.
const jsize size = env->GetStringUTFLength(str);
std::string res(size, 0);
// Translates 'len' number of Unicode characters into modified
// UTF-8 encoding and place the result in the given buffer.
const jsize len = env->GetStringLength(str);
env->GetStringUTFRegion(str, 0, len, res.data());
return res;
}
static jobject NewPosition(JNIEnv* env, const Position& position)
{
jclass clsPosition = env->FindClass(PACKAGE "Position");
jclass clsPoint = env->FindClass("android/graphics/Point");
jmethodID midPointInit= env->GetMethodID(clsPoint, "<init>", "(II)V");
auto NewPoint = [&](const PointI& point) {
return env->NewObject(clsPoint, midPointInit, point.x, point.y);
};
jmethodID midPositionInit= env->GetMethodID(
clsPosition, "<init>",
"(Landroid/graphics/Point;"
"Landroid/graphics/Point;"
"Landroid/graphics/Point;"
"Landroid/graphics/Point;"
"D)V");
return env->NewObject(
clsPosition, midPositionInit,
NewPoint(position[0]),
NewPoint(position[1]),
NewPoint(position[2]),
NewPoint(position[3]),
position.orientation());
}
static jbyteArray NewByteArray(JNIEnv* env, const std::vector<uint8_t>& byteArray)
{
auto size = static_cast<jsize>(byteArray.size());
jbyteArray res = env->NewByteArray(size);
env->SetByteArrayRegion(res, 0, size, reinterpret_cast<const jbyte*>(byteArray.data()));
return res;
}
static jobject NewEnum(JNIEnv* env, const char* value, const char* type)
{
auto className = PACKAGE ""s + type;
jclass cls = env->FindClass(className.c_str());
jfieldID fidCT = env->GetStaticFieldID(cls, value, ("L" + className + ";").c_str());
return env->GetStaticObjectField(cls, fidCT);
}
static jobject NewError(JNIEnv* env, const Error& error)
{
jclass cls = env->FindClass(PACKAGE "Error");
jmethodID midInit = env->GetMethodID(cls, "<init>", "(L" PACKAGE "ErrorType;" "Ljava/lang/String;)V");
return env->NewObject(cls, midInit, NewEnum(env, JavaErrorTypeName(error.type()), "ErrorType"), C2JString(env, error.msg()));
}
static jobject NewResult(JNIEnv* env, const Barcode& result)
{
jclass cls = env->FindClass(PACKAGE "Result");
jmethodID midInit = env->GetMethodID(
cls, "<init>",
"(L" PACKAGE "Format;"
"[B"
"Ljava/lang/String;"
"L" PACKAGE "ContentType;"
"L" PACKAGE "Position;"
"I"
"Ljava/lang/String;"
"Ljava/lang/String;"
"I"
"I"
"Ljava/lang/String;"
"Z"
"I"
"L" PACKAGE "Error;"
")V");
bool valid = result.isValid();
return env->NewObject(cls, midInit,
NewEnum(env, JavaBarcodeFormatName(result.format()), "Format"),
valid ? NewByteArray(env, result.bytes()) : nullptr,
valid ? C2JString(env, result.text()) : nullptr,
NewEnum(env, JavaContentTypeName(result.contentType()), "ContentType"),
NewPosition(env, result.position()),
result.orientation(),
valid ? C2JString(env, result.ecLevel()) : nullptr,
valid ? C2JString(env, result.symbologyIdentifier()) : nullptr,
result.sequenceSize(),
result.sequenceIndex(),
valid ? C2JString(env, result.sequenceId()) : nullptr,
result.readerInit(),
result.lineCount(),
result.error() ? NewError(env, result.error()) : nullptr
);
}
static jobject Read(JNIEnv *env, jobject thiz, ImageView image, const ReaderOptions& opts)
{
try {
auto startTime = std::chrono::high_resolution_clock::now();
auto barcodes = ReadBarcodes(image, opts);
auto duration = std::chrono::high_resolution_clock::now() - startTime;
// LOGD("time: %4d ms\n", (int)std::chrono::duration_cast<std::chrono::milliseconds>(duration).count());
auto time = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
env->SetIntField(thiz, env->GetFieldID(env->GetObjectClass(thiz), "lastReadTime", "I"), time);
jclass clsList = env->FindClass("java/util/ArrayList");
jobject objList = env->NewObject(clsList, env->GetMethodID(clsList, "<init>", "()V"));
if (!barcodes.empty()) {
jmethodID midAdd = env->GetMethodID(clsList, "add", "(Ljava/lang/Object;)Z");
for (const auto& barcode: barcodes)
env->CallBooleanMethod(objList, midAdd, NewResult(env, barcode));
}
return objList;
} catch (const std::exception& e) {
return ThrowJavaException(env, e.what());
} catch (...) {
return ThrowJavaException(env, "Unknown exception");
}
}
static bool GetBooleanField(JNIEnv* env, jclass cls, jobject opts, const char* name)
{
return env->GetBooleanField(opts, env->GetFieldID(cls, name, "Z"));
}
static int GetIntField(JNIEnv* env, jclass cls, jobject opts, const char* name)
{
return env->GetIntField(opts, env->GetFieldID(cls, name, "I"));
}
static std::string GetEnumField(JNIEnv* env, jclass cls, jobject opts, const char* name, const char* type)
{
auto className = PACKAGE ""s + type;
jmethodID midName = env->GetMethodID(env->FindClass(className.c_str()), "name", "()Ljava/lang/String;");
jobject objField = env->GetObjectField(opts, env->GetFieldID(cls, name, ("L"s + className + ";").c_str()));
return J2CString(env, static_cast<jstring>(env->CallObjectMethod(objField, midName)));
}
static BarcodeFormats GetFormats(JNIEnv* env, jclass clsOptions, jobject opts)
{
jobject objField = env->GetObjectField(opts, env->GetFieldID(clsOptions, "formats", "Ljava/util/Set;"));
jmethodID midToArray = env->GetMethodID(env->FindClass("java/util/Set"), "toArray", "()[Ljava/lang/Object;");
auto objArray = static_cast<jobjectArray>(env->CallObjectMethod(objField, midToArray));
if (!objArray)
return {};
jmethodID midName = env->GetMethodID(env->FindClass(PACKAGE "Format"), "name", "()Ljava/lang/String;");
BarcodeFormats ret;
for (int i = 0, size = env->GetArrayLength(objArray); i < size; ++i) {
auto objName = static_cast<jstring>(env->CallObjectMethod(env->GetObjectArrayElement(objArray, i), midName));
ret |= BarcodeFormatFromString(J2CString(env, objName));
}
return ret;
}
static ReaderOptions CreateReaderOptions(JNIEnv* env, jobject opts)
{
jclass cls = env->GetObjectClass(opts);
return ReaderOptions()
.setFormats(GetFormats(env, cls, opts))
.setTryHarder(GetBooleanField(env, cls, opts, "tryHarder"))
.setTryRotate(GetBooleanField(env, cls, opts, "tryRotate"))
.setTryInvert(GetBooleanField(env, cls, opts, "tryInvert"))
.setTryDownscale(GetBooleanField(env, cls, opts, "tryDownscale"))
.setIsPure(GetBooleanField(env, cls, opts, "isPure"))
.setBinarizer(BinarizerFromString(GetEnumField(env, cls, opts, "binarizer", "Binarizer")))
.setDownscaleThreshold(GetIntField(env, cls, opts, "downscaleThreshold"))
.setDownscaleFactor(GetIntField(env, cls, opts, "downscaleFactor"))
.setMinLineCount(GetIntField(env, cls, opts, "minLineCount"))
.setMaxNumberOfSymbols(GetIntField(env, cls, opts, "maxNumberOfSymbols"))
.setTryCode39ExtendedMode(GetBooleanField(env, cls, opts, "tryCode39ExtendedMode"))
.setReturnErrors(GetBooleanField(env, cls, opts, "returnErrors"))
.setEanAddOnSymbol(EanAddOnSymbolFromString(GetEnumField(env, cls, opts, "eanAddOnSymbol", "EanAddOnSymbol")))
.setTextMode(TextModeFromString(GetEnumField(env, cls, opts, "textMode", "TextMode")))
;
}
extern "C" JNIEXPORT jobject JNICALL
Java_zxingcpp_BarcodeReader_readYBuffer(
JNIEnv *env, jobject thiz, jobject yBuffer, jint rowStride,
jint left, jint top, jint width, jint height, jint rotation, jobject options)
{
const uint8_t* pixels = static_cast<uint8_t *>(env->GetDirectBufferAddress(yBuffer));
auto image =
ImageView{pixels + top * rowStride + left, width, height, ImageFormat::Lum, rowStride}
.rotated(rotation);
return Read(env, thiz, image, CreateReaderOptions(env, options));
}
struct LockedPixels
{
JNIEnv* env;
jobject bitmap;
void *pixels = nullptr;
LockedPixels(JNIEnv* env, jobject bitmap) : env(env), bitmap(bitmap) {
if (AndroidBitmap_lockPixels(env, bitmap, &pixels) != ANDROID_BITMAP_RESUT_SUCCESS)
pixels = nullptr;
}
operator const uint8_t*() const { return static_cast<const uint8_t*>(pixels); }
~LockedPixels() {
if (pixels)
AndroidBitmap_unlockPixels(env, bitmap);
}
};
extern "C" JNIEXPORT jobject JNICALL
Java_zxingcpp_BarcodeReader_readBitmap(
JNIEnv* env, jobject thiz, jobject bitmap,
jint left, jint top, jint width, jint height, jint rotation, jobject options)
{
AndroidBitmapInfo bmInfo;
AndroidBitmap_getInfo(env, bitmap, &bmInfo);
ImageFormat fmt = ImageFormat::None;
switch (bmInfo.format) {
case ANDROID_BITMAP_FORMAT_A_8: fmt = ImageFormat::Lum; break;
case ANDROID_BITMAP_FORMAT_RGBA_8888: fmt = ImageFormat::RGBA; break;
default: return ThrowJavaException(env, "Unsupported image format in AndroidBitmap");
}
auto pixels = LockedPixels(env, bitmap);
if (!pixels)
return ThrowJavaException(env, "Failed to lock/read AndroidBitmap data");
auto image =
ImageView{pixels, (int)bmInfo.width, (int)bmInfo.height, fmt, (int)bmInfo.stride}
.cropped(left, top, width, height)
.rotated(rotation);
return Read(env, thiz, image, CreateReaderOptions(env, options));
}
```
|
/content/code_sandbox/wrappers/android/zxingcpp/src/main/cpp/ZXingCpp.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 3,571
|
```objective-c
/*
*/
#pragma once
#include "BarcodeFormat.h"
#include "ReaderOptions.h"
#include <memory>
namespace ZXing {
public enum class BarcodeType : int {
AZTEC,
CODABAR,
CODE_39,
CODE_93,
CODE_128,
DATA_MATRIX,
DX_FILM_EDGE,
EAN_8,
EAN_13,
ITF,
MAXICODE,
PDF_417,
QR_CODE,
MICRO_QR_CODE,
RMQR_CODE,
RSS_14,
RSS_EXPANDED,
UPC_A,
UPC_E
};
ref class ReadResult;
public ref class BarcodeReader sealed
{
public:
BarcodeReader(bool tryHarder, bool tryRotate, const Platform::Array<BarcodeType>^ types);
BarcodeReader(bool tryHarder, bool tryRotate);
BarcodeReader(bool tryHarder);
ReadResult^ Read(Windows::Graphics::Imaging::SoftwareBitmap^ bitmap, int cropWidth, int cropHeight);
private:
~BarcodeReader();
void init(bool tryHarder, bool tryRotate, const Platform::Array<BarcodeType>^ types);
static BarcodeFormat ConvertRuntimeToNative(BarcodeType type);
static BarcodeType ConvertNativeToRuntime(BarcodeFormat format);
std::unique_ptr<ReaderOptions> m_opts;
};
} // ZXing
```
|
/content/code_sandbox/wrappers/winrt/BarcodeReader.h
|
objective-c
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 282
|
```objective-c
/*
*/
#pragma once
namespace ZXing {
public ref class ReadResult sealed
{
public:
property Platform::String^ Format {
Platform::String^ get() {
return m_format;
}
}
property Platform::String^ Text {
Platform::String^ get() {
return m_text;
}
}
property BarcodeType Type {
BarcodeType get() {
return m_barcode_type;
}
}
internal:
ReadResult(Platform::String^ format, Platform::String^ text, BarcodeType type) : m_format(format), m_text(text), m_barcode_type(type) {}
private:
Platform::String^ m_format;
Platform::String^ m_text;
BarcodeType m_barcode_type;
};
} // ZXing
```
|
/content/code_sandbox/wrappers/winrt/ReadResult.h
|
objective-c
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 165
|
```cmake
SET (CMAKE_SYSTEM_NAME WindowsStore)
SET (CMAKE_SYSTEM_VERSION 10.0)
```
|
/content/code_sandbox/wrappers/winrt/Toolchain-Win10.cmake
|
cmake
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 21
|
```xml
<?xml version="1.0" encoding="utf-8" ?>
<FileList
DisplayName="ZXing Barcode Scanner Library"
ProductFamilyName="ZXingWinRT"
MoreInfo="path_to_url"
MinVSVersion="14.0"
AppliesTo="WindowsAppContainer"
SupportsMultipleVersions="Error"
SupportedArchitectures="x86;x64;ARM;ARM64">
<File Reference="ZXing.winmd" Implementation="ZXing.dll" />
</FileList>
```
|
/content/code_sandbox/wrappers/winrt/UAP/v0.8.0.0/ExtensionSDKs/ZXingWinRT/1.0.0.0/SDKManifest.xml
|
xml
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 106
|
```xml
<?xml version="1.0"?>
<package>
<metadata>
<id>huycn.zxingcpp.winrt</id>
<version>1.0.0</version>
<title>ZXingWinRT</title>
<authors>Nu-book Inc.</authors>
<owners>Nu-book Inc.</owners>
<licenseUrl>path_to_url
<projectUrl>path_to_url
<description>C++ port of ZXing barcode scanner library</description>
<releaseNotes>Bug fixes and improvements for many readers and decoders</releaseNotes>
<tags>zxing barcode scanner qrcode</tags>
</metadata>
<files>
<file src="..\UAP\v0.8.0.0\ExtensionSDKs\ZXingWinRT\1.0.0.0\References\CommonConfiguration\Neutral\ZXing.winmd" target="lib\uap10.0"/>
<file src="..\UAP\v0.8.0.0\ExtensionSDKs\ZXingWinRT\1.0.0.0\References\CommonConfiguration\Neutral\ZXing.pri" target="runtimes\win10-arm\native"/>
<file src="..\UAP\v0.8.0.0\ExtensionSDKs\ZXingWinRT\1.0.0.0\Redist\Retail\ARM\ZXing.dll" target="runtimes\win10-arm\native"/>
<file src="..\UAP\v0.8.0.0\ExtensionSDKs\ZXingWinRT\1.0.0.0\References\CommonConfiguration\Neutral\ZXing.pri" target="runtimes\win10-arm64\native"/>
<file src="..\UAP\v0.8.0.0\ExtensionSDKs\ZXingWinRT\1.0.0.0\Redist\Retail\ARM64\ZXing.dll" target="runtimes\win10-arm64\native"/>
<file src="..\UAP\v0.8.0.0\ExtensionSDKs\ZXingWinRT\1.0.0.0\References\CommonConfiguration\Neutral\ZXing.pri" target="runtimes\win10-x64\native"/>
<file src="..\UAP\v0.8.0.0\ExtensionSDKs\ZXingWinRT\1.0.0.0\Redist\Retail\x64\ZXing.dll" target="runtimes\win10-x64\native"/>
<file src="..\UAP\v0.8.0.0\ExtensionSDKs\ZXingWinRT\1.0.0.0\References\CommonConfiguration\Neutral\ZXing.pri" target="runtimes\win10-x86\native"/>
<file src="..\UAP\v0.8.0.0\ExtensionSDKs\ZXingWinRT\1.0.0.0\Redist\Retail\x86\ZXing.dll" target="runtimes\win10-x86\native"/>
<file src="ZXingWinRT.targets" target="build\native"/>
</files>
</package>
```
|
/content/code_sandbox/wrappers/winrt/nuget/ZXingWinRT.nuspec
|
xml
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 680
|
```xml
<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="path_to_url">
<PropertyGroup>
<ZXingCpp-Platform Condition="'$(Platform)' == 'Win32'">x86</ZXingCpp-Platform>
<ZXingCpp-Platform Condition="'$(Platform)' != 'Win32'">$(Platform)</ZXingCpp-Platform>
</PropertyGroup>
<ItemGroup Condition="'$(TargetPlatformIdentifier)' == 'UAP'">
<Reference Include="$(MSBuildThisFileDirectory)..\..\lib\uap10.0\ZXing.winmd">
<Implementation>ZXing.dll</Implementation>
</Reference>
<ReferenceCopyLocalPaths Include="$(MSBuildThisFileDirectory)..\..\runtimes\win10-$(ZXingCpp-Platform)\native\ZXing.dll" />
</ItemGroup>
</Project>
```
|
/content/code_sandbox/wrappers/winrt/nuget/ZXingWinRT.targets
|
xml
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 187
|
```c++
/*
*/
#if (_MSC_VER >= 1915)
#define no_init_all deprecated
#pragma warning(disable : 4996)
#endif
#include "BarcodeReader.h"
#include "BarcodeFormat.h"
#include "ReaderOptions.h"
#include "ReadBarcode.h"
#include "ReadResult.h"
#include "Utf.h"
#include <algorithm>
#include <MemoryBuffer.h>
#include <stdexcept>
#include <wrl.h>
using namespace Microsoft::WRL;
using namespace Windows::Foundation;
using namespace Windows::Graphics::Imaging;
namespace ZXing {
BarcodeReader::BarcodeReader(bool tryHarder, bool tryRotate, const Platform::Array<BarcodeType>^ types)
{
init(tryHarder, tryRotate, types);
}
BarcodeReader::BarcodeReader(bool tryHarder, bool tryRotate)
{
init(tryHarder, tryRotate, nullptr);
}
BarcodeReader::BarcodeReader(bool tryHarder)
{
init(tryHarder, tryHarder, nullptr);
}
void
BarcodeReader::init(bool tryHarder, bool tryRotate, const Platform::Array<BarcodeType>^ types)
{
m_opts.reset(new ReaderOptions());
m_opts->setTryHarder(tryHarder);
m_opts->setTryRotate(tryRotate);
m_opts->setTryInvert(tryHarder);
if (types != nullptr && types->Length > 0) {
BarcodeFormats barcodeFormats;
for (BarcodeType type : types) {
barcodeFormats |= BarcodeReader::ConvertRuntimeToNative(type);
}
m_opts->setFormats(barcodeFormats);
}
}
BarcodeReader::~BarcodeReader()
{
}
BarcodeFormat BarcodeReader::ConvertRuntimeToNative(BarcodeType type)
{
switch (type) {
case BarcodeType::AZTEC:
return BarcodeFormat::Aztec;
case BarcodeType::CODABAR:
return BarcodeFormat::Codabar;
case BarcodeType::CODE_128:
return BarcodeFormat::Code128;
case BarcodeType::CODE_39:
return BarcodeFormat::Code39;
case BarcodeType::CODE_93:
return BarcodeFormat::Code93;
case BarcodeType::DATA_MATRIX:
return BarcodeFormat::DataMatrix;
case BarcodeType::EAN_13:
return BarcodeFormat::EAN13;
case BarcodeType::EAN_8:
return BarcodeFormat::EAN8;
case BarcodeType::ITF:
return BarcodeFormat::ITF;
case BarcodeType::MAXICODE:
return BarcodeFormat::MaxiCode;
case BarcodeType::PDF_417:
return BarcodeFormat::PDF417;
case BarcodeType::QR_CODE:
return BarcodeFormat::QRCode;
case BarcodeType::MICRO_QR_CODE:
return BarcodeFormat::MicroQRCode;
case BarcodeType::RMQR_CODE:
return BarcodeFormat::RMQRCode;
case BarcodeType::RSS_14:
return BarcodeFormat::DataBar;
case BarcodeType::RSS_EXPANDED:
return BarcodeFormat::DataBarExpanded;
case BarcodeType::DX_FILM_EDGE:
return BarcodeFormat::DXFilmEdge;
case BarcodeType::UPC_A:
return BarcodeFormat::UPCA;
case BarcodeType::UPC_E:
return BarcodeFormat::UPCE;
default:
std::wstring typeAsString = type.ToString()->Begin();
throw std::invalid_argument("Unknown Barcode Type: " + ToUtf8(typeAsString));
}
}
BarcodeType BarcodeReader::ConvertNativeToRuntime(BarcodeFormat format)
{
switch (format) {
case BarcodeFormat::Aztec:
return BarcodeType::AZTEC;
case BarcodeFormat::Codabar:
return BarcodeType::CODABAR;
case BarcodeFormat::Code128:
return BarcodeType::CODE_128;
case BarcodeFormat::Code39:
return BarcodeType::CODE_39;
case BarcodeFormat::Code93:
return BarcodeType::CODE_93;
case BarcodeFormat::DataMatrix:
return BarcodeType::DATA_MATRIX;
case BarcodeFormat::EAN13:
return BarcodeType::EAN_13;
case BarcodeFormat::EAN8:
return BarcodeType::EAN_8;
case BarcodeFormat::ITF:
return BarcodeType::ITF;
case BarcodeFormat::MaxiCode:
return BarcodeType::MAXICODE;
case BarcodeFormat::PDF417:
return BarcodeType::PDF_417;
case BarcodeFormat::QRCode:
return BarcodeType::QR_CODE;
case BarcodeFormat::MicroQRCode:
return BarcodeType::MICRO_QR_CODE;
case BarcodeFormat::RMQRCode:
return BarcodeType::RMQR_CODE;
case BarcodeFormat::DataBar:
return BarcodeType::RSS_14;
case BarcodeFormat::DataBarExpanded:
return BarcodeType::RSS_EXPANDED;
case BarcodeFormat::DXFilmEdge:
return BarcodeType::DX_FILM_EDGE;
case BarcodeFormat::UPCA:
return BarcodeType::UPC_A;
case BarcodeFormat::UPCE:
return BarcodeType::UPC_E;
default:
throw std::invalid_argument("Unknown Barcode Format ");
}
}
static Platform::String^ ToPlatformString(const std::string& str)
{
std::wstring wstr = FromUtf8(str);
return ref new Platform::String(wstr.c_str(), (unsigned)wstr.length());
}
ReadResult^
BarcodeReader::Read(SoftwareBitmap^ bitmap, int cropWidth, int cropHeight)
{
try {
cropWidth = cropWidth <= 0 ? bitmap->PixelWidth : std::min(bitmap->PixelWidth, cropWidth);
cropHeight = cropHeight <= 0 ? bitmap->PixelHeight : std::min(bitmap->PixelHeight, cropHeight);
int cropLeft = (bitmap->PixelWidth - cropWidth) / 2;
int cropTop = (bitmap->PixelHeight - cropHeight) / 2;
auto inBuffer = bitmap->LockBuffer(BitmapBufferAccessMode::Read);
auto inMemRef = inBuffer->CreateReference();
ComPtr<IMemoryBufferByteAccess> inBufferAccess;
if (SUCCEEDED(ComPtr<IUnknown>(reinterpret_cast<IUnknown*>(inMemRef)).As(&inBufferAccess))) {
BYTE* inBytes = nullptr;
UINT32 inCapacity = 0;
inBufferAccess->GetBuffer(&inBytes, &inCapacity);
ImageFormat fmt = ImageFormat::None;
switch (bitmap->BitmapPixelFormat)
{
case BitmapPixelFormat::Gray8: fmt = ImageFormat::Lum; break;
case BitmapPixelFormat::Bgra8: fmt = ImageFormat::BGRA; break;
case BitmapPixelFormat::Rgba8: fmt = ImageFormat::RGBA; break;
default:
throw std::runtime_error("Unsupported BitmapPixelFormat");
}
auto img = ImageView(inBytes, bitmap->PixelWidth, bitmap->PixelHeight, fmt, inBuffer->GetPlaneDescription(0).Stride)
.cropped(cropLeft, cropTop, cropWidth, cropHeight);
auto barcode = ReadBarcode(img, *m_opts);
if (barcode.isValid()) {
return ref new ReadResult(ToPlatformString(ZXing::ToString(barcode.format())), ToPlatformString(barcode.text()), ConvertNativeToRuntime(barcode.format()));
}
} else {
throw std::runtime_error("Failed to read bitmap's data");
}
}
catch (const std::exception& e) {
OutputDebugStringA(e.what());
}
catch (...) {
}
return nullptr;
}
} // ZXing
```
|
/content/code_sandbox/wrappers/winrt/BarcodeReader.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 1,573
|
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>zxing-cpp/wasm reader demo</title>
<link rel="shortcut icon" href="#" />
<script src="zxing_reader.js"></script>
<script>
var zxing = ZXing().then(function(instance) {
zxing = instance; // this line is supposedly not required but with current emsdk it is :-/
});
async function readBarcodes() {
let format = document.getElementById("format").value;
let file = document.getElementById("file").files[0];
let arrayBuffer = await file.arrayBuffer();
let u8Buffer = new Uint8Array(arrayBuffer);
let zxingBuffer = zxing._malloc(u8Buffer.length);
zxing.HEAPU8.set(u8Buffer, zxingBuffer);
let results = zxing.readBarcodesFromImage(zxingBuffer, u8Buffer.length, true, format, 0xff);
zxing._free(zxingBuffer);
showResults(results);
showImageWithResults(file, results);
}
function showImageWithResults(file, results) {
var canvas = document.getElementById("canvas");
var img = new Image()
img.addEventListener('load', function() {
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
for (let i = 0; i < results.size(); i += 1) {
const { position } = results.get(i);
// Draw outline square
ctx.beginPath();
ctx.moveTo(position.topLeft.x, position.topLeft.y);
ctx.lineTo(position.topRight.x, position.topRight.y);
ctx.lineTo(position.bottomRight.x, position.bottomRight.y);
ctx.lineTo(position.bottomLeft.x, position.bottomLeft.y);
ctx.closePath();
ctx.strokeStyle = "red";
ctx.lineWidth = 4;
ctx.stroke();
// Draw number inside square
const text = {
text: i + 1,
size: Math.abs((position.bottomRight.y - position.topLeft.y)) / 2,
x: (position.topLeft.x + position.bottomRight.x) / 2.0,
y: (position.topLeft.y + position.bottomRight.y) / 2.0,
};
ctx.fillStyle = "white";
ctx.font = `bold ${text.size}px sans`;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text.text, text.x, text.y);
ctx.strokeStyle = "red";
ctx.lineWidth = 2;
ctx.strokeText(text.text, text.x, text.y);
}
});
img.src = URL.createObjectURL(file)
}
function escapeTags(htmlStr) {
return htmlStr.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
}
function u8a2hex(bytes) {
return bytes.reduce((a, b) => a + b.toString(16).padStart(2, '0') + ' ', '');
}
function showResults(results) {
const resultsDiv = document.getElementById("results");
resultsDiv.innerHTML = "";
if (results.size() === 0) {
resultsDiv.innerHTML += "No " + (document.getElementById("format").value || "barcode") + " found";
}
else {
for (let i = 0; i < results.size(); i += 1) {
const { format, text, bytes, error } = results.get(i);
resultsDiv.innerHTML += "<li>Format: <strong>" + format + "</strong>"
+ "<pre>" + (escapeTags(text) || '<font color="red">Error: ' + error + '</font>') + "</pre>"
+ "<pre>" + u8a2hex(bytes) + "</pre>"
+ "</li>";
}
}
}
</script>
</head>
<body style="text-align: left">
<h2>zxing-cpp/wasm reader demo</h2>
<p>
This is a simple demo of the wasm wrapper of <a href="path_to_url">zxing-cpp</a>
scanning for barcodes in image files.
</p>
<p></p>
<div>
Scan Format:
<select id="format" onchange='readBarcodes()'>
<option value="" selected="">Any</option>
<option value="Aztec">Aztec</option>
<option value="Codabar">Codabar</option>
<option value="Code39">Code 39</option>
<option value="Code93">Code 93</option>
<option value="Code128">Code 128</option>
<option value="DataMatrix">DataMatrix</option>
<option value="DataBar">DataBar</option>
<option value="DataBarExpanded">DataBarExpanded</option>
<option value="DXFilmEdge">DXFilmEdge</option>
<option value="EAN8">EAN-8</option>
<option value="EAN13">EAN-13</option>
<option value="ITF">ITF</option>
<option value="PDF417">PDF417</option>
<option value="QRCode">QR Code</option>
<option value="MicroQRCode">Micro QRCode</option>
<option value="RMQRCode">rMQR Code</option>
<option value="UPCA">UPC-A</option>
<option value="UPCE">UPC-E</option>
<option value="LinearCodes">Linear Codes</option>
<option value="MatrixCodes">Matrix Codes</option>
</select>
Image File: <input id="file" type="file" accept="image/png, image/jpeg" onchange="readBarcodes()" />
<br /><br />
<canvas id="canvas" width="640" height="480"></canvas>
<br /><br />
<ol id="results"></ol>
</div>
</body>
</html>
```
|
/content/code_sandbox/wrappers/wasm/demo_reader.html
|
html
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 1,340
|
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>zxing-cpp/wasm writer demo</title>
<link rel="shortcut icon" href="#" />
<script src="zxing_writer.js"></script>
<script>
var zxing = ZXing().then(function(instance) {
zxing = instance; // this line is supposedly not required but with current emsdk it is :-/
});
function generateBarcode() {
var text = document.getElementById("input_text").value;
var format = document.getElementById("input_format").value;
var charset = document.getElementById("input_charset").value;
var margin = parseInt(document.getElementById("input_margin").value);
var width = parseInt(document.getElementById("input_width").value);
var height = parseInt(document.getElementById("input_height").value);
var eccLevel = parseInt(document.getElementById("input_ecclevel").value);
var container = document.getElementById("write_result")
var result = zxing.generateBarcode(text, format, charset, margin, width, height, eccLevel);
if (result.image) {
showImage(container, result.image);
} else {
container.innerHTML = '<font color="red">Error: ' + result.error + '</font>';
container.style.width = '300px';
}
result.delete();
}
function showImage(container, fileData) {
container.innerHTML = '';
var img = document.createElement("img");
img.addEventListener('load', function() {
container.style.width = img.width + 'px';
container.style.height = img.height + 'px';
});
img.src = URL.createObjectURL(new Blob([fileData]))
container.appendChild(img);
}
</script>
<style>
#input_text {
width: 240px;
}
select,
input {
margin: 3px 0px;
width: 120px;
}
tr td:first-child {
text-align: right;
}
div {
float: left;
margin: 0.5em;
}
</style>
</head>
<body>
<h2>zxing-cpp/wasm writer demo</h2>
<p>
This is a simple demo of the wasm wrapper of <a href="path_to_url">zxing-cpp</a>
for generating barcodes.
</p>
<p></p>
<div>
Enter your text here:<br />
<textarea id="input_text"></textarea>
<br />
<table>
<tr>
<td>Format:</td>
<td>
<select id="input_format">
<option value="Aztec">Aztec</option>
<option value="Codabar">Codabar</option>
<option value="Code39">Code 39</option>
<option value="Code93">Code 93</option>
<option value="Code128">Code 128</option>
<option value="DataMatrix">DataMatrix</option>
<option value="EAN8">EAN-8</option>
<option value="EAN13">EAN-13</option>
<option value="ITF">ITF</option>
<option value="PDF417">PDF417</option>
<option value="QRCode" selected="">QR Code</option>
<option value="UPCA">UPC-A</option>
<option value="UPCE">UPC-E</option>
</select>
</td>
</tr>
<tr>
<td>Encoding:</td>
<td>
<select id="input_charset">
<option value="Cp437">Cp437</option>
<option value="ISO-8859-1">ISO-8859-1</option>
<option value="ISO-8859-2">ISO-8859-2</option>
<option value="ISO-8859-3">ISO-8859-3</option>
<option value="ISO-8859-4">ISO-8859-4</option>
<option value="ISO-8859-5">ISO-8859-5</option>
<option value="ISO-8859-6">ISO-8859-6</option>
<option value="ISO-8859-7">ISO-8859-7</option>
<option value="ISO-8859-8">ISO-8859-8</option>
<option value="ISO-8859-9">ISO-8859-9</option>
<option value="ISO-8859-10">ISO-8859-10</option>
<option value="ISO-8859-11">ISO-8859-11</option>
<option value="ISO-8859-13">ISO-8859-13</option>
<option value="ISO-8859-14">ISO-8859-14</option>
<option value="ISO-8859-15">ISO-8859-15</option>
<option value="ISO-8859-16">ISO-8859-16</option>
<option value="Shift_JIS">Shift_JIS</option>
<option value="windows-1250">windows-1250</option>
<option value="windows-1251">windows-1251</option>
<option value="windows-1252">windows-1252</option>
<option value="windows-1256">windows-1256</option>
<option value="UTF-16BE">UTF-16BE</option>
<option value="UTF-8" selected="">UTF-8</option>
<option value="ASCII">ASCII</option>
<option value="Big5">Big5</option>
<option value="GB2312">GB2312</option>
<option value="GB18030">GB18030</option>
<option value="EUC-CN">EUC-CN</option>
<option value="GBK">GBK</option>
<option value="EUC-KR">EUC-KR</option>
</select>
</td>
</tr>
<td>ECC Level:</td>
<td>
<select id="input_ecclevel">
<option value="-1">Default</option>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
</select>
</td>
</tr>
<td>Quiet Zone:</td>
<td><input id="input_margin" type="number" value="10" /></td>
</tr>
<td>Image Width:</td>
<td><input id="input_width" type="number" value="200" /></td>
</tr>
<td>Image Height:</td>
<td><input id="input_height" type="number" value="200" /></td>
</tr>
</table>
<br />
<input type="button" value="Generate" onclick="generateBarcode()" />
</div>
<div id="write_result"></div>
</body>
</html>
```
|
/content/code_sandbox/wrappers/wasm/demo_writer.html
|
html
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 1,615
|
```c++
/*
*/
#include "BarcodeFormat.h"
#include "MultiFormatWriter.h"
#include "BitMatrix.h"
#include "CharacterSet.h"
#include <string>
#include <memory>
#include <exception>
#include <emscripten/bind.h>
#include <emscripten/val.h>
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include <stb_image_write.h>
class ImageData
{
public:
uint8_t* const buffer;
const int length;
ImageData(uint8_t* buf, int len) : buffer(buf), length(len) {}
~ImageData() { STBIW_FREE(buffer); }
};
class WriteResult
{
std::shared_ptr<ImageData> _image;
std::string _error;
public:
WriteResult(const std::shared_ptr<ImageData>& image) : _image(image) {}
WriteResult(std::string error) : _error(std::move(error)) {}
std::string error() const { return _error; }
emscripten::val image() const
{
if (_image != nullptr)
return emscripten::val(emscripten::typed_memory_view(_image->length, _image->buffer));
else
return emscripten::val::null();
}
};
WriteResult generateBarcode(std::wstring text, std::string format, std::string encoding, int margin, int width, int height, int eccLevel)
{
using namespace ZXing;
try {
auto barcodeFormat = BarcodeFormatFromString(format);
if (barcodeFormat == BarcodeFormat::None)
return {"Unsupported format: " + format};
MultiFormatWriter writer(barcodeFormat);
if (margin >= 0)
writer.setMargin(margin);
CharacterSet charset = CharacterSetFromString(encoding);
if (charset != CharacterSet::Unknown)
writer.setEncoding(charset);
if (eccLevel >= 0 && eccLevel <= 8)
writer.setEccLevel(eccLevel);
auto buffer = ToMatrix<uint8_t>(writer.encode(text, width, height));
int len;
uint8_t* bytes = stbi_write_png_to_mem(buffer.data(), 0, buffer.width(), buffer.height(), 1, &len);
if (bytes == nullptr)
return {"Unknown error"};
return {std::make_shared<ImageData>(bytes, len)};
} catch (const std::exception& e) {
return {e.what()};
} catch (...) {
return {"Unknown error"};
}
}
EMSCRIPTEN_BINDINGS(BarcodeWriter)
{
using namespace emscripten;
class_<WriteResult>("WriteResult")
.property("image", &WriteResult::image)
.property("error", &WriteResult::error)
;
function("generateBarcode", &generateBarcode);
}
```
|
/content/code_sandbox/wrappers/wasm/BarcodeWriter.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 569
|
```c++
/*
*/
#include "ReadBarcode.h"
#include <emscripten/bind.h>
#include <emscripten/val.h>
#include <memory>
#include <stdexcept>
#include <string>
#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>
using namespace ZXing;
struct ReadResult
{
std::string format{};
std::string text{};
emscripten::val bytes;
std::string error{};
Position position{};
std::string symbologyIdentifier{};
};
std::vector<ReadResult> readBarcodes(ImageView iv, bool tryHarder, const std::string& format, int maxSymbols)
{
try {
ReaderOptions opts;
opts.setTryHarder(tryHarder);
opts.setTryRotate(tryHarder);
opts.setTryInvert(tryHarder);
opts.setTryDownscale(tryHarder);
opts.setFormats(BarcodeFormatsFromString(format));
opts.setMaxNumberOfSymbols(maxSymbols);
// opts.setReturnErrors(maxSymbols > 1);
auto barcodes = ReadBarcodes(iv, opts);
std::vector<ReadResult> readResults{};
readResults.reserve(barcodes.size());
thread_local const emscripten::val Uint8Array = emscripten::val::global("Uint8Array");
for (auto&& barcode : barcodes) {
const ByteArray& bytes = barcode.bytes();
readResults.push_back({
ToString(barcode.format()),
barcode.text(),
Uint8Array.new_(emscripten::typed_memory_view(bytes.size(), bytes.data())),
ToString(barcode.error()),
barcode.position(),
barcode.symbologyIdentifier()
});
}
return readResults;
} catch (const std::exception& e) {
return {{"", "", {}, e.what()}};
} catch (...) {
return {{"", "", {}, "Unknown error"}};
}
return {};
}
std::vector<ReadResult> readBarcodesFromImage(int bufferPtr, int bufferLength, bool tryHarder, std::string format, int maxSymbols)
{
int width, height, channels;
std::unique_ptr<stbi_uc, void (*)(void*)> buffer(
stbi_load_from_memory(reinterpret_cast<const unsigned char*>(bufferPtr), bufferLength, &width, &height, &channels, 1),
stbi_image_free);
if (buffer == nullptr)
return {{"", "", {}, "Error loading image"}};
return readBarcodes({buffer.get(), width, height, ImageFormat::Lum}, tryHarder, format, maxSymbols);
}
ReadResult readBarcodeFromImage(int bufferPtr, int bufferLength, bool tryHarder, std::string format)
{
return FirstOrDefault(readBarcodesFromImage(bufferPtr, bufferLength, tryHarder, format, 1));
}
std::vector<ReadResult> readBarcodesFromPixmap(int bufferPtr, int imgWidth, int imgHeight, bool tryHarder, std::string format, int maxSymbols)
{
return readBarcodes({reinterpret_cast<uint8_t*>(bufferPtr), imgWidth, imgHeight, ImageFormat::RGBA}, tryHarder, format, maxSymbols);
}
ReadResult readBarcodeFromPixmap(int bufferPtr, int imgWidth, int imgHeight, bool tryHarder, std::string format)
{
return FirstOrDefault(readBarcodesFromPixmap(bufferPtr, imgWidth, imgHeight, tryHarder, format, 1));
}
EMSCRIPTEN_BINDINGS(BarcodeReader)
{
using namespace emscripten;
value_object<ReadResult>("ReadResult")
.field("format", &ReadResult::format)
.field("text", &ReadResult::text)
.field("bytes", &ReadResult::bytes)
.field("error", &ReadResult::error)
.field("position", &ReadResult::position)
.field("symbologyIdentifier", &ReadResult::symbologyIdentifier);
value_object<ZXing::PointI>("Point").field("x", &ZXing::PointI::x).field("y", &ZXing::PointI::y);
value_object<ZXing::Position>("Position")
.field("topLeft", emscripten::index<0>())
.field("topRight", emscripten::index<1>())
.field("bottomRight", emscripten::index<2>())
.field("bottomLeft", emscripten::index<3>());
register_vector<ReadResult>("vector<ReadResult>");
function("readBarcodeFromImage", &readBarcodeFromImage);
function("readBarcodeFromPixmap", &readBarcodeFromPixmap);
function("readBarcodesFromImage", &readBarcodesFromImage);
function("readBarcodesFromPixmap", &readBarcodesFromPixmap);
};
```
|
/content/code_sandbox/wrappers/wasm/BarcodeReader.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 997
|
```html
<!DOCTYPE html>
<html>
<head>
<title>zxing-cpp/wasm live demo</title>
<link rel="shortcut icon" href="#" />
<script src="zxing_reader.js"></script>
</head>
<body style="text-align: center">
<h2>zxing-cpp/wasm live demo</h2>
<p>
This is a simple demo of the wasm wrapper of <a href="path_to_url">zxing-cpp</a>
scanning for barcodes in a live video stream.
</p>
Camera:
<select id="cameraSelector">
<option value="user">Front Camera</option>
<option value="environment">Back Camera</option>
</select>
Format:
<select id="format">
<option value="" selected="">Any</option>
<option value="Aztec">Aztec</option>
<option value="Code39">Codabar</option>
<option value="CODE_39">Code39</option>
<option value="Code93">Code93</option>
<option value="Code128">Code128</option>
<option value="DataMatrix">DataMatrix</option>
<option value="DataBar">DataBar</option>
<option value="DataBarExpanded">DataBarExpanded</option>
<option value="DXFilmEdge">DXFilmEdge</option>
<option value="EAN8">EAN-8</option>
<option value="EAN13">EAN-13</option>
<option value="ITF">ITF</option>
<option value="PDF417">PDF417</option>
<option value="QRCode">QRCode</option>
<option value="MicroQRCode">Micro QRCode</option>
<option value="RMQRCode">rMQR Code</option>
<option value="UPCA">UPC-A</option>
<option value="UPCE">UPC-E</option>
<option value="LinearCodes">Linear Codes</option>
<option value="MatrixCodes">Matrix Codes</option>
</select>
Mode:
<select id="mode">
<option value="true" selected="">Normal</option>
<option value="false">Fast</option>
</select>
<br /><br />
<canvas id="canvas" width="640" height="480"></canvas>
<br /><br />
<div id="result"></div>
<script>
var zxing = ZXing().then(function (instance) {
zxing = instance; // this line is supposedly not required but with current emsdk it is :-/
});
const cameraSelector = document.getElementById("cameraSelector");
const format = document.getElementById("format");
const mode = document.getElementById("mode");
const canvas = document.getElementById("canvas");
const resultElement = document.getElementById("result");
const ctx = canvas.getContext("2d", { willReadFrequently: true });
const video = document.createElement("video");
video.setAttribute("id", "video");
video.setAttribute("width", canvas.width);
video.setAttribute("height", canvas.height);
video.setAttribute("autoplay", "");
function readBarcodeFromCanvas(canvas, format, mode) {
var imgWidth = canvas.width;
var imgHeight = canvas.height;
var imageData = canvas.getContext('2d').getImageData(0, 0, imgWidth, imgHeight);
var sourceBuffer = imageData.data;
if (zxing != null) {
var buffer = zxing._malloc(sourceBuffer.byteLength);
zxing.HEAPU8.set(sourceBuffer, buffer);
var result = zxing.readBarcodeFromPixmap(buffer, imgWidth, imgHeight, mode, format);
zxing._free(buffer);
return result;
} else {
return { error: "ZXing not yet initialized" };
}
}
function drawResult(code) {
ctx.beginPath();
ctx.lineWidth = 4;
ctx.strokeStyle = "red";
// ctx.textAlign = "center";
// ctx.fillStyle = "#green"
// ctx.font = "25px Arial";
// ctx.fontWeight = "bold";
with (code.position) {
ctx.moveTo(topLeft.x, topLeft.y);
ctx.lineTo(topRight.x, topRight.y);
ctx.lineTo(bottomRight.x, bottomRight.y);
ctx.lineTo(bottomLeft.x, bottomLeft.y);
ctx.lineTo(topLeft.x, topLeft.y);
ctx.stroke();
// ctx.fillText(code.text, (topLeft.x + bottomRight.x) / 2, (topLeft.y + bottomRight.y) / 2);
}
}
function escapeTags(htmlStr) {
return htmlStr.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
}
const processFrame = function () {
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
const code = readBarcodeFromCanvas(canvas, format.value, mode.value === 'true');
if (code.format) {
resultElement.innerText = code.format + ": " + escapeTags(code.text);
drawResult(code)
} else {
resultElement.innerText = "No barcode found";
}
requestAnimationFrame(processFrame);
};
const updateVideoStream = function (deviceId) {
// To ensure the camera switch, it is advisable to free up the media resources
if (video.srcObject) video.srcObject.getTracks().forEach(track => track.stop());
navigator.mediaDevices
.getUserMedia({ video: { facingMode: deviceId }, audio: false })
.then(function (stream) {
video.srcObject = stream;
video.setAttribute("playsinline", true); // required to tell iOS safari we don't want fullscreen
video.play();
processFrame();
})
.catch(function (error) {
console.error("Error accessing camera:", error);
});
};
cameraSelector.addEventListener("change", function () {
updateVideoStream(this.value);
});
updateVideoStream();
</script>
</body>
</html>
```
|
/content/code_sandbox/wrappers/wasm/demo_cam_reader.html
|
html
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 1,348
|
```unknown
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.31903.59
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZXingCpp", "ZXingCpp\ZXingCpp.csproj", "{64E71DE2-C1C6-4FCF-B8A6-FFC6D1605ECD}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZXingCpp.DemoReader", "ZXingCpp.DemoReader\ZXingCpp.DemoReader.csproj", "{05C626FE-A5CE-4263-9419-35E44F14DB93}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZXingCpp.DemoWriter", "ZXingCpp.DemoWriter\ZXingCpp.DemoWriter.csproj", "{E82B81A1-E873-4C40-BF47-83D6971848CE}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZXingCpp.Tests", "ZXingCpp.Tests\ZXingCpp.Tests.csproj", "{9D57E7B5-A24F-4F1D-8AF0-CED8FAE54B06}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{64E71DE2-C1C6-4FCF-B8A6-FFC6D1605ECD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{64E71DE2-C1C6-4FCF-B8A6-FFC6D1605ECD}.Debug|Any CPU.Build.0 = Debug|Any CPU
{64E71DE2-C1C6-4FCF-B8A6-FFC6D1605ECD}.Release|Any CPU.ActiveCfg = Release|Any CPU
{64E71DE2-C1C6-4FCF-B8A6-FFC6D1605ECD}.Release|Any CPU.Build.0 = Release|Any CPU
{05C626FE-A5CE-4263-9419-35E44F14DB93}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{05C626FE-A5CE-4263-9419-35E44F14DB93}.Debug|Any CPU.Build.0 = Debug|Any CPU
{05C626FE-A5CE-4263-9419-35E44F14DB93}.Release|Any CPU.ActiveCfg = Release|Any CPU
{05C626FE-A5CE-4263-9419-35E44F14DB93}.Release|Any CPU.Build.0 = Release|Any CPU
{9D57E7B5-A24F-4F1D-8AF0-CED8FAE54B06}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9D57E7B5-A24F-4F1D-8AF0-CED8FAE54B06}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9D57E7B5-A24F-4F1D-8AF0-CED8FAE54B06}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9D57E7B5-A24F-4F1D-8AF0-CED8FAE54B06}.Release|Any CPU.Build.0 = Release|Any CPU
{E82B81A1-E873-4C40-BF47-83D6971848CE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E82B81A1-E873-4C40-BF47-83D6971848CE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E82B81A1-E873-4C40-BF47-83D6971848CE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E82B81A1-E873-4C40-BF47-83D6971848CE}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal
```
|
/content/code_sandbox/wrappers/dotnet/dotnet.sln
|
unknown
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 1,091
|
```xml
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<!-- <ImplicitUsings>enable</ImplicitUsings> -->
<Nullable>enable</Nullable>
<PackageId>ZXingCpp</PackageId>
<Version>0.2.1-alpha</Version>
<Authors>Axel Waggershauser</Authors>
<Company>zxing-cpp</Company>
<Description>
ZXingCpp is a .NET wrapper for the C++ library zxing-cpp.
It is an open-source, multi-format linear/matrix barcode image processing library implemented in C++.
It was originally ported from the Java ZXing library but has been developed further and now includes
many improvements in terms of runtime and detection performance.</Description>
<PackageProjectUrl>path_to_url
<PackageReadmeFile>README.md</PackageReadmeFile>
<PackageTags>Barcode;QRCode</PackageTags>
</PropertyGroup>
<ItemGroup>
<None Include="README.md" Pack="true" PackagePath="README.md"/>
<None Include="../runtimes/ZXing.dll" Pack="true" PackagePath="runtimes/win-x64/native/" />
<None Include="../runtimes/libZXing.so" Pack="true" PackagePath="runtimes/linux-x64/native/" />
<None Include="../runtimes/libZXing.dylib" Pack="true" PackagePath="runtimes/osx-x64/native/" />
</ItemGroup>
</Project>
<!-- .NET Standard 2. (netstandard), see path_to_url#when-to-target-net80-vs-netstandard -->
<!-- dotnet nuget push bin/Release/ZXingCpp.0.1.0-alpha.nupkg -s path_to_url -k <api-key> -->
```
|
/content/code_sandbox/wrappers/dotnet/ZXingCpp/ZXingCpp.csproj
|
xml
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 399
|
```smalltalk
/*
*/
using System.Collections.Generic;
using SkiaSharp;
using ZXingCpp;
public static class SkBitmapBarcodeWriter
{
public static SKBitmap Write(Barcode barcode, WriterOptions? opts = null)
{
var img = barcode.ToImage(opts);
var info = new SKImageInfo(img.Width, img.Height, SKColorType.Gray8);
var res = new SKBitmap();
res.InstallPixels(info, img.Data, img.Width, (IntPtr _, object _) => img.Dispose());
return res;
}
public static SKBitmap ToSKBitmap(this Barcode barcode, WriterOptions? opts = null) => Write(barcode, opts);
}
public class Program
{
public static void Main(string[] args)
{
var (format, text, fn) = (args[0], args[1], args[2]);
var bc = new Barcode(text, Barcode.FormatFromString(format));
var img = bc.ToImage();
Console.WriteLine($"{img.Data}, {img.Width}, {img.Height}, {img.ToArray()}");
if (fn.EndsWith(".svg"))
File.WriteAllText(fn, bc.ToSVG());
else
using (SKBitmap skb = bc.ToSKBitmap(new WriterOptions(){Scale = 5})) {
skb.Encode(new SKFileWStream(args[2]), SKEncodedImageFormat.Png, 100);
}
}
}
```
|
/content/code_sandbox/wrappers/dotnet/ZXingCpp.DemoWriter/Program.cs
|
smalltalk
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 287
|
```xml
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="SkiaSharp" Version="2.88.7" ExcludeAssets="native" />
<!-- the following line was required to make dotnet install the missing *.so file on Linux -->
<!-- on another platform, you will need to remove the "ExludeAssets" property above -->
<PackageReference Include="SkiaSharp.NativeAssets.Linux.NoDependencies" Version="2.88.7" />
<ProjectReference Include="..\ZXingCpp\ZXingCpp.csproj" />
</ItemGroup>
</Project>
```
|
/content/code_sandbox/wrappers/dotnet/ZXingCpp.DemoWriter/ZXingCpp.DemoWriter.csproj
|
xml
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 194
|
```xml
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.6.0" />
<PackageReference Include="xunit" Version="2.4.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="6.0.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ZXingCpp\ZXingCpp.csproj" />
</ItemGroup>
</Project>
```
|
/content/code_sandbox/wrappers/dotnet/ZXingCpp.Tests/ZXingCpp.Tests.csproj
|
xml
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 270
|
```smalltalk
using Xunit;
using System.Text;
using ZXingCpp;
namespace ZXingCpp.Tests;
public class UnitTest1
{
[Fact]
public void ValidBarcodeFormatsParsing()
{
Assert.Equal(BarcodeFormats.QRCode, Barcode.FormatsFromString("qrcode"));
Assert.Equal(BarcodeFormats.LinearCodes, Barcode.FormatsFromString("linear_codes"));
Assert.Equal(BarcodeFormats.None, Barcode.FormatsFromString(""));
}
[Fact]
public void InvalidBarcodeFormatsParsing()
{
Assert.Throws<Exception>(() => Barcode.FormatsFromString("nope"));
}
[Fact]
public void InvalidImageView()
{
Assert.Throws<Exception>(() => new ImageView(new byte[0], 1, 1, ImageFormat.Lum));
Assert.Throws<Exception>(() => new ImageView(new byte[1], 1, 1, ImageFormat.Lum, 2));
}
[Fact]
public void Read()
{
var data = new List<byte>();
foreach (var v in your_sha256_hash110010100000")
data.Add((byte)(v == '0' ? 255 : 0));
var iv = new ImageView(data.ToArray(), data.Count, 1, ImageFormat.Lum);
var br = new BarcodeReader() {
Binarizer = Binarizer.BoolCast,
};
var res = br.From(iv);
var expected = "96385074";
Assert.Single(res);
Assert.True(res[0].IsValid);
Assert.Equal(BarcodeFormats.EAN8, res[0].Format);
Assert.Equal(expected, res[0].Text);
Assert.Equal(Encoding.ASCII.GetBytes(expected), res[0].Bytes);
Assert.False(res[0].HasECI);
Assert.Equal(ContentType.Text, res[0].ContentType);
Assert.Equal(0, res[0].Orientation);
Assert.Equal(new PointI() { X = 4, Y = 0 }, res[0].Position.TopLeft);
Assert.Equal(1, res[0].LineCount);
Assert.False(res[0].IsMirrored);
Assert.False(res[0].IsInverted);
Assert.Equal(ErrorType.None, res[0].ErrorType);
Assert.Equal("", res[0].ErrorMsg);
}
[Fact]
public void Create()
{
var text = "hello";
var res = new Barcode(text, BarcodeFormats.DataMatrix);
Assert.True(res.IsValid);
Assert.Equal(BarcodeFormats.DataMatrix, res.Format);
Assert.Equal(text, res.Text);
Assert.Equal(Encoding.ASCII.GetBytes(text), res.Bytes);
Assert.False(res.HasECI);
Assert.Equal(ContentType.Text, res.ContentType);
Assert.Equal(0, res.Orientation);
Assert.False(res.IsMirrored);
Assert.False(res.IsInverted);
Assert.Equal(new PointI() { X = 1, Y = 1 }, res.Position.TopLeft);
Assert.Equal(ErrorType.None, res.ErrorType);
Assert.Equal("", res.ErrorMsg);
}
}
```
|
/content/code_sandbox/wrappers/dotnet/ZXingCpp.Tests/UnitTest1.cs
|
smalltalk
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 629
|
```xml
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="SkiaSharp" Version="2.88.7" ExcludeAssets="native" />
<!-- the following line was required to make dotnet install the missing *.so file on Linux -->
<!-- on another platform, you will need to remove the "ExludeAssets" property above -->
<PackageReference Include="SkiaSharp.NativeAssets.Linux.NoDependencies" Version="2.88.7" />
<PackageReference Include="Magick.NET-Q8-x64" Version="13.5.0" />
<ProjectReference Include="..\ZXingCpp\ZXingCpp.csproj" />
</ItemGroup>
</Project>
```
|
/content/code_sandbox/wrappers/dotnet/ZXingCpp.DemoReader/ZXingCpp.DemoReader.csproj
|
xml
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 217
|
```smalltalk
/*
*/
using System.Collections.Generic;
using ImageMagick;
using SkiaSharp;
using ZXingCpp;
public static class MagickImageBarcodeReader
{
public static List<Barcode> Read(MagickImage img, ReaderOptions? opts = null)
{
if (img.DetermineBitDepth() < 8)
img.SetBitDepth(8);
var bytes = img.ToByteArray(MagickFormat.Gray);
var iv = new ImageView(bytes, img.Width, img.Height, ImageFormat.Lum);
return BarcodeReader.Read(iv, opts);
}
public static List<Barcode> From(this BarcodeReader reader, MagickImage img) => Read(img, reader);
}
public static class SkBitmapBarcodeReader
{
public static List<Barcode> Read(SKBitmap img, ReaderOptions? opts = null)
{
var format = img.Info.ColorType switch
{
SKColorType.Gray8 => ImageFormat.Lum,
SKColorType.Rgba8888 => ImageFormat.RGBA,
SKColorType.Bgra8888 => ImageFormat.BGRA,
_ => ImageFormat.None,
};
if (format == ImageFormat.None)
{
if (!img.CanCopyTo(SKColorType.Gray8))
throw new Exception("Incompatible SKColorType");
img = img.Copy(SKColorType.Gray8);
format = ImageFormat.Lum;
}
var iv = new ImageView(img.GetPixels(), img.Info.Width, img.Info.Height, format);
return BarcodeReader.Read(iv, opts);
}
public static List<Barcode> From(this BarcodeReader reader, SKBitmap img) => Read(img, reader);
}
public class Program
{
public static void Main(string[] args)
{
#if false
var img = new MagickImage(args[0]);
#else
var img = SKBitmap.Decode(args[0]);
#endif
Console.WriteLine(img);
var readBarcodes = new BarcodeReader() {
TryInvert = false,
ReturnErrors = true,
};
if (args.Length >= 2)
readBarcodes.Formats = Barcode.FormatsFromString(args[1]);
foreach (var b in readBarcodes.From(img))
Console.WriteLine($"{b.Format} ({b.ContentType}): {b.Text} / [{string.Join(", ", b.Bytes)}] {b.ErrorMsg}");
}
}
```
|
/content/code_sandbox/wrappers/dotnet/ZXingCpp.DemoReader/Program.cs
|
smalltalk
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 496
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.