-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPowershell-QrCodeGenerator.psm1
2436 lines (2049 loc) · 80.6 KB
/
Powershell-QrCodeGenerator.psm1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#region Enumerations
enum EccEnum{
LOW = 1
MEDIUM = 0
QUARTILE = 3
HIGH = 2
}
enum ModeEnum{
NUMERIC = 0
ALPHANUMERIC = 1
BYTE = 2
KANJI = 3
ECI = 4
}
#endregion Enumerations
#region Classes
class Ecc{
# Must be declared in ascending order of error protection
# so that the implicit getEccOrdinal and getEccValue work properly
# NAME | Ecc Value | Ordinal Value
# The QR Code can tolerate about 7% erroneous codewords -> LOW = 1 0
# The QR Code can tolerate about 15% erroneous codewords -> MEDIUM = 0 1
# The QR Code can tolerate about 25% erroneous codewords -> QUARTILE = 3 2
# The QR Code can tolerate about 30% erroneous codewords -> HIGH = 2 3
hidden [EccEnum] $internalEcl
[int] getEccValue(){
[int] $tmpEcl = 1 # LOW
switch ($this.internalEcl) {
"HIGH" { $tmpEcl = 2 }
"QUARTILE" { $tmpEcl = 3 }
"MEDIUM" { $tmpEcl = 0 }
# LOW
}
return $tmpEcl
}
[int] getEccOrdinal(){
[int] $tmpEcl = 0 # LOW
switch ($this.internalEcl) {
"HIGH" { $tmpEcl = 3 }
"QUARTILE" { $tmpEcl = 2 }
"MEDIUM" { $tmpEcl = 1 }
# LOW
}
return $tmpEcl
}
[Ecc] getHigherEcc(){
[Ecc] $tmpEcl = New-Object 'Ecc' 1
switch ($this.internalEcl) {
"LOW" { $tmpEcl.setEccValue(0) }
"MEDIUM" { $tmpEcl.setEccValue(3) }
"QUARTILE" { $tmpEcl.setEccValue(2) }
Default {
throw "getHigherEcc was called on a already HIGH Ecc"
}
}
return $tmpEcl
}
[Ecc] getLowerEcc(){
[Ecc] $tmpEcl = New-Object 'Ecc' 1
switch ($this.internalEcl) {
"HIGH" { $tmpEcl.setEccValue(3)}
"QUARTILE" { $tmpEcl.setEccValue(0) }
"MEDIUM" { $tmpEcl.setEccValue(1) }
Default {
throw "getLowerEcc was called on a already LOW Ecc"
}
}
return $tmpEcl
}
[bool] isMax(){
if ($this.internalEcl -eq [EccEnum]::HIGH) {
return $true
}
return $false
}
[bool] isMin(){
if ($this.internalEcl -eq [EccEnum]::LOW) {
return $true
}
return $false
}
setEccValue([int] $val){
$this.internalEcl = $val
}
setEccValue([Ecc] $val){
$this.setEccValue($val.getEccValue())
}
Ecc(){
$this.internalEcl = 0
}
Ecc([int] $val){
$this.internalEcl = $val
}
Ecc([Ecc] $val){
$this.internalEcl = $val.getEccValue()
}
Ecc([string] $val){
switch ($val) {
"LOW" { $this.internalEcl = "LOW" }
"QUARTILE" { $this.internalEcl = "QUARTILE" }
"MEDIUM" { $this.internalEcl = "MEDIUM" }
"HIGH" { $this.internalEcl = "HIGH" }
Default {
throw "Invalid ECC String"
}
}
}
static [Ecc] LOW() {return New-Object 'Ecc' 1}
static [Ecc] MEDIUM() {return New-Object 'Ecc' 0}
static [Ecc] QUARTILE() {return New-Object 'Ecc' 3}
static [Ecc] HIGH() {return New-Object 'Ecc' 2}
}
# Describes how a segment's data bits are interpreted.
class QrMode{
# -- Fields --
# The mode indicator bits, which is a uint4 value (range 0 to 15).
[int] $modeBits
# Number of character count bits for three different version ranges.
hidden [int[]] $numBitsCharCount
# -- Constructor --
hidden QrMode([int] $qrmode, [int[]] $ccbits)
{
$this.modeBits = $qrmode
$this.numBitsCharCount = $ccbits
}
QrMode([string] $qrmode){
switch ($qrmode) {
"NUMERIC" { $this.modeBits = 0x1 ; $this.numBitsCharCount = @( 10, 12, 14) }
"ALPHANUMERIC" { $this.modeBits = 0x2 ; $this.numBitsCharCount = @( 9, 11, 13) }
"BYTE" { $this.modeBits = 0x3 ; $this.numBitsCharCount = @( 8, 16, 16) }
"KANJI" { $this.modeBits = 0x8 ; $this.numBitsCharCount = @( 8, 10, 12) }
"ECI" { $this.modeBits = 0x7 ; $this.numBitsCharCount = @( 0, 0, 0) }
Default {
throw "Invalid QrMode String"
}
}
}
# -- Method --
static [QrMode] NUMERIC() {return New-Object 'QrMode' 0x1,@( 10, 12, 14)}
static [QrMode] ALPHANUMERIC() {return New-Object 'QrMode' 0x2,@( 9, 11, 13)}
static [QrMode] BYTE() {return New-Object 'QrMode' 0x4,@( 8, 16, 16)}
static [QrMode] KANJI() {return New-Object 'QrMode' 0x8,@( 8, 10, 12)}
static [QrMode] ECI() {return New-Object 'QrMode' 0x7,@( 0, 0, 0)}
# Returns the bit width of the character count field for a segment in this mode
# in a QR Code at the given version number. The result is in the range [0, 16].
[int] numCharCountBits([int] $ver)
{
if (([QrCode]::MIN_VERSION -gt $ver) -or ($ver -gt [QrCode]::MAX_VERSION))
{
throw "Version is not a valid value. It must range from "+[QrCode]::MIN_VERSION+" to "+[QrCode]::MAX_VERSION
}
return $this.numBitsCharCount[[Math]::truncate(($ver + 7) / 17)]
}
}
class QrBitBuffer {
# ---- Fields ----
hidden [string] $data
hidden [int] $bitLength # Non-negative
# ---- Constructor ----
# Constructs an empty bit buffer (length 0).
QrBitBuffer()
{
$this.data = ""
$this.bitLength = 0
}
QrBitBuffer([int] $size)
{
$this.data = ""
$this.bitLength = 0
for ($i = 0; $i -lt $size; $i++) {
$this.data += "0"
$this.bitLength += 1
}
}
QrBitBuffer([string] $binaryString)
{
if (-not($binaryString -match [QrCode]::BINARY_REGEX))
{
throw "binaryString to use is not a binary string"
}
$this.data = $binaryString
$this.bitLength = $binaryString.Length
}
# ---- Methods ----
# Returns the length of this sequence, which is a non-negative value.
# @return the length of this sequence
[int] getBitLength()
{
if($this.bitLength -lt 0)
{
throw "Negative BitLength ("+$this.bitLength+") Reached"
}
return $this.bitLength
}
# Returns the bit at the specified index, yielding 0 or 1.
# @param index the index to get the bit at
# @return the bit at the specified index
# @throws IndexOutOfBoundsException if index < 0 or index ≥ bitLength
[int] getBit([int] $index)
{
if (($index -lt 0) -or ($index -ge $this.bitLength))
{
throw "Requested Bit ("+$index+") is out of range (from 0 to "+$this.bitLength+")"
}
$retVal = 0
if($this.data[$index] -eq "1"){$retVal = 1}
return $retVal
}
[int] getByte([int] $index)
{
return [Convert]::ToByte([Convert]::ToInt16($this.data.Substring($index*8,8),2))
}
[int] getBigEndianByte([int] $index)
{
[string] $tmpString = $this.data.Substring($index*8,8)
[string] $tmpReverseString = $tmpString[7]+$tmpString[6]+$tmpString[5]+$tmpString[4]+$tmpString[3]+$tmpString[2]+$tmpString[1]+$tmpString[0]
return [Convert]::ToByte([Convert]::ToInt16($tmpReverseString,2))
}
setBit([int] $index,[int] $val)
{
[char] $insert = "0"
if ($val)
{
$insert = "1"
}
[string] $orig = $this.data
[string] $new = $orig.Substring(0,$val) + $insert + $orig.Substring($val+1,$orig.Length-1)
$this.data = $new
}
[byte[]] toBytes()
{
[int] $oversize = $this.bitLength % 8
[int] $stopBeforeEnd = 0
[int] $arraySize = [math]::Truncate($this.bitLength / 8)
if($oversize)
{
$stopBeforeEnd = 1
}
[byte[]] $byteArray = New-Object 'byte[]' $arraySize
for ($i = 0; $i -lt ($arraySize - $stopBeforeEnd); $i++)
{
$byteArray[$i] = $this.getByte($i)
}
if($oversize)
{
[string] $zeroes = ""
for($j = 0 ; $j -lt (8-$oversize) ; $j++)
{
$zeroes = $zeroes + "0"
}
$byteArray[3] = [Convert]::ToByte([Convert]::ToInt16($this.data.Substring(($arraySize-1)*8,$oversize)+""+$zeroes,2))
}
return $byteArray
}
[string] toString()
{
return $this.data
}
# Appends the specified number of low-order bits of the specified value to this
# buffer. Requires 0 ≤ len ≤ 31 and 0 ≤ val < 2<sup>len</sup>.
# @param val the value to append
# @param len the number of low-order bits in the value to take
# @throws IllegalArgumentException if the value or number of bits is out of range
# @throws IllegalStateException if appending the data
# would make bitLength exceed Integer.MAX_VALUE
appendBits([int] $val, [int] $len)
{
if ((($len -lt 0) -or ($len -gt 31) -or ($val -shr $len)) -ne 0)
{
throw "len ("+$len+") is out of range or val can't fit in len bit"
}
if (([int]::MaxValue - $this.bitLength) -lt $len)
{
throw "Maximum bitLength length reached when appending bits"
}
if($len -eq 0){return}
# for (int i = len - 1; i >= 0; i--, bitLength++) // Append bit by bit
# data.set(bitLength, QrCode.getBit(val, i));
$this.data += [Convert]::ToString($val, 2).PadLeft($len, '0')
$this.bitLength += $len
}
# Appends the content of the specified bit buffer to this buffer.
# @param bb the bit buffer whose data to append (not {@code null})
# @throws NullPointerException if the bit buffer is {@code null}
# @throws IllegalStateException if appending the data
# would make bitLength exceed Integer.MAX_VALUE
appendData([QrBitBuffer] $bb)
{
if (-not $bb)
{
throw "bb to append is null"
}
if (([int]::MaxValue - $this.bitLength) -lt $bb.getBitLength())
{
throw "Maximum bitLength length reached when appending data"
}
$tmpStr = $bb.ToString()
$this.data += $tmpStr
$this.bitLength += $tmpStr.Length
}
appendBinaryString([string] $binStr)
{
if (-not $binStr)
{
throw "binStr to append is null"
}
if (-not($binStr -match [QrCode]::BINARY_REGEX))
{
throw "binStr to append is not a binary string"
}
$this.data += $binStr
$this.bitLength += $binStr.Length
}
# Returns a new copy of this buffer.
# @return a new copy of this buffer (not {@code null})
[QrBitBuffer] clone()
{
[QrBitBuffer] $tmpBb = New-Object 'QrBitBuffer'
$tmpBb.appendData($this)
return ($tmpBb)
}
}
class QrSegment {
# ---- Static factory functions (mid level) ----
# Returns a segment representing the specified binary data
# encoded in byte mode. All input byte arrays are acceptable.
# <p>Any text string can be converted to UTF-8 bytes ({@code
# s.getBytes(StandardCharsets.UTF_8)}) and encoded as a byte mode segment.</p>
# @param data the binary data (not {@code null})
# @return a segment (not {@code null}) containing the data
# @throws NullPointerException if the array is {@code null}
static [QrSegment] makeBytes([byte[]] $data)
{
if (-not $data)
{
throw "data (Bytes) to forge segment is null"
}
[QrBitBuffer] $bb = New-Object 'QrBitBuffer'
foreach ($b in $data) {
$bb.appendBits($b -band 0xFF,8)
}
return (New-Object 'QrSegment' ([QrMode]::BYTE()),$data.Length,$bb )
}
# Returns a segment representing the specified string of decimal digits encoded in numeric mode.
# @param digits the text (not {@code null}), with only digits from 0 to 9 allowed
# @return a segment (not {@code null}) containing the text
# @throws NullPointerException if the string is {@code null}
# @throws IllegalArgumentException if the string contains non-digit characters
static [QrSegment] makeNumeric([String] $digits)
{
if (-not $digits)
{
throw "digits (String) to forge segment is null"
}
if (-not ($digits -match [QrCode]::NUMERIC_REGEX)){
throw "digits to forge segment from is not a digital string"
}
[QrBitBuffer] $bb = New-Object 'QrBitBuffer'
for ([int] $i = 0; $i -lt $digits.length; ) # Consume up to 3 digits per iteration
{
[int] $n = [Math]::Min($digits.length - $i, 3)
$bb.appendBits([int]::Parse($digits.Substring($i,$n)), ($n * 3) + 1)
$i += $n
}
return (New-Object 'QrSegment' ([QrMode]::NUMERIC()), $digits.length , $bb)
}
# Returns a segment representing the specified text string encoded in alphanumeric mode.
# The characters allowed are: 0 to 9, A to Z (uppercase only), space,
# dollar, percent, asterisk, plus, hyphen, period, slash, colon.
# @param text the text (not {@code null}), with only certain characters allowed
# @return a segment (not {@code null}) containing the text
# @throws NullPointerException if the string is {@code null}
# @throws IllegalArgumentException if the string contains non-encodable characters
static [QrSegment] makeAlphanumeric([String] $text)
{
if (-not $text)
{
throw "text (String) to forge segment is null"
}
if ( -not ( $text -cmatch [QrCode]::ALPHANUMERIC_REGEX))
{
throw "text (String) to forge segment from contains illegal characters"
}
[QrBitBuffer] $bb = New-Object 'QrBitBuffer'
[int] $i = 0 # needed here for global persistance
for ($i = 0; $i -le ($text.length - 2); $i += 2) # Process groups of 2
{
[int] $temp = [QrCode]::ALPHANUMERIC_CHARSET.IndexOf($text[$i]) * 45
$temp += [QrCode]::ALPHANUMERIC_CHARSET.IndexOf($text[$i+1])
$bb.appendBits($temp, 11)
}
if ($i -lt $text.length) # 1 character remaining
{
$bb.appendBits([QrCode]::ALPHANUMERIC_CHARSET.IndexOf($text[$i]), 6)
}
return (New-Object 'QrSegment' ([QrMode]::ALPHANUMERIC()), $text.length , $bb)
}
# Returns a list of zero or more segments to represent the specified Unicode text string.
# The result may use various segment modes and switch modes to optimize the length of the bit stream.
# @param text the text to be encoded, which can be any Unicode string
# @return a new mutable list (not {@code null}) of segments (not {@code null}) containing the text
# @throws NullPointerException if the text is {@code null}
static [QrSegment[]] makeSegments([String] $text)
{
if (-not $text)
{
throw "text (String) to forge generic segment is null"
}
# Select the most efficient segment encoding automatically
[QrSegment[]] $result = @()
if ($text.equals(""))
{
#Leave result empty
}
elseif ($text -match [QrCode]::NUMERIC_REGEX )
{
$result += ([QrSegment]::makeNumeric($text))
}
elseif ($text -cmatch [QrCode]::ALPHANUMERIC_REGEX )
{
$result += ([QrSegment]::makeAlphanumeric($text))
}
else
{
$enc = [system.Text.Encoding]::UTF8
$bytes = $enc.GetBytes($text)
$result += ([QrSegment]::makeBytes($bytes))
}
return $result
}
# Returns a segment representing an Extended Channel Interpretation
# (ECI) designator with the specified assignment value.
# @param assignVal the ECI assignment number (see the AIM ECI specification)
# @return a segment (not {@code null}) containing the data
# @throws IllegalArgumentException if the value is outside the range [0, 10<sup>6</sup>)
static [QrSegment] makeEci([int] $assignVal)
{
[QrBitBuffer] $bb = New-Object 'QrBitBuffer'
if ($assignVal -lt 0)
{
throw "ECI assignment value out of range"
}
elseif ($assignVal -lt (1 -shl 7))
{
$bb.appendBits($assignVal, 8)
}
elseif ($assignVal -lt (1 -shl 14))
{
$bb.appendBits(2, 2)
$bb.appendBits($assignVal, 14)
}
elseif ($assignVal -lt 1000000)
{
$bb.appendBits(6, 3)
$bb.appendBits($assignVal, 21)
}
else
{
throw "ECI assignment value out of range"
}
return New-Object 'QrSegment' ([QrMode]::ECI()), 0, $bb
}
# ---- Instance fields ----
# The mode indicator of this segment. Not {@code null}. */
[QrMode] $qrmode
# The length of this segment's unencoded data. Measured in characters for
# numeric/alphanumeric/kanji mode, bytes for byte mode, and 0 for ECI mode.
# Always zero or positive. Not the same as the data's bit length. */
[int] $numChars
# The data bits of this segment. Not null. Accessed through getData().
hidden [QrBitBuffer] $data
# ---- Constructor (low level) ----
# * Constructs a QR Code segment with the specified attributes and data.
# * The character count (numCh) must agree with the mode and the bit buffer length,
# * but the constraint isn't checked. The specified bit buffer is cloned and stored.
# * @param md the mode (not {@code null})
# * @param numCh the data length in characters or bytes, which is non-negative
# * @param data the data bits (not {@code null})
# * @throws NullPointerException if the mode or data is {@code null}
# * @throws IllegalArgumentException if the character count is negative
QrSegment([QrMode] $qrmd, [int] $numCh, [QrBitBuffer] $data)
{
if (-not $qrmd)
{
throw "md (Mode) is null"
}
$this.qrmode = $qrmd
if ($numCh -lt 0)
{
throw "numCh must be greater than zero"
}
if (-not $data)
{
throw "data (QrBitBuffer) is null"
}
$this.numChars = $numCh
$this.data = $data.clone() # Make defensive copy
}
# ---- Methods ----
# Returns the data bits of this segment.
# @return a new copy of the data bits (not {@code null})
[QrBitBuffer] getData() {
[QrBitBuffer] $tmpBb = $this.data.clone()
return $tmpBb # Make defensive copy
}
[int] getDataLength() {
return $this.data.getBitLength()
}
# Calculates the number of bits needed to encode the given segments at the given version.
# Returns a non-negative number if successful. Otherwise returns -1 if a segment has too
# many characters to fit its length field, or the total bits exceeds Integer.MAX_VALUE.
static [int] getTotalBits([QrSegment[]] $segs, [int] $version)
{
if (-not $segs)
{
throw "segs (QrSegment[]) is null"
}
[long] $result = 0
foreach ($seg in $segs)
{
if (-not $seg)
{
throw "inner seg (QrSegment) is null"
}
[int] $ccbits = $seg.qrmode.numCharCountBits($version)
if ($seg.numChars -ge (1 -shl $ccbits))
{
return -1 # The segment's length doesn't fit the field's bit width
}
$result += ([long]4) + $ccbits + $seg.getDataLength()
if ($result -gt [int]::MaxValue)
{
return -1 # The sum will overflow an int type
}
}
return [Convert]::ToInt32($result)
}
}
class QrCode {
# Returns a QR Code representing the specified Unicode text string at the specified error correction level.
# As a conservative upper bound, this function is guaranteed to succeed for strings that have 738 or fewer
# Unicode code points (not UTF-16 code units) if the low error correction level is used. The smallest possible
# QR Code version is automatically chosen for the output. The ECC level of the result may be higher than the
# ecl argument if it can be done without increasing the version.
# @param text the text to be encoded (not {@code null}), which can be any Unicode string
# @param ecl the error correction level to use (not {@code null}) (boostable)
# @return a QR Code (not {@code null}) representing the text
# @throws NullPointerException if the text or error correction level is {@code null}
# @throws DataTooLongException if the text fails to fit in the
# largest version QR Code at the ECL, which means it is too long
static [QrCode] encodeText([string] $text, [Ecc] $ecl,[int] $mask=-1, [boolean] $boostEcl=$true)
{
if (-not $text)
{
throw "text (string) in encodeText is null"
}
if (-not $ecl)
{
throw "Ecl (Ecc) in encodeText is null"
}
if(($mask -lt -2) -or ($mask -gt 7))
{
throw "mask is out of range. Must range from 0 to 7 (or -1 to auto detect ; -2 to disable masking)"
}
[QrSegment[]] $segs = [QrSegment]::makeSegments($text)
return [QrCode]::encodeSegments($segs, $ecl,$mask,$boostEcl)
}
# Returns a QR Code representing the specified binary data at the specified error correction level.
# This function always encodes using the binary segment mode, not any text mode. The maximum number of
# bytes allowed is 2953. The smallest possible QR Code version is automatically chosen for the output.
# The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version.
# @param data the binary data to encode (not {@code null})
# @param ecl the error correction level to use (not {@code null}) (boostable)
# @return a QR Code (not {@code null}) representing the data
# @throws NullPointerException if the data or error correction level is {@code null}
# @throws DataTooLongException if the data fails to fit in the
# largest version QR Code at the ECL, which means it is too long
static [QrCode] encodeBinary([byte[]] $data, [Ecc] $ecl,[int] $mask=-1, [boolean] $boostEcl=$true)
{
if (-not $data)
{
throw "data (byte[]) in encodeBinary is null"
}
if (-not $ecl)
{
throw "ecl (Ecc) in encodeBinary is null"
}
if(($mask -lt -2) -or ($mask -gt 7))
{
throw "mask is out of range. Must range from 0 to 7 (or -1 to auto detect ; -2 to disable masking)"
}
[QrSegment] $seg = [QrSegment]::makeBytes($data)
return [QrCode]::encodeSegments($seg, $ecl,$mask,$boostEcl)
}
# ---- Static Properties used globaly ----
# The minimum version number (1) supported in the QR Code Model 2 standard.
static [int] $MIN_VERSION = 1
# The maximum version number (40) supported in the QR Code Model 2 standard.
static [int] $MAX_VERSION = 40
# The Default Quiet Zone Size.
static [int] $DEFAULT_QUIET_ZONE = 2
# For use in getPenaltyScore(), when evaluating which mask is best.
static $PENALTY_N1 = 3
static $PENALTY_N2 = 3
static $PENALTY_N3 = 40
static $PENALTY_N4 = 10
static [byte[][]] $ECC_CODEWORDS_PER_BLOCK = @(
# Version: (note that index 0 is for padding, and is set to an illegal value)
# 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level
@(0xFF, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30), # Low
@(0xFF, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28), # Medium
@(0xFF, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30, 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30), # Quartile
@(0xFF, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30) # High
)
static [byte[][]] $NUM_ERROR_CORRECTION_BLOCKS = @(
# Version: (note that index 0 is for padding, and is set to an illegal value)
# 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level
@(0xFF, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25), # Low
@(0xFF, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49), # Medium
@(0xFF, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29, 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68), # Quartile
@(0xFF, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81) # High
)
# ---- Constants ----
static [string] $BINARY_REGEX = "^[01]+$"
# Describes precisely all strings that are encodable in numeric mode. To test whether a
# string {@code s} is encodable: {@code boolean ok = NUMERIC_REGEX.matcher(s).matches();}.
# A string is encodable iff each character is in the range 0 to 9.
# @see #makeNumeric(String) */
static [string] $NUMERIC_REGEX = "^\d+$"
# Describes precisely all strings that are encodable in alphanumeric mode. To test whether a
# string {@code s} is encodable: {@code boolean ok = ALPHANUMERIC_REGEX.matcher(s).matches();}.
# A string is encodable iff each character is in the following set: 0 to 9, A to Z
# (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon.
# @see #makeAlphanumeric(String) */
static [string] $ALPHANUMERIC_REGEX = "^[A-Z0-9 $%*+./:-]+$"
# The set of all legal characters in alphanumeric mode, where
# each character value maps to the index in the string.
static [string] $ALPHANUMERIC_CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:"
# ---- Static factory functions (mid level) ----
# Returns a QR Code representing the specified segments at the specified error correction
# level. The smallest possible QR Code version is automatically chosen for the output. The ECC level
# of the result may be higher than the ecl argument if it can be done without increasing the version.
# <p>This function allows the user to create a custom sequence of segments that switches
# between modes (such as alphanumeric and byte) to encode text in less space.
# This is a mid-level API; the high-level API is {@link #encodeText(String,Ecc)}
# and {@link #encodeBinary(byte[],Ecc)}.</p>
# @param segs the segments to encode
# @param ecl the error correction level to use (not {@code null}) (boostable)
# @return a QR Code (not {@code null}) representing the segments
# @throws NullPointerException if the list of segments, any segment, or the error correction level is {@code null}
# @throws DataTooLongException if the segments fail to fit in the
# largest version QR Code at the ECL, which means they are too long
static [QrCode] encodeSegments([QrSegment[]] $segs, [Ecc] $ecl,[int] $mask=-1, [boolean] $boostEcl=$true) {
return [QrCode]::encodeSegments($segs, $ecl, [QrCode]::MIN_VERSION, [QrCode]::MAX_VERSION, $mask, $boostEcl)
}
# Returns a QR Code representing the specified segments with the specified encoding parameters.
# The smallest possible QR Code version within the specified range is automatically
# chosen for the output. Iff boostEcl is {@code true}, then the ECC level of the
# result may be higher than the ecl argument if it can be done without increasing
# the version. The mask number is either between 0 to 7 (inclusive) to force that
# mask, or −1 to automatically choose an appropriate mask (which may be slow).
# <p>This function allows the user to create a custom sequence of segments that switches
# between modes (such as alphanumeric and byte) to encode text in less space.
# This is a mid-level API; the high-level API is {@link #encodeText(String,Ecc)}
# and {@link #encodeBinary(byte[],Ecc)}.</p>
# @param segs the segments to encode
# @param ecl the error correction level to use (not {@code null}) (boostable)
# @param minVersion the minimum allowed version of the QR Code (at least 1)
# @param maxVersion the maximum allowed version of the QR Code (at most 40)
# @param mask the mask number to use (between 0 and 7 (inclusive)), or −1 for automatic mask
# @param boostEcl increases the ECC level as long as it doesn't increase the version number
# @return a QR Code (not {@code null}) representing the segments
# @throws NullPointerException if the list of segments, any segment, or the error correction level is {@code null}
# @throws IllegalArgumentException if 1 ≤ minVersion ≤ maxVersion ≤ 40
# or −1 ≤ mask ≤ 7 is violated
# @throws DataTooLongException if the segments fail to fit in
# the maxVersion QR Code at the ECL, which means they are too long
static [QrCode] encodeSegments([QrSegment[]] $segs, [Ecc] $ecl, [int] $minVersion, [int] $maxVersion, [int] $mask, [boolean] $boostEcl) {
if (-not $segs)
{
throw "segs (QrSegment[]) in encodeSegments is null"
}
if (-not $ecl)
{
throw "ecl (Ecc) in encodeSegments is null"
}
if ( -not ((([QrCode]::MIN_VERSION -le $minVersion) -and ($minVersion -le $maxVersion) -and ($maxVersion -le [QrCode]::MAX_VERSION)) -or ($mask -lt -1) -or ($mask -gt 7)))
{
throw "invalid version or mask in encodeSegments"
}
# Find the minimal version number to use
[int] $tmpVersion = 0
[int] $dataUsedBits = 0
$continueLoop = $true
$tmpVersion = $minVersion - 1
while ($continueLoop) {
$tmpVersion++
[int] $dataCapacityBits = [QrCode]::getNumDataCodewords($tmpVersion, $ecl) * 8 # Number of data bits available
$dataUsedBits = [QrSegment]::getTotalBits($segs, $tmpVersion)
if (($dataUsedBits -ne -1) -and ($dataUsedBits -le $dataCapacityBits))
{
$continueLoop = $false # This version number is found to be suitable
}
else {
if ($tmpVersion -ge $maxVersion) # All versions in the range could not fit the given data
{
[String] $msg = "Segment too long"
if ($dataUsedBits -ne -1)
{
$msg = "Data length = " + $dataUsedBits.toString() + " bits, Max capacity = " + $dataCapacityBits.toString() + " bits"
}
throw "$msg"
}
}
}
if ($dataUsedBits -eq -1)
{
throw "dataUsedBits error in encodeSegments"
}
# Increase the error correction level while the data still fits in the current version number
if($boostEcl)
{
$nextEcl = $ecl
while (-not $nextEcl.isMax())
{
$nextEcl = $nextEcl.getHigherEcc()
if ($dataUsedBits -le ([QrCode]::getNumDataCodewords($tmpVersion, $nextEcl) * 8))
{
$ecl.setEccValue($nextEcl.getEccValue())
}
}
}
# Concatenate all segments to create the data bit string
[QrBitBuffer] $bb = New-Object 'QrBitBuffer'
foreach ($seg in $segs)
{
$bb.appendBits($seg.qrmode.modeBits, 4)
$bb.appendBits($seg.numChars, $seg.qrmode.numCharCountBits($tmpVersion))
$bb.appendData($seg.getData())
}
if ($bb.getBitLength() -ne $dataUsedBits)
{
throw "bb.getBitLength must now be equal to dataUsedBits"
}
# Add terminator and pad up to a byte if applicable
[int] $dataCapacityBits = [QrCode]::getNumDataCodewords($tmpVersion, $ecl) * 8
if ($bb.getBitLength() -gt $dataCapacityBits)
{
throw "bb.getBitLength cannot be greater than dataCapacityBits"
}
$bb.appendBits(0,[Math]::Min(4,$dataCapacityBits - $bb.getBitLength()))
$bb.appendBits(0,((8 - $bb.getBitLength() % 8) % 8))
if (($bb.getBitLength() % 8) -ne 0)
{
throw "bb.getBitLength must be a multiple of 8"
}
# Pad with alternating bytes until data capacity is reached
for ([int] $padByte = 0xEC; $bb.getBitLength() -lt $dataCapacityBits; $padByte = $padByte -bxor (0xEC -bxor 0x11))
{
$bb.appendBits($padByte,8)
}
# Pack bits into bytes in big endian
$byteSize = ([Math]::truncate($bb.getBitLength() / 8))
[byte[]] $dataCodewords = New-Object 'byte[]' $byteSize
for ([int] $i = 0; $i -lt $byteSize; $i++) {
# Write-Host("BEFORE -- i : ",$i," --- bit : ",$bb.getBit($i)," --- (i >> 3) : ",($i -shr 3)," --- dcw[i>>3] : ",$datacodewords[$i -shr 3]," --- dcw : ",$datacodewords)
$dataCodewords[$i] = $bb.getByte($i)
# Write-Host(" AFTER -- i : ",$i," --- bit : ",$bb.getBit($i)," --- (i >> 3) : ",($i -shr 3)," --- dcw[i>>3] : ",$datacodewords[$i -shr 3]," --- dcw : ",$datacodewords)
}
# Create the QR Code object
return New-Object 'QrCode' $tmpVersion, $ecl, $dataCodewords, $mask
}
# ---- Instance fields ----
# Public immutable scalar parameters:
# The version number of this QR Code, which is between 1 and 40 (inclusive).
# This determines the size of this barcode.
[int] $version
# The width and height of this QR Code, measured in modules, between
# 21 and 177 (inclusive). This is equal to version × 4 + 17.
[int] $size
# Stores the size of the border
[int] $quietZone
# Stores the printing scale of the QR Code
[int] $scale
# /** The error correction level used in this QR Code, which is not {@code null}. */
[Ecc] $errorCorrectionLevel
# /** The index of the mask pattern used in this QR Code, which is between 0 and 7 (inclusive).
# * <p>Even if a QR Code is created with automatic masking requested (mask =
# * −1), the resulting object still has a mask value between 0 and 7. */
[int] $mask
# Stores if the QRCode must be displayed with inverted colors
[boolean] $isInverted
# // Private grids of modules/pixels, with dimensions of size*size:
# // The modules of this QR Code (false = white, true = black).
# // Immutable after constructor finishes. Accessed through getModule().
hidden [boolean[][]] $modules
# // Indicates function modules that are not subjected to masking. Discarded when constructor finishes.
hidden [boolean[][]] $isFunction
# ---- Constructor (low level) ----
# Constructs a QR Code with the specified version number,
# error correction level, data codeword bytes, and mask number.
# <p>This is a low-level API that most users should not use directly. A mid-level
# API is the {@link #encodeSegments(List,Ecc,int,int,int,boolean)} function.</p>
# @param ver the version number to use, which must be in the range 1 to 40 (inclusive)
# @param ecl the error correction level to use
# @param dataCodewords the bytes representing segments to encode (without ECC)
# @param msk the mask pattern to use, which is either −1 for automatic choice or from 0 to 7 for fixed choice
# @throws NullPointerException if the byte array or error correction level is {@code null}
# @throws IllegalArgumentException if the version or mask value is out of range,
# or if the data is the wrong length for the specified version and error correction level
QrCode([int] $ver, [Ecc] $ecl, [byte[]] $dataCodewords, [int] $msk) {
# Check arguments and initialize fields
if (($ver -lt [QrCode]::MIN_VERSION) -or ($ver -gt [QrCode]::MAX_VERSION))
{
throw "version is out of range. Must range from "+[QrCode]::MIN_VERSION+" to "+[QrCode]::MAX_VERSION
}
if (($msk -lt -2) -or ($msk -gt 7))
{
throw "mask is out of range. Must range from 0 to 7 (or -1 to auto detect ; -2 to disable masking)"
}
$this.version = $ver
$this.size = ($ver * 4) + 17
$this.errorCorrectionLevel = New-Object 'Ecc' $ecl;
$this.quietZone=[QrCode]::DEFAULT_QUIET_ZONE
if (-not $dataCodewords)