Roo/dialog/UploadCropbox.js
[roojs1] / Roo / dialog / UploadCropbox.js
1
2 /*
3 * Licence: LGPL
4 */
5
6 /**
7  * @class Roo.dialog.UploadCropbox
8  * @extends Roo.BoxComponent
9  * Dialog UploadCropbox class
10  * @cfg {String} emptyText show when image has been loaded
11  * @cfg {String} rotateNotify show when image too small to rotate
12  * @cfg {Number} errorTimeout default 3000
13  * @cfg {Number} minWidth default 300
14  * @cfg {Number} minHeight default 300
15  * @cfg {Number} outputMaxWidth default 1200
16  * @cfg {Array} buttons default ['rotateLeft', 'pictureBtn', 'rotateRight']
17  * @cfg {Boolean} isDocument (true|false) default false
18  * @cfg {String} url action url
19  * @cfg {String} paramName default 'imageUpload'
20  * @cfg {String} method default POST
21  * @cfg {Boolean} loadMask (true|false) default true
22  * @cfg {Boolean} loadingText default 'Loading...'
23  * 
24  * @constructor
25  * Create a new UploadCropbox
26  * @param {Object} config The config object
27  */
28
29  Roo.dialog.UploadCropbox = function(config){
30     Roo.dialog.UploadCropbox.superclass.constructor.call(this, config);
31     
32     this.addEvents({
33         /**
34          * @event beforeselectfile
35          * Fire before select file
36          * @param {Roo.dialog.UploadCropbox} this
37          */
38         "beforeselectfile" : true,
39         /**
40          * @event initial
41          * Fire after initEvent
42          * @param {Roo.dialog.UploadCropbox} this
43          */
44         "initial" : true,
45         /**
46          * @event crop
47          * Fire after initEvent
48          * @param {Roo.dialog.UploadCropbox} this
49          * @param {String} data
50          */
51         "crop" : true,
52         /**
53          * @event prepare
54          * Fire when preparing the file data
55          * @param {Roo.dialog.UploadCropbox} this
56          * @param {Object} file
57          */
58         "prepare" : true,
59         /**
60          * @event exception
61          * Fire when get exception
62          * @param {Roo.dialog.UploadCropbox} this
63          * @param {XMLHttpRequest} xhr
64          */
65         "exception" : true,
66         /**
67          * @event beforeloadcanvas
68          * Fire before load the canvas
69          * @param {Roo.dialog.UploadCropbox} this
70          * @param {String} src
71          */
72         "beforeloadcanvas" : true,
73         /**
74          * @event trash
75          * Fire when trash image
76          * @param {Roo.dialog.UploadCropbox} this
77          */
78         "trash" : true,
79         /**
80          * @event download
81          * Fire when download the image
82          * @param {Roo.dialog.UploadCropbox} this
83          */
84         "download" : true,
85         /**
86          * @event footerbuttonclick
87          * Fire when footerbuttonclick
88          * @param {Roo.dialog.UploadCropbox} this
89          * @param {String} type
90          */
91         "footerbuttonclick" : true,
92         /**
93          * @event resize
94          * Fire when resize
95          * @param {Roo.dialog.UploadCropbox} this
96          */
97         "resize" : true,
98         /**
99          * @event rotate
100          * Fire when rotate the image
101          * @param {Roo.dialog.UploadCropbox} this
102          * @param {String} pos
103          */
104         "rotate" : true,
105         /**
106          * @event inspect
107          * Fire when inspect the file
108          * @param {Roo.dialog.UploadCropbox} this
109          * @param {Object} file
110          */
111         "inspect" : true,
112         /**
113          * @event upload
114          * Fire when xhr upload the file
115          * @param {Roo.dialog.UploadCropbox} this
116          * @param {Object} data
117          */
118         "upload" : true,
119         /**
120          * @event arrange
121          * Fire when arrange the file data
122          * @param {Roo.dialog.UploadCropbox} this
123          * @param {Object} formData
124          */
125         "arrange" : true,
126         /**
127          * @event loadcanvas
128          * Fire after load the canvas
129          * @param {Roo.dialog.UploadCropbox}
130          * @param {Object} imgEl
131          */
132         "loadcanvas" : true
133     });
134     
135     this.buttons = this.buttons || Roo.dialog.UploadCropbox.footer.STANDARD;
136 };
137
138 Roo.extend(Roo.dialog.UploadCropbox, Roo.Component,  {
139     
140     emptyText : 'Click to upload image',
141     rotateNotify : 'Image is too small to rotate',
142     errorTimeout : 3000,
143     scale : 0,
144     baseScale : 1,
145     rotate : 0,
146     dragable : false,
147     pinching : false,
148     mouseX : 0,
149     mouseY : 0,
150     cropData : false,
151     minWidth : 300,
152     minHeight : 300,
153     outputMaxWidth : 1200,
154     file : false,
155     exif : {},
156     baseRotate : 1,
157     cropType : 'image/jpeg',
158     buttons : false,
159     canvasLoaded : false,
160     isDocument : false,
161     method : 'POST',
162     paramName : 'imageUpload',
163     loadMask : true,
164     loadingText : 'Loading...',
165     maskEl : false,
166     
167     getAutoCreate : function()
168     {
169         var cfg = {
170             tag : 'div',
171             cls : 'roo-upload-cropbox',
172             cn : [
173                 {
174                     tag : 'input',
175                     cls : 'roo-upload-cropbox-selector',
176                     type : 'file'
177                 },
178                 {
179                     tag : 'div',
180                     cls : 'roo-upload-cropbox-body',
181                     style : 'cursor:pointer',
182                     cn : [
183                         {
184                             tag : 'div',
185                             cls : 'roo-upload-cropbox-preview'
186                         },
187                         {
188                             tag : 'div',
189                             cls : 'roo-upload-cropbox-thumb'
190                         },
191                         {
192                             tag : 'div',
193                             cls : 'roo-upload-cropbox-empty-notify',
194                             html : this.emptyText
195                         },
196                         {
197                             tag : 'div',
198                             cls : 'roo-upload-cropbox-error-notify alert alert-danger',
199                             html : this.rotateNotify
200                         }
201                     ]
202                 },
203                 {
204                     tag : 'div',
205                     cls : 'roo-upload-cropbox-footer',
206                     cn : {
207                         tag : 'div',
208                         cls : 'btn-group btn-group-justified roo-upload-cropbox-btn-group',
209                         cn : []
210                     }
211                 }
212             ]
213         };
214         
215         return cfg;
216     },
217     
218     onRender : function(ct, position)
219     {
220         Roo.dialog.UploadCropbox.superclass.onRender.call(this, ct, position);
221
222         if(this.el){
223             if (this.el.attr('xtype')) {
224                 this.el.attr('xtypex', this.el.attr('xtype'));
225                 this.el.dom.removeAttribute('xtype');
226                 
227                 this.initEvents();
228             }
229         }
230         else {
231             var cfg = Roo.apply({},  this.getAutoCreate());
232         
233             cfg.id = this.id || Roo.id();
234             
235             if (this.cls) {
236                 cfg.cls = (typeof(cfg.cls) == 'undefined' ? this.cls : cfg.cls) + ' ' + this.cls;
237             }
238             
239             if (this.style) { // fixme needs to support more complex style data.
240                 cfg.style = (typeof(cfg.style) == 'undefined' ? this.style : cfg.style) + '; ' + this.style;
241             }
242             
243             this.el = ct.createChild(cfg, position);
244             
245             this.initEvents();
246         }
247         
248         if (this.buttons.length) {
249             
250             Roo.each(this.buttons, function(bb) {
251                 
252                 var btn = this.el.select('.roo-upload-cropbox-footer div.roo-upload-cropbox-btn-group').first().createChild(bb);
253                 
254                 btn.on('click', this.onFooterButtonClick.createDelegate(this, [bb.action], true));
255                 
256             }, this);
257         }
258         
259         if(this.loadMask){
260             this.maskEl = this.el;
261         }
262     },
263     
264     initEvents : function()
265     {
266         this.urlAPI = (window.createObjectURL && window) || 
267                                 (window.URL && URL.revokeObjectURL && URL) || 
268                                 (window.webkitURL && webkitURL);
269                         
270         this.bodyEl = this.el.select('.roo-upload-cropbox-body', true).first();
271         this.bodyEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
272         
273         this.selectorEl = this.el.select('.roo-upload-cropbox-selector', true).first();
274         this.selectorEl.hide();
275         
276         this.previewEl = this.el.select('.roo-upload-cropbox-preview', true).first();
277         this.previewEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
278         
279         this.thumbEl = this.el.select('.roo-upload-cropbox-thumb', true).first();
280         this.thumbEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
281         this.thumbEl.hide();
282         
283         this.notifyEl = this.el.select('.roo-upload-cropbox-empty-notify', true).first();
284         this.notifyEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
285         
286         this.errorEl = this.el.select('.roo-upload-cropbox-error-notify', true).first();
287         this.errorEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
288         this.errorEl.hide();
289         
290         this.footerEl = this.el.select('.roo-upload-cropbox-footer', true).first();
291         this.footerEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
292         this.footerEl.hide();
293         
294         this.setThumbBoxSize();
295         
296         this.bind();
297         
298         this.resize();
299         
300         this.fireEvent('initial', this);
301     },
302
303     bind : function()
304     {
305         var _this = this;
306         
307         window.addEventListener("resize", function() { _this.resize(); } );
308         
309         this.bodyEl.on('click', this.beforeSelectFile, this);
310         
311         if(Roo.isTouch){
312             this.bodyEl.on('touchstart', this.onTouchStart, this);
313             this.bodyEl.on('touchmove', this.onTouchMove, this);
314             this.bodyEl.on('touchend', this.onTouchEnd, this);
315         }
316         
317         if(!Roo.isTouch){
318             this.bodyEl.on('mousedown', this.onMouseDown, this);
319             this.bodyEl.on('mousemove', this.onMouseMove, this);
320             var mousewheel = (/Firefox/i.test(navigator.userAgent))? 'DOMMouseScroll' : 'mousewheel';
321             this.bodyEl.on(mousewheel, this.onMouseWheel, this);
322             Roo.get(document).on('mouseup', this.onMouseUp, this);
323         }
324         
325         this.selectorEl.on('change', this.onFileSelected, this);
326     },
327     
328     reset : function()
329     {    
330         this.scale = 0;
331         this.baseScale = 1;
332         this.rotate = 0;
333         this.baseRotate = 1;
334         this.dragable = false;
335         this.pinching = false;
336         this.mouseX = 0;
337         this.mouseY = 0;
338         this.cropData = false;
339         this.notifyEl.dom.innerHTML = this.emptyText;
340         
341         // this.selectorEl.dom.value = '';
342         
343     },
344     
345     resize : function()
346     {
347         if(this.fireEvent('resize', this) != false){
348             this.setThumbBoxPosition();
349             this.setCanvasPosition();
350         }
351     },
352     
353     onFooterButtonClick : function(e, el, o, type)
354     {
355         switch (type) {
356             case 'rotate-left' :
357                 this.onRotateLeft(e);
358                 break;
359             case 'rotate-right' :
360                 this.onRotateRight(e);
361                 break;
362             case 'picture' :
363                 this.beforeSelectFile(e);
364                 break;
365             case 'trash' :
366                 this.trash(e);
367                 break;
368             case 'crop' :
369                 this.crop(e);
370                 break;
371             case 'download' :
372                 this.download(e);
373                 break;
374             default :
375                 break;
376         }
377         
378         this.fireEvent('footerbuttonclick', this, type);
379     },
380     
381     beforeSelectFile : function(e)
382     {
383         e.preventDefault();
384         
385         if(this.fireEvent('beforeselectfile', this) != false){
386             this.selectorEl.dom.click();
387         }
388     },
389     
390     onFileSelected : function(e)
391     {
392         e.preventDefault();
393         
394         if(typeof(this.selectorEl.dom.files) == 'undefined' || !this.selectorEl.dom.files.length){
395             return;
396         }
397         
398         var file = this.selectorEl.dom.files[0];
399         
400         if(this.fireEvent('inspect', this, file) != false){
401             this.prepare(file);
402         }
403         
404     },
405     
406     trash : function(e)
407     {
408         this.fireEvent('trash', this);
409     },
410     
411     download : function(e)
412     {
413         this.fireEvent('download', this);
414     },
415     
416     loadCanvas : function(src)
417     {   
418         if(this.fireEvent('beforeloadcanvas', this, src) != false){
419             
420             this.reset();
421             
422             this.imageEl = document.createElement('img');
423             
424             var _this = this;
425             
426             this.imageEl.addEventListener("load", function(){ _this.onLoadCanvas(); });
427             
428             this.imageEl.src = src;
429         }
430     },
431     
432     onLoadCanvas : function()
433     {   
434         this.imageEl.OriginWidth = this.imageEl.naturalWidth || this.imageEl.width;
435         this.imageEl.OriginHeight = this.imageEl.naturalHeight || this.imageEl.height;
436
437         if(this.fireEvent('loadcanvas', this, this.imageEl) != false){
438         
439             this.bodyEl.un('click', this.beforeSelectFile, this);
440             
441             this.notifyEl.hide();
442             this.thumbEl.show();
443             this.footerEl.show();
444             
445             this.baseRotateLevel();
446             
447             if(this.isDocument){
448                 this.setThumbBoxSize();
449             }
450             
451             this.setThumbBoxPosition();
452             
453             this.baseScaleLevel();
454             
455             this.draw();
456             
457             this.resize();
458             
459             this.canvasLoaded = true;
460         
461         }
462         
463         if(this.loadMask){
464             this.maskEl.unmask();
465         }
466         
467     },
468     
469     setCanvasPosition : function()
470     {   
471         if(!this.canvasEl){
472             return;
473         }
474         
475         var pw = Math.ceil((this.bodyEl.getWidth() - this.canvasEl.width) / 2);
476         var ph = Math.ceil((this.bodyEl.getHeight() - this.canvasEl.height) / 2);
477         
478         this.previewEl.setLeft(pw);
479         this.previewEl.setTop(ph);
480         
481     },
482     
483     onMouseDown : function(e)
484     {   
485         e.stopEvent();
486         
487         this.dragable = true;
488         this.pinching = false;
489         
490         if(this.isDocument && (this.canvasEl.width < this.thumbEl.getWidth() || this.canvasEl.height < this.thumbEl.getHeight())){
491             this.dragable = false;
492             return;
493         }
494         
495         this.mouseX = Roo.isTouch ? e.browserEvent.touches[0].pageX : e.getPageX();
496         this.mouseY = Roo.isTouch ? e.browserEvent.touches[0].pageY : e.getPageY();
497         
498     },
499     
500     onMouseMove : function(e)
501     {   
502         e.stopEvent();
503         
504         if(!this.canvasLoaded){
505             return;
506         }
507         
508         if (!this.dragable){
509             return;
510         }
511         
512         var minX = Math.ceil(this.thumbEl.getLeft(true));
513         var minY = Math.ceil(this.thumbEl.getTop(true));
514         
515         var maxX = Math.ceil(minX + this.thumbEl.getWidth() - this.canvasEl.width);
516         var maxY = Math.ceil(minY + this.thumbEl.getHeight() - this.canvasEl.height);
517
518         if(minX > maxX) {
519             var tempX = minX;
520             minX = maxX;
521             maxX = tempX;
522         }
523
524         if(minY > maxY) {
525             var tempY = minY;
526             minY = maxY;
527             maxY = tempY;
528         }
529
530         var x = Roo.isTouch ? e.browserEvent.touches[0].pageX : e.getPageX();
531         var y = Roo.isTouch ? e.browserEvent.touches[0].pageY : e.getPageY();
532         
533         x = x - this.mouseX;
534         y = y - this.mouseY;
535
536         var bgX = Math.ceil(x + this.previewEl.getLeft(true));
537         var bgY = Math.ceil(y + this.previewEl.getTop(true));
538         
539         bgX = (bgX < minX) ? minX : ((bgX > maxX) ? maxX : bgX);
540         bgY = (bgY < minY) ? minY : ((bgY > maxY) ? maxY : bgY);
541         
542         this.previewEl.setLeft(bgX);
543         this.previewEl.setTop(bgY);
544         
545         this.mouseX = Roo.isTouch ? e.browserEvent.touches[0].pageX : e.getPageX();
546         this.mouseY = Roo.isTouch ? e.browserEvent.touches[0].pageY : e.getPageY();
547     },
548     
549     onMouseUp : function(e)
550     {   
551         e.stopEvent();
552         
553         this.dragable = false;
554     },
555     
556     onMouseWheel : function(e)
557     {   
558         e.stopEvent();
559         
560         this.startScale = this.scale;
561         this.scale = (e.getWheelDelta() == 1) ? (this.scale + 1) : (this.scale - 1);
562         
563         console.log('startScale: ' . this.startScale);
564         console.log('scale: ' . this.scale);
565         console.log('getWheelDelta: ' . e.getWheelDelta());
566         if(!this.zoomable()){
567             this.scale = this.startScale;
568             return;
569         }
570
571         
572         this.draw();
573         
574         return;
575     },
576     
577     zoomable : function()
578     {
579         var minScale = this.thumbEl.getWidth() / this.minWidth;
580         
581         if(this.minWidth < this.minHeight){
582             minScale = this.thumbEl.getHeight() / this.minHeight;
583         }
584         
585         var width = Math.ceil(this.imageEl.OriginWidth * this.getScaleLevel() / minScale);
586         var height = Math.ceil(this.imageEl.OriginHeight * this.getScaleLevel() / minScale);
587
588
589         var maxWidth = this.imageEl.OriginWidth;
590         var maxHeight = this.imageEl.OriginHeight;
591         
592         if(
593                 this.isDocument &&
594                 (this.rotate == 0 || this.rotate == 180) && 
595                 (
596                     width > this.imageEl.OriginWidth || 
597                     height > this.imageEl.OriginHeight ||
598                     (width < this.minWidth && height < this.minHeight)
599                 )
600         ){
601             return false;
602         }
603         
604         if(
605                 this.isDocument &&
606                 (this.rotate == 90 || this.rotate == 270) && 
607                 (
608                     width > this.imageEl.OriginWidth || 
609                     height > this.imageEl.OriginHeight ||
610                     (width < this.minHeight && height < this.minWidth)
611                 )
612         ){
613             return false;
614         }
615         
616         if(
617                 !this.isDocument &&
618                 (this.rotate == 0 || this.rotate == 180) && 
619                 (
620                     (this.imageEl.OriginWidth >= this.minWidth) && width < this.minWidth ||
621                     (this.imageEl.OriginHeight >= this.minHeight) && height < this.minHeight ||
622                     width > maxWidth ||
623                     height > maxHeight
624                 )
625         ){
626             return false;
627         }
628         
629         if(
630                 !this.isDocument &&
631                 (this.rotate == 90 || this.rotate == 270) && 
632                 (
633                     width < this.minHeight || 
634                     width > this.imageEl.OriginWidth || 
635                     height < this.minWidth || 
636                     height > this.imageEl.OriginHeight
637                 )
638         ){
639             return false;
640         }
641         
642         return true;
643         
644     },
645     
646     onRotateLeft : function(e)
647     {   
648         if(!this.isDocument && (this.canvasEl.height < this.thumbEl.getWidth() || this.canvasEl.width < this.thumbEl.getHeight())){
649             
650             var minScale = this.thumbEl.getWidth() / this.minWidth;
651             
652             var bw = Math.ceil(this.canvasEl.width / this.getScaleLevel());
653             var bh = Math.ceil(this.canvasEl.height / this.getScaleLevel());
654             
655             this.startScale = this.scale;
656             
657             while (this.getScaleLevel() < minScale){
658             
659                 this.scale = this.scale + 1;
660                 
661                 if(!this.zoomable()){
662                     break;
663                 }
664                 
665                 if(
666                         Math.ceil(bw * this.getScaleLevel()) < this.thumbEl.getHeight() ||
667                         Math.ceil(bh * this.getScaleLevel()) < this.thumbEl.getWidth()
668                 ){
669                     continue;
670                 }
671                 
672                 this.rotate = (this.rotate < 90) ? 270 : this.rotate - 90;
673
674                 this.draw();
675                 
676                 return;
677             }
678             
679             this.scale = this.startScale;
680             
681             this.onRotateFail();
682             
683             return false;
684         }
685         
686         this.rotate = (this.rotate < 90) ? 270 : this.rotate - 90;
687
688         if(this.isDocument){
689             this.setThumbBoxSize();
690             this.setThumbBoxPosition();
691             this.setCanvasPosition();
692         }
693         
694         this.draw();
695         
696         this.fireEvent('rotate', this, 'left');
697         
698     },
699     
700     onRotateRight : function(e)
701     {
702         if(!this.isDocument && (this.canvasEl.height < this.thumbEl.getWidth() || this.canvasEl.width < this.thumbEl.getHeight())){
703             
704             var minScale = this.thumbEl.getWidth() / this.minWidth;
705         
706             var bw = Math.ceil(this.canvasEl.width / this.getScaleLevel());
707             var bh = Math.ceil(this.canvasEl.height / this.getScaleLevel());
708             
709             this.startScale = this.scale;
710             
711             while (this.getScaleLevel() < minScale){
712             
713                 this.scale = this.scale + 1;
714                 
715                 if(!this.zoomable()){
716                     break;
717                 }
718                 
719                 if(
720                         Math.ceil(bw * this.getScaleLevel()) < this.thumbEl.getHeight() ||
721                         Math.ceil(bh * this.getScaleLevel()) < this.thumbEl.getWidth()
722                 ){
723                     continue;
724                 }
725                 
726                 this.rotate = (this.rotate > 180) ? 0 : this.rotate + 90;
727
728                 this.draw();
729                 
730                 return;
731             }
732             
733             this.scale = this.startScale;
734             
735             this.onRotateFail();
736             
737             return false;
738         }
739         
740         this.rotate = (this.rotate > 180) ? 0 : this.rotate + 90;
741
742         if(this.isDocument){
743             this.setThumbBoxSize();
744             this.setThumbBoxPosition();
745             this.setCanvasPosition();
746         }
747         
748         this.draw();
749         
750         this.fireEvent('rotate', this, 'right');
751     },
752     
753     onRotateFail : function()
754     {
755         this.errorEl.show(true);
756         
757         var _this = this;
758         
759         (function() { _this.errorEl.hide(true); }).defer(this.errorTimeout);
760     },
761     
762     draw : function()
763     {
764         this.previewEl.dom.innerHTML = '';
765         
766         var canvasEl = document.createElement("canvas");
767         
768         var contextEl = canvasEl.getContext("2d");
769         
770         canvasEl.width = this.imageEl.OriginWidth * this.getScaleLevel();
771         canvasEl.height = this.imageEl.OriginWidth * this.getScaleLevel();
772         var center = this.imageEl.OriginWidth / 2;
773         
774         if(this.imageEl.OriginWidth < this.imageEl.OriginHeight){
775             canvasEl.width = this.imageEl.OriginHeight * this.getScaleLevel();
776             canvasEl.height = this.imageEl.OriginHeight * this.getScaleLevel();
777             center = this.imageEl.OriginHeight / 2;
778         }
779         
780         contextEl.scale(this.getScaleLevel(), this.getScaleLevel());
781         
782         contextEl.translate(center, center);
783         contextEl.rotate(this.rotate * Math.PI / 180);
784
785         contextEl.drawImage(this.imageEl, 0, 0, this.imageEl.OriginWidth, this.imageEl.OriginHeight, center * -1, center * -1, this.imageEl.OriginWidth, this.imageEl.OriginHeight);
786         
787         this.canvasEl = document.createElement("canvas");
788         
789         this.contextEl = this.canvasEl.getContext("2d");
790         
791         switch (this.rotate) {
792             case 0 :
793                 
794                 this.canvasEl.width = this.imageEl.OriginWidth * this.getScaleLevel();
795                 this.canvasEl.height = this.imageEl.OriginHeight * this.getScaleLevel();
796                 
797                 this.contextEl.drawImage(canvasEl, 0, 0, this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
798                 
799                 break;
800             case 90 : 
801                 
802                 this.canvasEl.width = this.imageEl.OriginHeight * this.getScaleLevel();
803                 this.canvasEl.height = this.imageEl.OriginWidth * this.getScaleLevel();
804                 
805                 if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
806                     this.contextEl.drawImage(canvasEl, Math.abs(this.canvasEl.width - this.canvasEl.height), 0, this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
807                     break;
808                 }
809                 
810                 this.contextEl.drawImage(canvasEl, 0, 0, this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
811                 
812                 break;
813             case 180 :
814                 
815                 this.canvasEl.width = this.imageEl.OriginWidth * this.getScaleLevel();
816                 this.canvasEl.height = this.imageEl.OriginHeight * this.getScaleLevel();
817                 
818                 if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
819                     this.contextEl.drawImage(canvasEl, 0, Math.abs(this.canvasEl.width - this.canvasEl.height), this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
820                     break;
821                 }
822                 
823                 this.contextEl.drawImage(canvasEl, Math.abs(this.canvasEl.width - this.canvasEl.height), 0, this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
824                 
825                 break;
826             case 270 :
827                 
828                 this.canvasEl.width = this.imageEl.OriginHeight * this.getScaleLevel();
829                 this.canvasEl.height = this.imageEl.OriginWidth * this.getScaleLevel();
830         
831                 if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
832                     this.contextEl.drawImage(canvasEl, 0, 0, this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
833                     break;
834                 }
835                 
836                 this.contextEl.drawImage(canvasEl, 0, Math.abs(this.canvasEl.width - this.canvasEl.height), this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
837                 
838                 break;
839             default : 
840                 break;
841         }
842         
843         this.previewEl.appendChild(this.canvasEl);
844         
845         this.setCanvasPosition();
846     },
847     
848     crop : function()
849     {
850         if(!this.canvasLoaded){
851             return;
852         }
853         
854         var imageCanvas = document.createElement("canvas");
855         
856         var imageContext = imageCanvas.getContext("2d");
857         
858         imageCanvas.width = (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? this.imageEl.OriginWidth : this.imageEl.OriginHeight;
859         imageCanvas.height = (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? this.imageEl.OriginWidth : this.imageEl.OriginHeight;
860         
861         var center = imageCanvas.width / 2;
862         
863         imageContext.translate(center, center);
864         
865         imageContext.rotate(this.rotate * Math.PI / 180);
866         
867         imageContext.drawImage(this.imageEl, 0, 0, this.imageEl.OriginWidth, this.imageEl.OriginHeight, center * -1, center * -1, this.imageEl.OriginWidth, this.imageEl.OriginHeight);
868         
869         var canvas = document.createElement("canvas");
870         
871         var context = canvas.getContext("2d");
872
873         canvas.width = this.thumbEl.getWidth() / this.getScaleLevel();
874         
875         canvas.height = this.thumbEl.getHeight() / this.getScaleLevel();
876
877         switch (this.rotate) {
878             case 0 :
879                 
880                 var width = (this.thumbEl.getWidth() / this.getScaleLevel() > this.imageEl.OriginWidth) ? this.imageEl.OriginWidth : (this.thumbEl.getWidth() / this.getScaleLevel());
881                 var height = (this.thumbEl.getHeight() / this.getScaleLevel() > this.imageEl.OriginHeight) ? this.imageEl.OriginHeight : (this.thumbEl.getHeight() / this.getScaleLevel());
882                 
883                 var x = (this.thumbEl.getLeft(true) > this.previewEl.getLeft(true)) ? 0 : ((this.previewEl.getLeft(true) - this.thumbEl.getLeft(true)) / this.getScaleLevel());
884                 var y = (this.thumbEl.getTop(true) > this.previewEl.getTop(true)) ? 0 : ((this.previewEl.getTop(true) - this.thumbEl.getTop(true)) / this.getScaleLevel());
885                 
886                 var sx = this.thumbEl.getLeft(true) - this.previewEl.getLeft(true);
887                 var sy = this.thumbEl.getTop(true) - this.previewEl.getTop(true);
888
889                 sx = sx < 0 ? 0 : (sx / this.getScaleLevel());
890                 sy = sy < 0 ? 0 : (sy / this.getScaleLevel());
891
892                 if(canvas.width > this.outputMaxWidth) {
893                     var scale = this.outputMaxWidth / canvas.width;
894                     canvas.width = canvas.width * scale;
895                     canvas.height = canvas.height * scale;
896                     context.scale(scale, scale);
897                 }
898
899                 context.drawImage(imageCanvas, sx, sy, width, height, x, y, width, height);
900                 
901                 break;
902             case 90 : 
903                 
904                 var width = (this.thumbEl.getWidth() / this.getScaleLevel() > this.imageEl.OriginHeight) ? this.imageEl.OriginHeight : (this.thumbEl.getWidth() / this.getScaleLevel());
905                 var height = (this.thumbEl.getHeight() / this.getScaleLevel() > this.imageEl.OriginWidth) ? this.imageEl.OriginWidth : (this.thumbEl.getHeight() / this.getScaleLevel());
906                 
907                 var x = (this.thumbEl.getLeft(true) > this.previewEl.getLeft(true)) ? 0 : ((this.previewEl.getLeft(true) - this.thumbEl.getLeft(true)) / this.getScaleLevel());
908                 var y = (this.thumbEl.getTop(true) > this.previewEl.getTop(true)) ? 0 : ((this.previewEl.getTop(true) - this.thumbEl.getTop(true)) / this.getScaleLevel());
909                 
910                 var targetWidth = this.minWidth - 2 * x;
911                 var targetHeight = this.minHeight - 2 * y;
912                 
913                 var scale = 1;
914                 
915                 if((x == 0 && y == 0) || (x == 0 && y > 0)){
916                     scale = targetWidth / width;
917                 }
918                 
919                 if(x > 0 && y == 0){
920                     scale = targetHeight / height;
921                 }
922                 
923                 if(x > 0 && y > 0){
924                     scale = targetWidth / width;
925                     
926                     if(width < height){
927                         scale = targetHeight / height;
928                     }
929                 }
930                 
931                 context.scale(scale, scale);
932                 
933                 var sx = Math.min(this.canvasEl.width - this.thumbEl.getWidth(), this.thumbEl.getLeft(true) - this.previewEl.getLeft(true));
934                 var sy = Math.min(this.canvasEl.height - this.thumbEl.getHeight(), this.thumbEl.getTop(true) - this.previewEl.getTop(true));
935
936                 sx = sx < 0 ? 0 : (sx / this.getScaleLevel());
937                 sy = sy < 0 ? 0 : (sy / this.getScaleLevel());
938                 
939                 sx += (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? Math.abs(this.imageEl.OriginWidth - this.imageEl.OriginHeight) : 0;
940                 
941                 context.drawImage(imageCanvas, sx, sy, width, height, x, y, width, height);
942                 
943                 break;
944             case 180 :
945                 
946                 var width = (this.thumbEl.getWidth() / this.getScaleLevel() > this.imageEl.OriginWidth) ? this.imageEl.OriginWidth : (this.thumbEl.getWidth() / this.getScaleLevel());
947                 var height = (this.thumbEl.getHeight() / this.getScaleLevel() > this.imageEl.OriginHeight) ? this.imageEl.OriginHeight : (this.thumbEl.getHeight() / this.getScaleLevel());
948                 
949                 var x = (this.thumbEl.getLeft(true) > this.previewEl.getLeft(true)) ? 0 : ((this.previewEl.getLeft(true) - this.thumbEl.getLeft(true)) / this.getScaleLevel());
950                 var y = (this.thumbEl.getTop(true) > this.previewEl.getTop(true)) ? 0 : ((this.previewEl.getTop(true) - this.thumbEl.getTop(true)) / this.getScaleLevel());
951                 
952                 var targetWidth = this.minWidth - 2 * x;
953                 var targetHeight = this.minHeight - 2 * y;
954                 
955                 var scale = 1;
956                 
957                 if((x == 0 && y == 0) || (x == 0 && y > 0)){
958                     scale = targetWidth / width;
959                 }
960                 
961                 if(x > 0 && y == 0){
962                     scale = targetHeight / height;
963                 }
964                 
965                 if(x > 0 && y > 0){
966                     scale = targetWidth / width;
967                     
968                     if(width < height){
969                         scale = targetHeight / height;
970                     }
971                 }
972                 
973                 context.scale(scale, scale);
974                 
975                 var sx = Math.min(this.canvasEl.width - this.thumbEl.getWidth(), this.thumbEl.getLeft(true) - this.previewEl.getLeft(true));
976                 var sy = Math.min(this.canvasEl.height - this.thumbEl.getHeight(), this.thumbEl.getTop(true) - this.previewEl.getTop(true));
977
978                 sx = sx < 0 ? 0 : (sx / this.getScaleLevel());
979                 sy = sy < 0 ? 0 : (sy / this.getScaleLevel());
980
981                 sx += (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? 0 : Math.abs(this.imageEl.OriginWidth - this.imageEl.OriginHeight);
982                 sy += (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? Math.abs(this.imageEl.OriginWidth - this.imageEl.OriginHeight) : 0;
983                 
984                 context.drawImage(imageCanvas, sx, sy, width, height, x, y, width, height);
985                 
986                 break;
987             case 270 :
988                 
989                 var width = (this.thumbEl.getWidth() / this.getScaleLevel() > this.imageEl.OriginHeight) ? this.imageEl.OriginHeight : (this.thumbEl.getWidth() / this.getScaleLevel());
990                 var height = (this.thumbEl.getHeight() / this.getScaleLevel() > this.imageEl.OriginWidth) ? this.imageEl.OriginWidth : (this.thumbEl.getHeight() / this.getScaleLevel());
991                 
992                 var x = (this.thumbEl.getLeft(true) > this.previewEl.getLeft(true)) ? 0 : ((this.previewEl.getLeft(true) - this.thumbEl.getLeft(true)) / this.getScaleLevel());
993                 var y = (this.thumbEl.getTop(true) > this.previewEl.getTop(true)) ? 0 : ((this.previewEl.getTop(true) - this.thumbEl.getTop(true)) / this.getScaleLevel());
994                 
995                 var targetWidth = this.minWidth - 2 * x;
996                 var targetHeight = this.minHeight - 2 * y;
997                 
998                 var scale = 1;
999                 
1000                 if((x == 0 && y == 0) || (x == 0 && y > 0)){
1001                     scale = targetWidth / width;
1002                 }
1003                 
1004                 if(x > 0 && y == 0){
1005                     scale = targetHeight / height;
1006                 }
1007                 
1008                 if(x > 0 && y > 0){
1009                     scale = targetWidth / width;
1010                     
1011                     if(width < height){
1012                         scale = targetHeight / height;
1013                     }
1014                 }
1015                 
1016                 context.scale(scale, scale);
1017                 var sx = Math.min(this.canvasEl.width - this.thumbEl.getWidth(), this.thumbEl.getLeft(true) - this.previewEl.getLeft(true));
1018                 var sy = Math.min(this.canvasEl.height - this.thumbEl.getHeight(), this.thumbEl.getTop(true) - this.previewEl.getTop(true));
1019
1020                 sx = sx < 0 ? 0 : (sx / this.getScaleLevel());
1021                 sy = sy < 0 ? 0 : (sy / this.getScaleLevel());
1022                 
1023                 sy += (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? 0 : Math.abs(this.imageEl.OriginWidth - this.imageEl.OriginHeight);
1024                 
1025                 context.drawImage(imageCanvas, sx, sy, width, height, x, y, width, height);
1026                 
1027                 break;
1028             default : 
1029                 break;
1030         }
1031         
1032         this.cropData = canvas.toDataURL(this.cropType);
1033         
1034         if(this.fireEvent('crop', this, this.cropData) !== false){
1035             this.process(this.file, this.cropData);
1036         }
1037         
1038         return;
1039         
1040     },
1041     
1042     setThumbBoxSize : function()
1043     {
1044         var width, height;
1045         
1046         if(this.isDocument && typeof(this.imageEl) != 'undefined'){
1047             width = (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? Math.max(this.minWidth, this.minHeight) : Math.min(this.minWidth, this.minHeight);
1048             height = (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? Math.min(this.minWidth, this.minHeight) : Math.max(this.minWidth, this.minHeight);
1049             
1050             this.minWidth = width;
1051             this.minHeight = height;
1052             
1053             if(this.rotate == 90 || this.rotate == 270){
1054                 this.minWidth = height;
1055                 this.minHeight = width;
1056             }
1057         }
1058         
1059         height = 500;
1060         width = Math.ceil(this.minWidth * height / this.minHeight);
1061         
1062         if(this.minWidth > this.minHeight){
1063             width = 500;
1064             height = Math.ceil(this.minHeight * width / this.minWidth);
1065         }
1066         
1067         this.thumbEl.setStyle({
1068             width : width + 'px',
1069             height : height + 'px'
1070         });
1071
1072         return;
1073             
1074     },
1075     
1076     setThumbBoxPosition : function()
1077     {
1078         var x = Math.ceil((this.bodyEl.getWidth() - this.thumbEl.getWidth()) / 2 );
1079         var y = Math.ceil((this.bodyEl.getHeight() - this.thumbEl.getHeight()) / 2);
1080         
1081         this.thumbEl.setLeft(x);
1082         this.thumbEl.setTop(y);
1083         
1084     },
1085     
1086     baseRotateLevel : function()
1087     {
1088         this.baseRotate = 1;
1089         
1090         if(
1091                 typeof(this.exif) != 'undefined' &&
1092                 typeof(this.exif[Roo.dialog.UploadCropbox['tags']['Orientation']]) != 'undefined' &&
1093                 [1, 3, 6, 8].indexOf(this.exif[Roo.dialog.UploadCropbox['tags']['Orientation']]) != -1
1094         ){
1095             this.baseRotate = this.exif[Roo.dialog.UploadCropbox['tags']['Orientation']];
1096         }
1097         
1098         this.rotate = Roo.dialog.UploadCropbox['Orientation'][this.baseRotate];
1099         
1100     },
1101     
1102     baseScaleLevel : function()
1103     {
1104         var width, height;
1105         
1106         if(this.isDocument){
1107             
1108             if(this.baseRotate == 6 || this.baseRotate == 8){
1109             
1110                 height = this.thumbEl.getHeight();
1111                 this.baseScale = height / this.imageEl.OriginWidth;
1112
1113                 if(this.imageEl.OriginHeight * this.baseScale > this.thumbEl.getWidth()){
1114                     width = this.thumbEl.getWidth();
1115                     this.baseScale = width / this.imageEl.OriginHeight;
1116                 }
1117
1118                 return;
1119             }
1120
1121             height = this.thumbEl.getHeight();
1122             this.baseScale = height / this.imageEl.OriginHeight;
1123
1124             if(this.imageEl.OriginWidth * this.baseScale > this.thumbEl.getWidth()){
1125                 width = this.thumbEl.getWidth();
1126                 this.baseScale = width / this.imageEl.OriginWidth;
1127             }
1128
1129             return;
1130         }
1131         
1132         if(this.baseRotate == 6 || this.baseRotate == 8){
1133             
1134             width = this.thumbEl.getHeight();
1135             this.baseScale = width / this.imageEl.OriginHeight;
1136             
1137             if(this.imageEl.OriginHeight * this.baseScale < this.thumbEl.getWidth()){
1138                 height = this.thumbEl.getWidth();
1139                 this.baseScale = height / this.imageEl.OriginHeight;
1140             }
1141             
1142             if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
1143                 height = this.thumbEl.getWidth();
1144                 this.baseScale = height / this.imageEl.OriginHeight;
1145                 
1146                 if(this.imageEl.OriginWidth * this.baseScale < this.thumbEl.getHeight()){
1147                     width = this.thumbEl.getHeight();
1148                     this.baseScale = width / this.imageEl.OriginWidth;
1149                 }
1150             }
1151             
1152             return;
1153         }
1154         
1155         width = this.thumbEl.getWidth();
1156         this.baseScale = width / this.imageEl.OriginWidth;
1157         
1158         if(this.imageEl.OriginHeight * this.baseScale < this.thumbEl.getHeight()){
1159             height = this.thumbEl.getHeight();
1160             this.baseScale = height / this.imageEl.OriginHeight;
1161         }
1162         
1163         if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
1164             
1165             height = this.thumbEl.getHeight();
1166             this.baseScale = height / this.imageEl.OriginHeight;
1167             
1168             if(this.imageEl.OriginWidth * this.baseScale < this.thumbEl.getWidth()){
1169                 width = this.thumbEl.getWidth();
1170                 this.baseScale = width / this.imageEl.OriginWidth;
1171             }
1172             
1173         }
1174
1175         if(this.imageEl.OriginWidth < this.minWidth || this.imageEl.OriginHeight < this.minHeight) {
1176             this.baseScale = width / this.minWidth;
1177         }
1178
1179         return;
1180     },
1181     
1182     getScaleLevel : function()
1183     {
1184         return this.baseScale * Math.pow(1.02, this.scale);
1185     },
1186     
1187     onTouchStart : function(e)
1188     {
1189         if(!this.canvasLoaded){
1190             this.beforeSelectFile(e);
1191             return;
1192         }
1193         
1194         var touches = e.browserEvent.touches;
1195         
1196         if(!touches){
1197             return;
1198         }
1199         
1200         if(touches.length == 1){
1201             this.onMouseDown(e);
1202             return;
1203         }
1204         
1205         if(touches.length != 2){
1206             return;
1207         }
1208         
1209         var coords = [];
1210         
1211         for(var i = 0, finger; finger = touches[i]; i++){
1212             coords.push(finger.pageX, finger.pageY);
1213         }
1214         
1215         var x = Math.pow(coords[0] - coords[2], 2);
1216         var y = Math.pow(coords[1] - coords[3], 2);
1217         
1218         this.startDistance = Math.sqrt(x + y);
1219         
1220         this.startScale = this.scale;
1221         
1222         this.pinching = true;
1223         this.dragable = false;
1224         
1225     },
1226     
1227     onTouchMove : function(e)
1228     {
1229         if(!this.pinching && !this.dragable){
1230             return;
1231         }
1232         
1233         var touches = e.browserEvent.touches;
1234         
1235         if(!touches){
1236             return;
1237         }
1238         
1239         if(this.dragable){
1240             this.onMouseMove(e);
1241             return;
1242         }
1243         
1244         var coords = [];
1245         
1246         for(var i = 0, finger; finger = touches[i]; i++){
1247             coords.push(finger.pageX, finger.pageY);
1248         }
1249         
1250         var x = Math.pow(coords[0] - coords[2], 2);
1251         var y = Math.pow(coords[1] - coords[3], 2);
1252         
1253         this.endDistance = Math.sqrt(x + y);
1254         
1255         this.scale = this.startScale + Math.floor(Math.log(this.endDistance / this.startDistance) / Math.log(1.1));
1256         
1257         if(!this.zoomable()){
1258             this.scale = this.startScale;
1259             return;
1260         }
1261         
1262         this.draw();
1263         
1264     },
1265     
1266     onTouchEnd : function(e)
1267     {
1268         this.pinching = false;
1269         this.dragable = false;
1270         
1271     },
1272     
1273     process : function(file, crop)
1274     {
1275         if(this.loadMask){
1276             this.maskEl.mask(this.loadingText);
1277         }
1278         
1279         this.xhr = new XMLHttpRequest();
1280         
1281         file.xhr = this.xhr;
1282
1283         this.xhr.open(this.method, this.url, true);
1284         
1285         var headers = {
1286             "Accept": "application/json",
1287             "Cache-Control": "no-cache",
1288             "X-Requested-With": "XMLHttpRequest"
1289         };
1290         
1291         for (var headerName in headers) {
1292             var headerValue = headers[headerName];
1293             if (headerValue) {
1294                 this.xhr.setRequestHeader(headerName, headerValue);
1295             }
1296         }
1297         
1298         var _this = this;
1299         
1300         this.xhr.onload = function()
1301         {
1302             _this.xhrOnLoad(_this.xhr);
1303         }
1304         
1305         this.xhr.onerror = function()
1306         {
1307             _this.xhrOnError(_this.xhr);
1308         }
1309         
1310         var formData = new FormData();
1311
1312         formData.append('returnHTML', 'NO');
1313
1314         if(crop){
1315             formData.append('crop', crop);
1316             var blobBin = atob(crop.split(',')[1]);
1317             var array = [];
1318             for(var i = 0; i < blobBin.length; i++) {
1319                 array.push(blobBin.charCodeAt(i));
1320             }
1321             var croppedFile =new Blob([new Uint8Array(array)], {type: this.cropType});
1322             formData.append(this.paramName, croppedFile, file.name);
1323         }
1324         
1325         if(typeof(file.filename) != 'undefined'){
1326             formData.append('filename', file.filename);
1327         }
1328         
1329         if(typeof(file.mimetype) != 'undefined'){
1330             formData.append('mimetype', file.mimetype);
1331         }
1332
1333         if(this.fireEvent('arrange', this, formData) != false){
1334             this.xhr.send(formData);
1335         };
1336     },
1337     
1338     xhrOnLoad : function(xhr)
1339     {
1340         if(this.loadMask){
1341             this.maskEl.unmask();
1342         }
1343         
1344         if (xhr.readyState !== 4) {
1345             this.fireEvent('exception', this, xhr);
1346             return;
1347         }
1348
1349         var response = Roo.decode(xhr.responseText);
1350         
1351         if(!response.success){
1352             this.fireEvent('exception', this, xhr);
1353             return;
1354         }
1355         
1356         var response = Roo.decode(xhr.responseText);
1357         
1358         this.fireEvent('upload', this, response);
1359         
1360     },
1361     
1362     xhrOnError : function()
1363     {
1364         if(this.loadMask){
1365             this.maskEl.unmask();
1366         }
1367         
1368         Roo.log('xhr on error');
1369         
1370         var response = Roo.decode(xhr.responseText);
1371           
1372         Roo.log(response);
1373         
1374     },
1375     
1376     prepare : function(file)
1377     {   
1378         if(this.loadMask){
1379             this.maskEl.mask(this.loadingText);
1380         }
1381         
1382         this.file = false;
1383         this.exif = {};
1384         
1385         if(typeof(file) === 'string'){
1386             this.loadCanvas(file);
1387             return;
1388         }
1389         
1390         if(!file || !this.urlAPI){
1391             return;
1392         }
1393         
1394         this.file = file;
1395         if(typeof(file.type) != 'undefined' && file.type.length != 0) {
1396             this.cropType = file.type;
1397         }
1398         
1399         var _this = this;
1400         
1401         if(this.fireEvent('prepare', this, this.file) != false){
1402             
1403             var reader = new FileReader();
1404             
1405             reader.onload = function (e) {
1406                 if (e.target.error) {
1407                     Roo.log(e.target.error);
1408                     return;
1409                 }
1410                 
1411                 var buffer = e.target.result,
1412                     dataView = new DataView(buffer),
1413                     offset = 2,
1414                     maxOffset = dataView.byteLength - 4,
1415                     markerBytes,
1416                     markerLength;
1417                 
1418                 if (dataView.getUint16(0) === 0xffd8) {
1419                     while (offset < maxOffset) {
1420                         markerBytes = dataView.getUint16(offset);
1421                         
1422                         if ((markerBytes >= 0xffe0 && markerBytes <= 0xffef) || markerBytes === 0xfffe) {
1423                             markerLength = dataView.getUint16(offset + 2) + 2;
1424                             if (offset + markerLength > dataView.byteLength) {
1425                                 Roo.log('Invalid meta data: Invalid segment size.');
1426                                 break;
1427                             }
1428                             
1429                             if(markerBytes == 0xffe1){
1430                                 _this.parseExifData(
1431                                     dataView,
1432                                     offset,
1433                                     markerLength
1434                                 );
1435                             }
1436                             
1437                             offset += markerLength;
1438                             
1439                             continue;
1440                         }
1441                         
1442                         break;
1443                     }
1444                     
1445                 }
1446                 
1447                 var url = _this.urlAPI.createObjectURL(_this.file);
1448                 
1449                 _this.loadCanvas(url);
1450                 
1451                 return;
1452             }
1453             
1454             reader.readAsArrayBuffer(this.file);
1455             
1456         }
1457         
1458     },
1459     
1460     parseExifData : function(dataView, offset, length)
1461     {
1462         var tiffOffset = offset + 10,
1463             littleEndian,
1464             dirOffset;
1465     
1466         if (dataView.getUint32(offset + 4) !== 0x45786966) {
1467             // No Exif data, might be XMP data instead
1468             return;
1469         }
1470         
1471         // Check for the ASCII code for "Exif" (0x45786966):
1472         if (dataView.getUint32(offset + 4) !== 0x45786966) {
1473             // No Exif data, might be XMP data instead
1474             return;
1475         }
1476         if (tiffOffset + 8 > dataView.byteLength) {
1477             Roo.log('Invalid Exif data: Invalid segment size.');
1478             return;
1479         }
1480         // Check for the two null bytes:
1481         if (dataView.getUint16(offset + 8) !== 0x0000) {
1482             Roo.log('Invalid Exif data: Missing byte alignment offset.');
1483             return;
1484         }
1485         // Check the byte alignment:
1486         switch (dataView.getUint16(tiffOffset)) {
1487         case 0x4949:
1488             littleEndian = true;
1489             break;
1490         case 0x4D4D:
1491             littleEndian = false;
1492             break;
1493         default:
1494             Roo.log('Invalid Exif data: Invalid byte alignment marker.');
1495             return;
1496         }
1497         // Check for the TIFF tag marker (0x002A):
1498         if (dataView.getUint16(tiffOffset + 2, littleEndian) !== 0x002A) {
1499             Roo.log('Invalid Exif data: Missing TIFF marker.');
1500             return;
1501         }
1502         // Retrieve the directory offset bytes, usually 0x00000008 or 8 decimal:
1503         dirOffset = dataView.getUint32(tiffOffset + 4, littleEndian);
1504         
1505         this.parseExifTags(
1506             dataView,
1507             tiffOffset,
1508             tiffOffset + dirOffset,
1509             littleEndian
1510         );
1511     },
1512     
1513     parseExifTags : function(dataView, tiffOffset, dirOffset, littleEndian)
1514     {
1515         var tagsNumber,
1516             dirEndOffset,
1517             i;
1518         if (dirOffset + 6 > dataView.byteLength) {
1519             Roo.log('Invalid Exif data: Invalid directory offset.');
1520             return;
1521         }
1522         tagsNumber = dataView.getUint16(dirOffset, littleEndian);
1523         dirEndOffset = dirOffset + 2 + 12 * tagsNumber;
1524         if (dirEndOffset + 4 > dataView.byteLength) {
1525             Roo.log('Invalid Exif data: Invalid directory size.');
1526             return;
1527         }
1528         for (i = 0; i < tagsNumber; i += 1) {
1529             this.parseExifTag(
1530                 dataView,
1531                 tiffOffset,
1532                 dirOffset + 2 + 12 * i, // tag offset
1533                 littleEndian
1534             );
1535         }
1536         // Return the offset to the next directory:
1537         return dataView.getUint32(dirEndOffset, littleEndian);
1538     },
1539     
1540     parseExifTag : function (dataView, tiffOffset, offset, littleEndian) 
1541     {
1542         var tag = dataView.getUint16(offset, littleEndian);
1543         
1544         this.exif[tag] = this.getExifValue(
1545             dataView,
1546             tiffOffset,
1547             offset,
1548             dataView.getUint16(offset + 2, littleEndian), // tag type
1549             dataView.getUint32(offset + 4, littleEndian), // tag length
1550             littleEndian
1551         );
1552     },
1553     
1554     getExifValue : function (dataView, tiffOffset, offset, type, length, littleEndian)
1555     {
1556         var tagType = Roo.dialog.UploadCropbox.exifTagTypes[type],
1557             tagSize,
1558             dataOffset,
1559             values,
1560             i,
1561             str,
1562             c;
1563     
1564         if (!tagType) {
1565             Roo.log('Invalid Exif data: Invalid tag type.');
1566             return;
1567         }
1568         
1569         tagSize = tagType.size * length;
1570         // Determine if the value is contained in the dataOffset bytes,
1571         // or if the value at the dataOffset is a pointer to the actual data:
1572         dataOffset = tagSize > 4 ?
1573                 tiffOffset + dataView.getUint32(offset + 8, littleEndian) : (offset + 8);
1574         if (dataOffset + tagSize > dataView.byteLength) {
1575             Roo.log('Invalid Exif data: Invalid data offset.');
1576             return;
1577         }
1578         if (length === 1) {
1579             return tagType.getValue(dataView, dataOffset, littleEndian);
1580         }
1581         values = [];
1582         for (i = 0; i < length; i += 1) {
1583             values[i] = tagType.getValue(dataView, dataOffset + i * tagType.size, littleEndian);
1584         }
1585         
1586         if (tagType.ascii) {
1587             str = '';
1588             // Concatenate the chars:
1589             for (i = 0; i < values.length; i += 1) {
1590                 c = values[i];
1591                 // Ignore the terminating NULL byte(s):
1592                 if (c === '\u0000') {
1593                     break;
1594                 }
1595                 str += c;
1596             }
1597             return str;
1598         }
1599         return values;
1600     }
1601     
1602 });
1603
1604 Roo.apply(Roo.dialog.UploadCropbox, {
1605     tags : {
1606         'Orientation': 0x0112
1607     },
1608     
1609     Orientation: {
1610             1: 0, //'top-left',
1611 //            2: 'top-right',
1612             3: 180, //'bottom-right',
1613 //            4: 'bottom-left',
1614 //            5: 'left-top',
1615             6: 90, //'right-top',
1616 //            7: 'right-bottom',
1617             8: 270 //'left-bottom'
1618     },
1619     
1620     exifTagTypes : {
1621         // byte, 8-bit unsigned int:
1622         1: {
1623             getValue: function (dataView, dataOffset) {
1624                 return dataView.getUint8(dataOffset);
1625             },
1626             size: 1
1627         },
1628         // ascii, 8-bit byte:
1629         2: {
1630             getValue: function (dataView, dataOffset) {
1631                 return String.fromCharCode(dataView.getUint8(dataOffset));
1632             },
1633             size: 1,
1634             ascii: true
1635         },
1636         // short, 16 bit int:
1637         3: {
1638             getValue: function (dataView, dataOffset, littleEndian) {
1639                 return dataView.getUint16(dataOffset, littleEndian);
1640             },
1641             size: 2
1642         },
1643         // long, 32 bit int:
1644         4: {
1645             getValue: function (dataView, dataOffset, littleEndian) {
1646                 return dataView.getUint32(dataOffset, littleEndian);
1647             },
1648             size: 4
1649         },
1650         // rational = two long values, first is numerator, second is denominator:
1651         5: {
1652             getValue: function (dataView, dataOffset, littleEndian) {
1653                 return dataView.getUint32(dataOffset, littleEndian) /
1654                     dataView.getUint32(dataOffset + 4, littleEndian);
1655             },
1656             size: 8
1657         },
1658         // slong, 32 bit signed int:
1659         9: {
1660             getValue: function (dataView, dataOffset, littleEndian) {
1661                 return dataView.getInt32(dataOffset, littleEndian);
1662             },
1663             size: 4
1664         },
1665         // srational, two slongs, first is numerator, second is denominator:
1666         10: {
1667             getValue: function (dataView, dataOffset, littleEndian) {
1668                 return dataView.getInt32(dataOffset, littleEndian) /
1669                     dataView.getInt32(dataOffset + 4, littleEndian);
1670             },
1671             size: 8
1672         }
1673     },
1674     
1675     footer : {
1676         STANDARD : [
1677             {
1678                 tag : 'div',
1679                 cls : 'btn-group roo-upload-cropbox-rotate-left',
1680                 action : 'rotate-left',
1681                 cn : [
1682                     {
1683                         tag : 'button',
1684                         cls : 'btn btn-default',
1685                         html : '<i class="fa fa-undo"></i>'
1686                     }
1687                 ]
1688             },
1689             {
1690                 tag : 'div',
1691                 cls : 'btn-group roo-upload-cropbox-picture',
1692                 action : 'picture',
1693                 cn : [
1694                     {
1695                         tag : 'button',
1696                         cls : 'btn btn-default',
1697                         html : '<i class="fa fa-picture-o"></i>'
1698                     }
1699                 ]
1700             },
1701             {
1702                 tag : 'div',
1703                 cls : 'btn-group roo-upload-cropbox-rotate-right',
1704                 action : 'rotate-right',
1705                 cn : [
1706                     {
1707                         tag : 'button',
1708                         cls : 'btn btn-default',
1709                         html : '<i class="fa fa-repeat"></i>'
1710                     }
1711                 ]
1712             }
1713         ],
1714         DOCUMENT : [
1715             {
1716                 tag : 'div',
1717                 cls : 'btn-group roo-upload-cropbox-rotate-left',
1718                 action : 'rotate-left',
1719                 cn : [
1720                     {
1721                         tag : 'button',
1722                         cls : 'btn btn-default',
1723                         html : '<i class="fa fa-undo"></i>'
1724                     }
1725                 ]
1726             },
1727             {
1728                 tag : 'div',
1729                 cls : 'btn-group roo-upload-cropbox-download',
1730                 action : 'download',
1731                 cn : [
1732                     {
1733                         tag : 'button',
1734                         cls : 'btn btn-default',
1735                         html : '<i class="fa fa-download"></i>'
1736                     }
1737                 ]
1738             },
1739             {
1740                 tag : 'div',
1741                 cls : 'btn-group roo-upload-cropbox-crop',
1742                 action : 'crop',
1743                 cn : [
1744                     {
1745                         tag : 'button',
1746                         cls : 'btn btn-default',
1747                         html : '<i class="fa fa-crop"></i>'
1748                     }
1749                 ]
1750             },
1751             {
1752                 tag : 'div',
1753                 cls : 'btn-group roo-upload-cropbox-trash',
1754                 action : 'trash',
1755                 cn : [
1756                     {
1757                         tag : 'button',
1758                         cls : 'btn btn-default',
1759                         html : '<i class="fa fa-trash"></i>'
1760                     }
1761                 ]
1762             },
1763             {
1764                 tag : 'div',
1765                 cls : 'btn-group roo-upload-cropbox-rotate-right',
1766                 action : 'rotate-right',
1767                 cn : [
1768                     {
1769                         tag : 'button',
1770                         cls : 'btn btn-default',
1771                         html : '<i class="fa fa-repeat"></i>'
1772                     }
1773                 ]
1774             }
1775         ],
1776         ROTATOR : [
1777             {
1778                 tag : 'div',
1779                 cls : 'btn-group roo-upload-cropbox-rotate-left',
1780                 action : 'rotate-left',
1781                 cn : [
1782                     {
1783                         tag : 'button',
1784                         cls : 'btn btn-default',
1785                         html : '<i class="fa fa-undo"></i>'
1786                     }
1787                 ]
1788             },
1789             {
1790                 tag : 'div',
1791                 cls : 'btn-group roo-upload-cropbox-rotate-right',
1792                 action : 'rotate-right',
1793                 cn : [
1794                     {
1795                         tag : 'button',
1796                         cls : 'btn btn-default',
1797                         html : '<i class="fa fa-repeat"></i>'
1798                     }
1799                 ]
1800             }
1801         ]
1802     }
1803 });