-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathqrReader.uc.js
3454 lines (3158 loc) · 100 KB
/
qrReader.uc.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
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
// ==UserScript==
// @include chrome://browser/content/browser.xul
// @charset UTF-8
// @note version 20130627
// @name qrReader.uc.js
// ==/UserScript==
(function(){
var qrReaderUc={
initialize:function(){
var menu=document.getElementById("contentAreaContextMenu");
menu.addEventListener("popupshowing", qrReaderUc.optionsShowHide, false);
qrReaderUc.createMenu();
},
getClickHandler:function(){
var url=qrReaderUc.imgURL;
qrcode.decode(url);
qrcode.callback=qrReaderUc.read;
},
read:function(d){
var p=/^(https?|ftp|file):\/\/[-_.~*'()|a-zA-Z0-9;:\/?,@&=+$%#]*[-_.~*)|a-zA-Z0-9;:\/?@&=+$%#]$/;
if(p.test(d)){
var f=confirm("QR码为网络地址,确认打开?"+'\n\n'+d);
if(f==true){
gBrowser.loadOneTab(d, null, null, null, true, false);
}
}
else if(d=="error decoding QR Code"){
alert("该图像不包含有效的QR码或无法读取它。 :(" );
}
else{
var r=confirm("QR代码值(按OK键将其复制到剪贴板):"+'\n\n'+d);
if(r==true){
try{
Components.classes["@mozilla.org/widget/clipboardhelper;1"].getService(Components.interfaces.nsIClipboardHelper).copyString(d);
}
catch(e){
alert(e);
}
}
}
},
createMenu:function(){
qrReaderUc.menuItems=0;
var menu=document.getElementById("contentAreaContextMenu");
var menuItem=document.createElement("menuitem");
menuItem.setAttribute("id", "qrReaderUc.menu.0");
menuItem.addEventListener("command", function(){qrReaderUc.getClickHandler();}, false);
menuItem.setAttribute("label", "解析图像QR码");
menuItem.setAttribute("class", "menuitem-iconic");
menuItem.setAttribute("image", "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAA3UlEQVQ4jaWSzWnDQBBGH2kiLsAnIfXhQzoKGBZcgHpxBWpBPqoAGdSCrJfTbix5V4Zk4GNmvvlddvCfgiqQsOdnY5HMJaYpGfulQa74uXCbt2qQm1Sa+GLvrbj3tN8NHg8/ICH6JX7L4TTp/e4BdBx1HD1A0Y/6E3SaxK7zBHq9+pXRWy7iBNp1Ytvq5eIZNATPkBB9Q1jFDMFv0LYVm0arSuvaGyRY1wk5zqrSphH7XofBI3iEZDsMKzvGn2Hfi8vy9nSLN7Es4jwXk3N/vxo2z/un/HYDN6f8F/kB7L2cwHXEHwAAAAAASUVORK5CYII=");
menu.insertBefore(menuItem, document.getElementById("context-openlinkintab"));qrReaderUc.menuItems++;
},
optionsShowHide:function(){ // show or hide the menuitem based on what the context menu is on
if(gContextMenu){
var isViewableImage=false;
qrReaderUc.imgTarget=gContextMenu.target;
if(gContextMenu.onImage){
isViewableImage=true;
qrReaderUc.imgURL=gContextMenu.imageURL;
if(gContextMenu.onLink){qrReaderUc.linkURL=gContextMenu.linkURL;}
else{qrReaderUc.linkURL='';}
}
for(var i=-1;i<(qrReaderUc.menuItems);i++){
var currentEntry=document.getElementById("qrReaderUc.menu."+i);
if(currentEntry){currentEntry.hidden=!isViewableImage;}
}
}
},
fun_OpenSite:function(url){
gBrowser.loadOneTab(url, null, null, null, true, false);
},
};
qrReaderUc.initialize();
/*
Ported to JavaScript by Lazar Laszlo 2011
[email protected], www.lazarsoft.info
*/
/*
*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
function BitMatrix( width, height)
{
if(!height)
height=width;
if (width < 1 || height < 1)
{
throw "Both dimensions must be greater than 0";
}
this.width = width;
this.height = height;
var rowSize = width >> 5;
if ((width & 0x1f) != 0)
{
rowSize++;
}
this.rowSize = rowSize;
this.bits = new Array(rowSize * height);
for(var i=0;i<this.bits.length;i++)
this.bits[i]=0;
this.__defineGetter__("Width", function()
{
return this.width;
});
this.__defineGetter__("Height", function()
{
return this.height;
});
this.__defineGetter__("Dimension", function()
{
if (this.width != this.height)
{
throw "Can't call getDimension() on a non-square matrix";
}
return this.width;
});
this.get_Renamed=function( x, y)
{
var offset = y * this.rowSize + (x >> 5);
return ((URShift(this.bits[offset], (x & 0x1f))) & 1) != 0;
}
this.set_Renamed=function( x, y)
{
var offset = y * this.rowSize + (x >> 5);
this.bits[offset] |= 1 << (x & 0x1f);
}
this.flip=function( x, y)
{
var offset = y * this.rowSize + (x >> 5);
this.bits[offset] ^= 1 << (x & 0x1f);
}
this.clear=function()
{
var max = this.bits.length;
for (var i = 0; i < max; i++)
{
this.bits[i] = 0;
}
}
this.setRegion=function( left, top, width, height)
{
if (top < 0 || left < 0)
{
throw "Left and top must be nonnegative";
}
if (height < 1 || width < 1)
{
throw "Height and width must be at least 1";
}
var right = left + width;
var bottom = top + height;
if (bottom > this.height || right > this.width)
{
throw "The region must fit inside the matrix";
}
for (var y = top; y < bottom; y++)
{
var offset = y * this.rowSize;
for (var x = left; x < right; x++)
{
this.bits[offset + (x >> 5)] |= 1 << (x & 0x1f);
}
}
}
}
var GridSampler = {};
GridSampler.checkAndNudgePoints=function( image, points)
{
var width = qrcode.width;
var height = qrcode.height;
// Check and nudge points from start until we see some that are OK:
var nudged = true;
for (var offset = 0; offset < points.Length && nudged; offset += 2)
{
var x = Math.floor (points[offset]);
var y = Math.floor( points[offset + 1]);
if (x < - 1 || x > width || y < - 1 || y > height)
{
throw "Error.checkAndNudgePoints ";
}
nudged = false;
if (x == - 1)
{
points[offset] = 0.0;
nudged = true;
}
else if (x == width)
{
points[offset] = width - 1;
nudged = true;
}
if (y == - 1)
{
points[offset + 1] = 0.0;
nudged = true;
}
else if (y == height)
{
points[offset + 1] = height - 1;
nudged = true;
}
}
// Check and nudge points from end:
nudged = true;
for (var offset = points.Length - 2; offset >= 0 && nudged; offset -= 2)
{
var x = Math.floor( points[offset]);
var y = Math.floor( points[offset + 1]);
if (x < - 1 || x > width || y < - 1 || y > height)
{
throw "Error.checkAndNudgePoints ";
}
nudged = false;
if (x == - 1)
{
points[offset] = 0.0;
nudged = true;
}
else if (x == width)
{
points[offset] = width - 1;
nudged = true;
}
if (y == - 1)
{
points[offset + 1] = 0.0;
nudged = true;
}
else if (y == height)
{
points[offset + 1] = height - 1;
nudged = true;
}
}
}
GridSampler.sampleGrid3=function( image, dimension, transform)
{
var bits = new BitMatrix(dimension);
var points = new Array(dimension << 1);
for (var y = 0; y < dimension; y++)
{
var max = points.length;
var iValue = y + 0.5;
for (var x = 0; x < max; x += 2)
{
points[x] = (x >> 1) + 0.5;
points[x + 1] = iValue;
}
transform.transformPoints1(points);
// Quick check to see if points transformed to something inside the image;
// sufficient to check the endpoints
GridSampler.checkAndNudgePoints(image, points);
try
{
for (var x = 0; x < max; x += 2)
{
var xpoint = (Math.floor( points[x]) * 4) + (Math.floor( points[x + 1]) * qrcode.width * 4);
var bit = image[Math.floor( points[x])+ qrcode.width* Math.floor( points[x + 1])];
qrcode.imagedata.data[xpoint] = bit?255:0;
qrcode.imagedata.data[xpoint+1] = bit?255:0;
qrcode.imagedata.data[xpoint+2] = 0;
qrcode.imagedata.data[xpoint+3] = 255;
//bits[x >> 1][ y]=bit;
if(bit)
bits.set_Renamed(x >> 1, y);
}
}
catch ( aioobe)
{
// This feels wrong, but, sometimes if the finder patterns are misidentified, the resulting
// transform gets "twisted" such that it maps a straight line of points to a set of points
// whose endpoints are in bounds, but others are not. There is probably some mathematical
// way to detect this about the transformation that I don't know yet.
// This results in an ugly runtime exception despite our clever checks above -- can't have
// that. We could check each point's coordinates but that feels duplicative. We settle for
// catching and wrapping ArrayIndexOutOfBoundsException.
throw "Error.checkAndNudgePoints";
}
}
return bits;
}
GridSampler.sampleGridx=function( image, dimension, p1ToX, p1ToY, p2ToX, p2ToY, p3ToX, p3ToY, p4ToX, p4ToY, p1FromX, p1FromY, p2FromX, p2FromY, p3FromX, p3FromY, p4FromX, p4FromY)
{
var transform = PerspectiveTransform.quadrilateralToQuadrilateral(p1ToX, p1ToY, p2ToX, p2ToY, p3ToX, p3ToY, p4ToX, p4ToY, p1FromX, p1FromY, p2FromX, p2FromY, p3FromX, p3FromY, p4FromX, p4FromY);
return GridSampler.sampleGrid3(image, dimension, transform);
}
var qrcode = {};
qrcode.imagedata = null;
qrcode.width = 0;
qrcode.height = 0;
qrcode.qrCodeSymbol = null;
qrcode.debug = false;
qrcode.sizeOfDataLengthInfo = [ [ 10, 9, 8, 8 ], [ 12, 11, 16, 10 ], [ 14, 13, 16, 12 ] ];
qrcode.callback = null;
qrcode.decode = function(src){
if(arguments.length==0)
{
var canvas_qr = document.getElementById("qr-canvas");
var context = canvas_qr.getContext('2d');
qrcode.width = canvas_qr.width;
qrcode.height = canvas_qr.height;
qrcode.imagedata = context.getImageData(0, 0, qrcode.width, qrcode.height);
qrcode.result = qrcode.process(context);
if(qrcode.callback!=null)
qrcode.callback(qrcode.result);
return qrcode.result;
}
else
{
var image = new Image();
image.onload=function(){
//var canvas_qr = document.getElementById("qr-canvas");
var canvas_qr = document.createElementNS("http://www.w3.org/1999/xhtml", "canvas");
var context = canvas_qr.getContext('2d');
var canvas_out = document.getElementById("out-canvas");
if(canvas_out!=null)
{
var outctx = canvas_out.getContext('2d');
outctx.clearRect(0, 0, 320, 240);
outctx.drawImage(image, 0, 0, 320, 240);
}
canvas_qr.width = image.width;
canvas_qr.height = image.height;
context.drawImage(image, 0, 0);
qrcode.width = image.width;
qrcode.height = image.height;
try{
qrcode.imagedata = context.getImageData(0, 0, image.width, image.height);
}catch(e){
qrcode.result = "Cross domain image reading not supported in your browser! Save it to your computer then drag and drop the file!";
if(qrcode.callback!=null)
qrcode.callback(qrcode.result);
return;
}
try
{
qrcode.result = qrcode.process(context);
}
catch(e)
{
console.log(e);
qrcode.result = "error decoding QR Code";
}
if(qrcode.callback!=null)
qrcode.callback(qrcode.result);
}
image.src = src;
}
}
qrcode.decode_utf8 = function ( s )
{
return decodeURIComponent( s );
//return decodeURIComponent( escape( s ) );
}
qrcode.process = function(ctx){
var start = new Date().getTime();
var image = qrcode.grayScaleToBitmap(qrcode.grayscale());
//var image = qrcode.binarize(128);
if(qrcode.debug)
{
for (var y = 0; y < qrcode.height; y++)
{
for (var x = 0; x < qrcode.width; x++)
{
var point = (x * 4) + (y * qrcode.width * 4);
qrcode.imagedata.data[point] = image[x+y*qrcode.width]?0:0;
qrcode.imagedata.data[point+1] = image[x+y*qrcode.width]?0:0;
qrcode.imagedata.data[point+2] = image[x+y*qrcode.width]?255:0;
}
}
ctx.putImageData(qrcode.imagedata, 0, 0);
}
//var finderPatternInfo = new FinderPatternFinder().findFinderPattern(image);
var detector = new Detector(image);
var qRCodeMatrix = detector.detect();
/*for (var y = 0; y < qRCodeMatrix.bits.Height; y++)
{
for (var x = 0; x < qRCodeMatrix.bits.Width; x++)
{
var point = (x * 4*2) + (y*2 * qrcode.width * 4);
qrcode.imagedata.data[point] = qRCodeMatrix.bits.get_Renamed(x,y)?0:0;
qrcode.imagedata.data[point+1] = qRCodeMatrix.bits.get_Renamed(x,y)?0:0;
qrcode.imagedata.data[point+2] = qRCodeMatrix.bits.get_Renamed(x,y)?255:0;
}
}*/
if(qrcode.debug)
ctx.putImageData(qrcode.imagedata, 0, 0);
var reader = Decoder.decode(qRCodeMatrix.bits);
var data = reader.DataByte;
var str="";
var strarray = [];
for(var i=0;i<data.length;i++)
{
for(var j=0;j<data[i].length;j++)
//str+=String.fromCharCode(data[i][j]);
strarray.push(data[i][j]);
}
str = String.fromCharCode.apply(null, strarray);
var end = new Date().getTime();
var time = end - start;
console.log(time);
return qrcode.decode_utf8(str);
//alert("Time:" + time + " Code: "+str);
}
qrcode.getPixel = function(x,y){
if (qrcode.width < x) {
throw "point error";
}
if (qrcode.height < y) {
throw "point error";
}
var point = (x * 4) + (y * qrcode.width * 4);
var p = (qrcode.imagedata.data[point]*33 + qrcode.imagedata.data[point + 1]*34 + qrcode.imagedata.data[point + 2]*33)/100;
return p;
}
qrcode.binarize = function(th){
var ret = new Array(qrcode.width*qrcode.height);
for (var y = 0; y < qrcode.height; y++)
{
for (var x = 0; x < qrcode.width; x++)
{
var gray = qrcode.getPixel(x, y);
ret[x+y*qrcode.width] = gray<=th?true:false;
}
}
return ret;
}
qrcode.getMiddleBrightnessPerArea=function(image)
{
var numSqrtArea = 4;
//obtain middle brightness((min + max) / 2) per area
var areaWidth = Math.floor(qrcode.width / numSqrtArea);
var areaHeight = Math.floor(qrcode.height / numSqrtArea);
var minmax = new Array(numSqrtArea);
for (var i = 0; i < numSqrtArea; i++)
{
minmax[i] = new Array(numSqrtArea);
for (var i2 = 0; i2 < numSqrtArea; i2++)
{
minmax[i][i2] = new Array(0,0);
}
}
for (var ay = 0; ay < numSqrtArea; ay++)
{
for (var ax = 0; ax < numSqrtArea; ax++)
{
minmax[ax][ay][0] = 0xFF;
for (var dy = 0; dy < areaHeight; dy++)
{
for (var dx = 0; dx < areaWidth; dx++)
{
var target = image[areaWidth * ax + dx+(areaHeight * ay + dy)*qrcode.width];
if (target < minmax[ax][ay][0])
minmax[ax][ay][0] = target;
if (target > minmax[ax][ay][1])
minmax[ax][ay][1] = target;
}
}
//minmax[ax][ay][0] = (minmax[ax][ay][0] + minmax[ax][ay][1]) / 2;
}
}
var middle = new Array(numSqrtArea);
for (var i3 = 0; i3 < numSqrtArea; i3++)
{
middle[i3] = new Array(numSqrtArea);
}
for (var ay = 0; ay < numSqrtArea; ay++)
{
for (var ax = 0; ax < numSqrtArea; ax++)
{
middle[ax][ay] = Math.floor((minmax[ax][ay][0] + minmax[ax][ay][1]) / 2);
//Console.out.print(middle[ax][ay] + ",");
}
//Console.out.println("");
}
//Console.out.println("");
return middle;
}
qrcode.grayScaleToBitmap=function(grayScale)
{
var middle = qrcode.getMiddleBrightnessPerArea(grayScale);
var sqrtNumArea = middle.length;
var areaWidth = Math.floor(qrcode.width / sqrtNumArea);
var areaHeight = Math.floor(qrcode.height / sqrtNumArea);
var bitmap = new Array(qrcode.height*qrcode.width);
for (var ay = 0; ay < sqrtNumArea; ay++)
{
for (var ax = 0; ax < sqrtNumArea; ax++)
{
for (var dy = 0; dy < areaHeight; dy++)
{
for (var dx = 0; dx < areaWidth; dx++)
{
bitmap[areaWidth * ax + dx+ (areaHeight * ay + dy)*qrcode.width] = (grayScale[areaWidth * ax + dx+ (areaHeight * ay + dy)*qrcode.width] < middle[ax][ay])?true:false;
}
}
}
}
return bitmap;
}
qrcode.grayscale = function(){
var ret = new Array(qrcode.width*qrcode.height);
for (var y = 0; y < qrcode.height; y++)
{
for (var x = 0; x < qrcode.width; x++)
{
var gray = qrcode.getPixel(x, y);
ret[x+y*qrcode.width] = gray;
}
}
return ret;
}
function URShift( number, bits)
{
if (number >= 0)
return number >> bits;
else
return (number >> bits) + (2 << ~bits);
}
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
var MIN_SKIP = 3;
var MAX_MODULES = 57;
var INTEGER_MATH_SHIFT = 8;
var CENTER_QUORUM = 2;
qrcode.orderBestPatterns=function(patterns)
{
function distance( pattern1, pattern2)
{
var xDiff = pattern1.X - pattern2.X;
var yDiff = pattern1.Y - pattern2.Y;
return Math.sqrt( (xDiff * xDiff + yDiff * yDiff));
}
/// <summary> Returns the z component of the cross product between vectors BC and BA.</summary>
function crossProductZ( pointA, pointB, pointC)
{
var bX = pointB.x;
var bY = pointB.y;
return ((pointC.x - bX) * (pointA.y - bY)) - ((pointC.y - bY) * (pointA.x - bX));
}
// Find distances between pattern centers
var zeroOneDistance = distance(patterns[0], patterns[1]);
var oneTwoDistance = distance(patterns[1], patterns[2]);
var zeroTwoDistance = distance(patterns[0], patterns[2]);
var pointA, pointB, pointC;
// Assume one closest to other two is B; A and C will just be guesses at first
if (oneTwoDistance >= zeroOneDistance && oneTwoDistance >= zeroTwoDistance)
{
pointB = patterns[0];
pointA = patterns[1];
pointC = patterns[2];
}
else if (zeroTwoDistance >= oneTwoDistance && zeroTwoDistance >= zeroOneDistance)
{
pointB = patterns[1];
pointA = patterns[0];
pointC = patterns[2];
}
else
{
pointB = patterns[2];
pointA = patterns[0];
pointC = patterns[1];
}
// Use cross product to figure out whether A and C are correct or flipped.
// This asks whether BC x BA has a positive z component, which is the arrangement
// we want for A, B, C. If it's negative, then we've got it flipped around and
// should swap A and C.
if (crossProductZ(pointA, pointB, pointC) < 0.0)
{
var temp = pointA;
pointA = pointC;
pointC = temp;
}
patterns[0] = pointA;
patterns[1] = pointB;
patterns[2] = pointC;
}
function FinderPattern(posX, posY, estimatedModuleSize)
{
this.x=posX;
this.y=posY;
this.count = 1;
this.estimatedModuleSize = estimatedModuleSize;
this.__defineGetter__("EstimatedModuleSize", function()
{
return this.estimatedModuleSize;
});
this.__defineGetter__("Count", function()
{
return this.count;
});
this.__defineGetter__("X", function()
{
return this.x;
});
this.__defineGetter__("Y", function()
{
return this.y;
});
this.incrementCount = function()
{
this.count++;
}
this.aboutEquals=function( moduleSize, i, j)
{
if (Math.abs(i - this.y) <= moduleSize && Math.abs(j - this.x) <= moduleSize)
{
var moduleSizeDiff = Math.abs(moduleSize - this.estimatedModuleSize);
return moduleSizeDiff <= 1.0 || moduleSizeDiff / this.estimatedModuleSize <= 1.0;
}
return false;
}
}
function FinderPatternInfo(patternCenters)
{
this.bottomLeft = patternCenters[0];
this.topLeft = patternCenters[1];
this.topRight = patternCenters[2];
this.__defineGetter__("BottomLeft", function()
{
return this.bottomLeft;
});
this.__defineGetter__("TopLeft", function()
{
return this.topLeft;
});
this.__defineGetter__("TopRight", function()
{
return this.topRight;
});
}
function FinderPatternFinder()
{
this.image=null;
this.possibleCenters = [];
this.hasSkipped = false;
this.crossCheckStateCount = new Array(0,0,0,0,0);
this.resultPointCallback = null;
this.__defineGetter__("CrossCheckStateCount", function()
{
this.crossCheckStateCount[0] = 0;
this.crossCheckStateCount[1] = 0;
this.crossCheckStateCount[2] = 0;
this.crossCheckStateCount[3] = 0;
this.crossCheckStateCount[4] = 0;
return this.crossCheckStateCount;
});
this.foundPatternCross=function( stateCount)
{
var totalModuleSize = 0;
for (var i = 0; i < 5; i++)
{
var count = stateCount[i];
if (count == 0)
{
return false;
}
totalModuleSize += count;
}
if (totalModuleSize < 7)
{
return false;
}
var moduleSize = Math.floor((totalModuleSize << INTEGER_MATH_SHIFT) / 7);
var maxVariance = Math.floor(moduleSize / 2);
// Allow less than 50% variance from 1-1-3-1-1 proportions
return Math.abs(moduleSize - (stateCount[0] << INTEGER_MATH_SHIFT)) < maxVariance && Math.abs(moduleSize - (stateCount[1] << INTEGER_MATH_SHIFT)) < maxVariance && Math.abs(3 * moduleSize - (stateCount[2] << INTEGER_MATH_SHIFT)) < 3 * maxVariance && Math.abs(moduleSize - (stateCount[3] << INTEGER_MATH_SHIFT)) < maxVariance && Math.abs(moduleSize - (stateCount[4] << INTEGER_MATH_SHIFT)) < maxVariance;
}
this.centerFromEnd=function( stateCount, end)
{
return (end - stateCount[4] - stateCount[3]) - stateCount[2] / 2.0;
}
this.crossCheckVertical=function( startI, centerJ, maxCount, originalStateCountTotal)
{
var image = this.image;
var maxI = qrcode.height;
var stateCount = this.CrossCheckStateCount;
// Start counting up from center
var i = startI;
while (i >= 0 && image[centerJ + i*qrcode.width])
{
stateCount[2]++;
i--;
}
if (i < 0)
{
return NaN;
}
while (i >= 0 && !image[centerJ +i*qrcode.width] && stateCount[1] <= maxCount)
{
stateCount[1]++;
i--;
}
// If already too many modules in this state or ran off the edge:
if (i < 0 || stateCount[1] > maxCount)
{
return NaN;
}
while (i >= 0 && image[centerJ + i*qrcode.width] && stateCount[0] <= maxCount)
{
stateCount[0]++;
i--;
}
if (stateCount[0] > maxCount)
{
return NaN;
}
// Now also count down from center
i = startI + 1;
while (i < maxI && image[centerJ +i*qrcode.width])
{
stateCount[2]++;
i++;
}
if (i == maxI)
{
return NaN;
}
while (i < maxI && !image[centerJ + i*qrcode.width] && stateCount[3] < maxCount)
{
stateCount[3]++;
i++;
}
if (i == maxI || stateCount[3] >= maxCount)
{
return NaN;
}
while (i < maxI && image[centerJ + i*qrcode.width] && stateCount[4] < maxCount)
{
stateCount[4]++;
i++;
}
if (stateCount[4] >= maxCount)
{
return NaN;
}
// If we found a finder-pattern-like section, but its size is more than 40% different than
// the original, assume it's a false positive
var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4];
if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal)
{
return NaN;
}
return this.foundPatternCross(stateCount)?this.centerFromEnd(stateCount, i):NaN;
}
this.crossCheckHorizontal=function( startJ, centerI, maxCount, originalStateCountTotal)
{
var image = this.image;
var maxJ = qrcode.width;
var stateCount = this.CrossCheckStateCount;
var j = startJ;
while (j >= 0 && image[j+ centerI*qrcode.width])
{
stateCount[2]++;
j--;
}
if (j < 0)
{
return NaN;
}
while (j >= 0 && !image[j+ centerI*qrcode.width] && stateCount[1] <= maxCount)
{
stateCount[1]++;
j--;
}
if (j < 0 || stateCount[1] > maxCount)
{
return NaN;
}
while (j >= 0 && image[j+ centerI*qrcode.width] && stateCount[0] <= maxCount)
{
stateCount[0]++;
j--;
}
if (stateCount[0] > maxCount)
{
return NaN;
}
j = startJ + 1;
while (j < maxJ && image[j+ centerI*qrcode.width])
{
stateCount[2]++;
j++;
}
if (j == maxJ)
{
return NaN;
}
while (j < maxJ && !image[j+ centerI*qrcode.width] && stateCount[3] < maxCount)
{
stateCount[3]++;
j++;
}
if (j == maxJ || stateCount[3] >= maxCount)
{
return NaN;
}
while (j < maxJ && image[j+ centerI*qrcode.width] && stateCount[4] < maxCount)
{
stateCount[4]++;
j++;
}
if (stateCount[4] >= maxCount)
{
return NaN;
}
// If we found a finder-pattern-like section, but its size is significantly different than
// the original, assume it's a false positive
var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4];
if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= originalStateCountTotal)
{
return NaN;
}
return this.foundPatternCross(stateCount)?this.centerFromEnd(stateCount, j):NaN;
}
this.handlePossibleCenter=function( stateCount, i, j)
{
var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4];
var centerJ = this.centerFromEnd(stateCount, j); //float
var centerI = this.crossCheckVertical(i, Math.floor( centerJ), stateCount[2], stateCountTotal); //float
if (!isNaN(centerI))
{
// Re-cross check
centerJ = this.crossCheckHorizontal(Math.floor( centerJ), Math.floor( centerI), stateCount[2], stateCountTotal);
if (!isNaN(centerJ))
{
var estimatedModuleSize = stateCountTotal / 7.0;
var found = false;
var max = this.possibleCenters.length;
for (var index = 0; index < max; index++)
{
var center = this.possibleCenters[index];
// Look for about the same center and module size:
if (center.aboutEquals(estimatedModuleSize, centerI, centerJ))
{
center.incrementCount();
found = true;
break;
}
}
if (!found)
{
var point = new FinderPattern(centerJ, centerI, estimatedModuleSize);
this.possibleCenters.push(point);
if (this.resultPointCallback != null)
{
this.resultPointCallback.foundPossibleResultPoint(point);
}
}
return true;
}
}
return false;
}
this.selectBestPatterns=function()
{
var startSize = this.possibleCenters.length;
if (startSize < 3)
{
// Couldn't find enough finder patterns
throw "Couldn't find enough finder patterns (found " + startSize + ")";
}
// Filter outlier possibilities whose module size is too different
if (startSize > 3)
{
// But we can only afford to do so if we have at least 4 possibilities to choose from
var totalModuleSize = 0.0;
for (var i = 0; i < startSize; i++)
{
totalModuleSize += this.possibleCenters[i].EstimatedModuleSize;
}
var average = totalModuleSize / startSize;
for (var i = 0; i < this.possibleCenters.length && this.possibleCenters.length > 3; i++)
{
var pattern = this.possibleCenters[i];
if (Math.abs(pattern.EstimatedModuleSize - average) > 0.2 * average)
{
this.possibleCenters.remove(i);
i--;
}
}
}
if (this.possibleCenters.Count > 3)
{
// Throw away all but those first size candidate points we found.
//Collections.insertionSort(possibleCenters, new CenterComparator());
//SupportClass.SetCapacity(possibleCenters, 3);
}
return new Array( this.possibleCenters[0], this.possibleCenters[1], this.possibleCenters[2]);
}
this.findRowSkip=function()
{
var max = this.possibleCenters.length;