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