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