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} 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 maxPaddingLeft = this.canvasEl.width / 0.9 * 0.05;
557         var maxPaddingTop = maxPaddingLeft * this.minHeight / this.minWidth;
558
559         if ((this.imageEl.OriginWidth / this.imageEl.OriginHeight <= this.minWidth / this.minHeight)) {
560             maxPaddingLeft = (this.canvasEl.height * this.minWidth / this.minHeight - this.canvasEl.width) / 2 + maxPaddingLeft;
561         }
562
563         if ((this.imageEl.OriginWidth / this.imageEl.OriginHeight >= this.minWidth / this.minHeight)) {
564             maxPaddingTop = (this.canvasEl.width * this.minHeight / this.minWidth - this.canvasEl.height) / 2 + maxPaddingTop;
565         }
566         
567         var minX = Math.ceil(this.thumbEl.getLeft(true) + this.thumbEl.getWidth() - this.canvasEl.width - maxPaddingLeft);
568         var minY = Math.ceil(this.thumbEl.getTop(true) + this.thumbEl.getHeight() - this.canvasEl.height - maxPaddingTop);
569         
570         var maxX = Math.ceil(this.thumbEl.getLeft(true) + maxPaddingLeft);
571         var maxY = Math.ceil(this.thumbEl.getTop(true) +  maxPaddingTop);
572
573         Roo.log("++++++++++++++++++");
574         
575         Roo.log("maxPaddingLeft: " + maxPaddingLeft);
576         Roo.log("maxPaddingTop: " + maxPaddingTop);
577         Roo.log("min X: " + minX);
578         Roo.log("min Y: " + minY);
579         Roo.log("max X: " + maxX);
580         Roo.log("max Y: " + maxY);
581
582
583         if(minX > maxX) {
584             var tempX = minX;
585             minX = maxX;
586             maxX = tempX;
587         }
588
589         if(minY > maxY) {
590             var tempY = minY;
591             minY = maxY;
592             maxY = tempY;
593         }
594
595         var x = Roo.isTouch ? e.browserEvent.touches[0].pageX : e.getPageX();
596         var y = Roo.isTouch ? e.browserEvent.touches[0].pageY : e.getPageY();
597         
598         x = x - this.mouseX;
599         y = y - this.mouseY;
600
601         var bgX = Math.ceil(x + this.previewEl.getLeft(true));
602         var bgY = Math.ceil(y + this.previewEl.getTop(true));
603         
604         bgX = (bgX < minX) ? minX : ((bgX > maxX) ? maxX : bgX);
605         bgY = (bgY < minY) ? minY : ((bgY > maxY) ? maxY : bgY);
606         
607         this.previewEl.setLeft(bgX);
608         this.previewEl.setTop(bgY);
609         
610         this.mouseX = Roo.isTouch ? e.browserEvent.touches[0].pageX : e.getPageX();
611         this.mouseY = Roo.isTouch ? e.browserEvent.touches[0].pageY : e.getPageY();
612     },
613     
614     onMouseUp : function(e)
615     {   
616         e.stopEvent();
617         
618         this.dragable = false;
619     },
620     
621     onMouseWheel : function(e)
622     {   
623         e.stopEvent();
624         
625         this.startScale = this.scale;
626         this.scale = (e.getWheelDelta() > 0) ? (this.scale + 1) : (this.scale - 1);
627         
628         if(!this.zoomable()){
629             this.scale = this.startScale;
630             return;
631         }
632
633         
634         this.draw();
635         
636         return;
637     },
638     
639     zoomable : function()
640     {
641         var minScale = this.thumbEl.getWidth() / this.minWidth;
642         
643         if(this.minWidth < this.minHeight){
644             minScale = this.thumbEl.getHeight() / this.minHeight;
645         }
646         
647         var width = Math.ceil(this.imageEl.OriginWidth * this.getScaleLevel() / minScale);
648         var height = Math.ceil(this.imageEl.OriginHeight * this.getScaleLevel() / minScale);
649  
650         var maxWidth = this.imageEl.OriginWidth;
651         var maxHeight = this.imageEl.OriginHeight;
652
653
654         var newCanvasWidth = Math.floor(this.imageEl.OriginWidth * this.getScaleLevel());
655         var newCanvasHeight = Math.floor(this.imageEl.OriginHeight * this.getScaleLevel());
656
657         var oldCenterLeft = Math.ceil((this.bodyEl.getWidth() - this.canvasEl.width) / 2);
658         var oldCenterTop = Math.ceil((this.bodyEl.getHeight() - this.canvasEl.height) / 2);
659
660         var newCenterLeft = Math.ceil((this.bodyEl.getWidth() - newCanvasWidth) / 2);
661         var newCenterTop = Math.ceil((this.bodyEl.getHeight() - newCanvasHeight) / 2);
662
663         var leftDiff = newCenterLeft - oldCenterLeft;
664         var topDiff = newCenterTop - oldCenterTop;
665
666         var newPreviewLeft = this.previewEl.getLeft(true) + leftDiff;
667         var newPreviewTop = this.previewEl.getTop(true) + topDiff;
668
669         var paddingLeft = newPreviewLeft - this.thumbEl.getLeft(true);
670         var paddingTop = newPreviewTop - this.thumbEl.getTop(true);
671
672         var paddingRight = this.thumbEl.getLeft(true) + this.thumbEl.getWidth() - newCanvasWidth - newPreviewLeft;
673         var paddingBottom = this.thumbEl.getTop(true) + this.thumbEl.getHeight() - newCanvasHeight - newPreviewTop;
674
675         var maxPaddingLeft = newCanvasWidth / 0.9 * 0.05;
676         var maxPaddingTop = maxPaddingLeft * this.minHeight / this.minWidth;
677
678         if ((this.imageEl.OriginWidth / this.imageEl.OriginHeight <= this.minWidth / this.minHeight)) {
679             maxPaddingLeft = (newCanvasHeight * this.minWidth / this.minHeight - newCanvasWidth) / 2 + maxPaddingLeft;
680         }
681
682         if ((this.imageEl.OriginWidth / this.imageEl.OriginHeight >= this.minWidth / this.minHeight)) {
683             maxPaddingTop = (newCanvasWidth * this.minHeight / this.minWidth - newCanvasHeight) / 2 + maxPaddingTop;
684         }
685
686         Roo.log("=================================");
687         Roo.log("old canvas width: " + this.canvasEl.width);
688         Roo.log("old canvas height: " + this.canvasEl.height);
689
690         Roo.log("new canvas width: " + newCanvasWidth);
691         Roo.log("new canvas height: " + newCanvasHeight);
692
693         Roo.log("old preview left: " + this.previewEl.getLeft(true));
694         Roo.log("old preview top: " + this.previewEl.getTop(true));
695
696         Roo.log("new preview left: " + newPreviewLeft);
697         Roo.log("new preview top: " + newPreviewTop);
698
699         Roo.log("padding left: " + paddingLeft);
700         Roo.log("padding top: " + paddingTop);
701
702         Roo.log("padding right: " + paddingRight);
703         Roo.log("padding bottom: " + paddingBottom);
704
705         Roo.log("max padding left: " + maxPaddingLeft);
706         Roo.log("max padding top: " + maxPaddingTop);
707         
708         if(
709                 this.isDocument &&
710                 (this.rotate == 0 || this.rotate == 180) && 
711                 (
712                     width > this.imageEl.OriginWidth || 
713                     height > this.imageEl.OriginHeight ||
714                     (width < this.minWidth && height < this.minHeight)
715                 )
716         ){
717             return false;
718         }
719         
720         if(
721                 this.isDocument &&
722                 (this.rotate == 90 || this.rotate == 270) && 
723                 (
724                     width > this.imageEl.OriginWidth || 
725                     height > this.imageEl.OriginHeight ||
726                     (width < this.minHeight && height < this.minWidth)
727                 )
728         ){
729             return false;
730         }
731         
732         if(
733                 !this.isDocument &&
734                 (this.rotate == 0 || this.rotate == 180) && 
735                 (
736                     // for zoom out
737                     paddingLeft > maxPaddingLeft ||
738                     paddingRight > maxPaddingLeft ||
739                     paddingTop > maxPaddingTop ||
740                     paddingBottom > maxPaddingTop ||
741                     // for zoom in
742                     width > maxWidth ||
743                     height > maxHeight
744                 )
745         ){
746             return false;
747         }
748         
749         if(
750                 !this.isDocument &&
751                 (this.rotate == 90 || this.rotate == 270) && 
752                 (
753                     width < this.minHeight || 
754                     width > this.imageEl.OriginWidth || 
755                     height < this.minWidth || 
756                     height > this.imageEl.OriginHeight
757                 )
758         ){
759             return false;
760         }
761         
762         return true;
763         
764     },
765     
766     onRotateLeft : function(e)
767     {   
768         if(!this.isDocument && (this.canvasEl.height < this.thumbEl.getWidth() || this.canvasEl.width < this.thumbEl.getHeight())){
769             
770             var minScale = this.thumbEl.getWidth() / this.minWidth;
771             
772             var bw = Math.ceil(this.canvasEl.width / this.getScaleLevel());
773             var bh = Math.ceil(this.canvasEl.height / this.getScaleLevel());
774             
775             this.startScale = this.scale;
776             
777             while (this.getScaleLevel() < minScale){
778             
779                 this.scale = this.scale + 1;
780                 
781                 if(!this.zoomable()){
782                     break;
783                 }
784                 
785                 if(
786                         Math.ceil(bw * this.getScaleLevel()) < this.thumbEl.getHeight() ||
787                         Math.ceil(bh * this.getScaleLevel()) < this.thumbEl.getWidth()
788                 ){
789                     continue;
790                 }
791                 
792                 this.rotate = (this.rotate < 90) ? 270 : this.rotate - 90;
793
794                 this.draw();
795                 
796                 return;
797             }
798             
799             this.scale = this.startScale;
800             
801             this.onRotateFail();
802             
803             return false;
804         }
805         
806         this.rotate = (this.rotate < 90) ? 270 : this.rotate - 90;
807
808         if(this.isDocument){
809             this.setThumbBoxSize();
810             this.setThumbBoxPosition();
811             this.setCanvasPosition();
812         }
813         
814         this.draw();
815         
816         this.fireEvent('rotate', this, 'left');
817         
818     },
819     
820     onRotateRight : function(e)
821     {
822         if(!this.isDocument && (this.canvasEl.height < this.thumbEl.getWidth() || this.canvasEl.width < this.thumbEl.getHeight())){
823             
824             var minScale = this.thumbEl.getWidth() / this.minWidth;
825         
826             var bw = Math.ceil(this.canvasEl.width / this.getScaleLevel());
827             var bh = Math.ceil(this.canvasEl.height / this.getScaleLevel());
828             
829             this.startScale = this.scale;
830             
831             while (this.getScaleLevel() < minScale){
832             
833                 this.scale = this.scale + 1;
834                 
835                 if(!this.zoomable()){
836                     break;
837                 }
838                 
839                 if(
840                         Math.ceil(bw * this.getScaleLevel()) < this.thumbEl.getHeight() ||
841                         Math.ceil(bh * this.getScaleLevel()) < this.thumbEl.getWidth()
842                 ){
843                     continue;
844                 }
845                 
846                 this.rotate = (this.rotate > 180) ? 0 : this.rotate + 90;
847
848                 this.draw();
849                 
850                 return;
851             }
852             
853             this.scale = this.startScale;
854             
855             this.onRotateFail();
856             
857             return false;
858         }
859         
860         this.rotate = (this.rotate > 180) ? 0 : this.rotate + 90;
861
862         if(this.isDocument){
863             this.setThumbBoxSize();
864             this.setThumbBoxPosition();
865             this.setCanvasPosition();
866         }
867         
868         this.draw();
869         
870         this.fireEvent('rotate', this, 'right');
871     },
872     
873     onRotateFail : function()
874     {
875         this.errorEl.show(true);
876         
877         var _this = this;
878         
879         (function() { _this.errorEl.hide(true); }).defer(this.errorTimeout);
880     },
881     
882     draw : function()
883     {
884         this.previewEl.dom.innerHTML = '';
885         
886         var canvasEl = document.createElement("canvas");
887         
888         var contextEl = canvasEl.getContext("2d");
889         
890         canvasEl.width = this.imageEl.OriginWidth * this.getScaleLevel();
891         canvasEl.height = this.imageEl.OriginWidth * this.getScaleLevel();
892         var center = this.imageEl.OriginWidth / 2;
893         
894         if(this.imageEl.OriginWidth < this.imageEl.OriginHeight){
895             canvasEl.width = this.imageEl.OriginHeight * this.getScaleLevel();
896             canvasEl.height = this.imageEl.OriginHeight * this.getScaleLevel();
897             center = this.imageEl.OriginHeight / 2;
898         }
899         
900         contextEl.scale(this.getScaleLevel(), this.getScaleLevel());
901         
902         contextEl.translate(center, center);
903         contextEl.rotate(this.rotate * Math.PI / 180);
904
905         contextEl.drawImage(this.imageEl, 0, 0, this.imageEl.OriginWidth, this.imageEl.OriginHeight, center * -1, center * -1, this.imageEl.OriginWidth, this.imageEl.OriginHeight);
906         
907         this.canvasEl = document.createElement("canvas");
908         
909         this.contextEl = this.canvasEl.getContext("2d");
910         
911         switch (this.rotate) {
912             case 0 :
913                 
914                 this.canvasEl.width = this.imageEl.OriginWidth * this.getScaleLevel();
915                 this.canvasEl.height = this.imageEl.OriginHeight * this.getScaleLevel();
916                 
917                 this.contextEl.drawImage(canvasEl, 0, 0, this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
918                 
919                 break;
920             case 90 : 
921                 
922                 this.canvasEl.width = this.imageEl.OriginHeight * this.getScaleLevel();
923                 this.canvasEl.height = this.imageEl.OriginWidth * this.getScaleLevel();
924                 
925                 if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
926                     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);
927                     break;
928                 }
929                 
930                 this.contextEl.drawImage(canvasEl, 0, 0, this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
931                 
932                 break;
933             case 180 :
934                 
935                 this.canvasEl.width = this.imageEl.OriginWidth * this.getScaleLevel();
936                 this.canvasEl.height = this.imageEl.OriginHeight * this.getScaleLevel();
937                 
938                 if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
939                     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);
940                     break;
941                 }
942                 
943                 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);
944                 
945                 break;
946             case 270 :
947                 
948                 this.canvasEl.width = this.imageEl.OriginHeight * this.getScaleLevel();
949                 this.canvasEl.height = this.imageEl.OriginWidth * this.getScaleLevel();
950         
951                 if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
952                     this.contextEl.drawImage(canvasEl, 0, 0, this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
953                     break;
954                 }
955                 
956                 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);
957                 
958                 break;
959             default : 
960                 break;
961         }
962         
963         this.previewEl.appendChild(this.canvasEl);
964         
965         this.setCanvasPosition(false);
966     },
967     
968     crop : function()
969     {
970         if(!this.canvasLoaded){
971             return;
972         }
973         
974         var imageCanvas = document.createElement("canvas");
975         
976         var imageContext = imageCanvas.getContext("2d");
977         
978         imageCanvas.width = (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? this.imageEl.OriginWidth : this.imageEl.OriginHeight;
979         imageCanvas.height = (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? this.imageEl.OriginWidth : this.imageEl.OriginHeight;
980         
981         var center = imageCanvas.width / 2;
982         
983         imageContext.translate(center, center);
984         
985         imageContext.rotate(this.rotate * Math.PI / 180);
986         
987         imageContext.drawImage(this.imageEl, 0, 0, this.imageEl.OriginWidth, this.imageEl.OriginHeight, center * -1, center * -1, this.imageEl.OriginWidth, this.imageEl.OriginHeight);
988         
989         var canvas = document.createElement("canvas");
990         
991         var context = canvas.getContext("2d");
992
993         canvas.width = this.thumbEl.getWidth() / this.getScaleLevel();
994         
995         canvas.height = this.thumbEl.getHeight() / this.getScaleLevel();
996
997         switch (this.rotate) {
998             case 0 :
999                 
1000                 var width = (this.thumbEl.getWidth() / this.getScaleLevel() > this.imageEl.OriginWidth) ? this.imageEl.OriginWidth : (this.thumbEl.getWidth() / this.getScaleLevel());
1001                 var height = (this.thumbEl.getHeight() / this.getScaleLevel() > this.imageEl.OriginHeight) ? this.imageEl.OriginHeight : (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 sx = this.thumbEl.getLeft(true) - this.previewEl.getLeft(true);
1007                 var sy = this.thumbEl.getTop(true) - this.previewEl.getTop(true);
1008
1009                 sx = sx < 0 ? 0 : (sx / this.getScaleLevel());
1010                 sy = sy < 0 ? 0 : (sy / this.getScaleLevel());
1011
1012                 if(canvas.width > this.outputMaxWidth) {
1013                     var scale = this.outputMaxWidth / canvas.width;
1014                     canvas.width = canvas.width * scale;
1015                     canvas.height = canvas.height * scale;
1016                     context.scale(scale, scale);
1017                 }
1018
1019                 context.fillStyle = 'white';
1020                 context.fillRect(0, 0, this.thumbEl.getWidth() / this.getScaleLevel(), this.thumbEl.getHeight() / this.getScaleLevel());
1021
1022
1023                 context.drawImage(imageCanvas, sx, sy, width, height, x, y, width, height);
1024                 
1025                 break;
1026             case 90 : 
1027                 
1028                 var width = (this.thumbEl.getWidth() / this.getScaleLevel() > this.imageEl.OriginHeight) ? this.imageEl.OriginHeight : (this.thumbEl.getWidth() / this.getScaleLevel());
1029                 var height = (this.thumbEl.getHeight() / this.getScaleLevel() > this.imageEl.OriginWidth) ? this.imageEl.OriginWidth : (this.thumbEl.getHeight() / this.getScaleLevel());
1030                 
1031                 var x = (this.thumbEl.getLeft(true) > this.previewEl.getLeft(true)) ? 0 : ((this.previewEl.getLeft(true) - this.thumbEl.getLeft(true)) / this.getScaleLevel());
1032                 var y = (this.thumbEl.getTop(true) > this.previewEl.getTop(true)) ? 0 : ((this.previewEl.getTop(true) - this.thumbEl.getTop(true)) / this.getScaleLevel());
1033                 
1034                 var targetWidth = this.minWidth - 2 * x;
1035                 var targetHeight = this.minHeight - 2 * y;
1036                 
1037                 var scale = 1;
1038                 
1039                 if((x == 0 && y == 0) || (x == 0 && y > 0)){
1040                     scale = targetWidth / width;
1041                 }
1042                 
1043                 if(x > 0 && y == 0){
1044                     scale = targetHeight / height;
1045                 }
1046                 
1047                 if(x > 0 && y > 0){
1048                     scale = targetWidth / width;
1049                     
1050                     if(width < height){
1051                         scale = targetHeight / height;
1052                     }
1053                 }
1054                 
1055                 context.scale(scale, scale);
1056                 
1057                 var sx = Math.min(this.canvasEl.width - this.thumbEl.getWidth(), this.thumbEl.getLeft(true) - this.previewEl.getLeft(true));
1058                 var sy = Math.min(this.canvasEl.height - this.thumbEl.getHeight(), this.thumbEl.getTop(true) - this.previewEl.getTop(true));
1059
1060                 sx = sx < 0 ? 0 : (sx / this.getScaleLevel());
1061                 sy = sy < 0 ? 0 : (sy / this.getScaleLevel());
1062                 
1063                 sx += (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? Math.abs(this.imageEl.OriginWidth - this.imageEl.OriginHeight) : 0;
1064                 
1065                 context.drawImage(imageCanvas, sx, sy, width, height, x, y, width, height);
1066                 
1067                 break;
1068             case 180 :
1069                 
1070                 var width = (this.thumbEl.getWidth() / this.getScaleLevel() > this.imageEl.OriginWidth) ? this.imageEl.OriginWidth : (this.thumbEl.getWidth() / this.getScaleLevel());
1071                 var height = (this.thumbEl.getHeight() / this.getScaleLevel() > this.imageEl.OriginHeight) ? this.imageEl.OriginHeight : (this.thumbEl.getHeight() / this.getScaleLevel());
1072                 
1073                 var x = (this.thumbEl.getLeft(true) > this.previewEl.getLeft(true)) ? 0 : ((this.previewEl.getLeft(true) - this.thumbEl.getLeft(true)) / this.getScaleLevel());
1074                 var y = (this.thumbEl.getTop(true) > this.previewEl.getTop(true)) ? 0 : ((this.previewEl.getTop(true) - this.thumbEl.getTop(true)) / this.getScaleLevel());
1075                 
1076                 var targetWidth = this.minWidth - 2 * x;
1077                 var targetHeight = this.minHeight - 2 * y;
1078                 
1079                 var scale = 1;
1080                 
1081                 if((x == 0 && y == 0) || (x == 0 && y > 0)){
1082                     scale = targetWidth / width;
1083                 }
1084                 
1085                 if(x > 0 && y == 0){
1086                     scale = targetHeight / height;
1087                 }
1088                 
1089                 if(x > 0 && y > 0){
1090                     scale = targetWidth / width;
1091                     
1092                     if(width < height){
1093                         scale = targetHeight / height;
1094                     }
1095                 }
1096                 
1097                 context.scale(scale, scale);
1098                 
1099                 var sx = Math.min(this.canvasEl.width - this.thumbEl.getWidth(), this.thumbEl.getLeft(true) - this.previewEl.getLeft(true));
1100                 var sy = Math.min(this.canvasEl.height - this.thumbEl.getHeight(), this.thumbEl.getTop(true) - this.previewEl.getTop(true));
1101
1102                 sx = sx < 0 ? 0 : (sx / this.getScaleLevel());
1103                 sy = sy < 0 ? 0 : (sy / this.getScaleLevel());
1104
1105                 sx += (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? 0 : Math.abs(this.imageEl.OriginWidth - this.imageEl.OriginHeight);
1106                 sy += (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? Math.abs(this.imageEl.OriginWidth - this.imageEl.OriginHeight) : 0;
1107                 
1108                 context.drawImage(imageCanvas, sx, sy, width, height, x, y, width, height);
1109                 
1110                 break;
1111             case 270 :
1112                 
1113                 var width = (this.thumbEl.getWidth() / this.getScaleLevel() > this.imageEl.OriginHeight) ? this.imageEl.OriginHeight : (this.thumbEl.getWidth() / this.getScaleLevel());
1114                 var height = (this.thumbEl.getHeight() / this.getScaleLevel() > this.imageEl.OriginWidth) ? this.imageEl.OriginWidth : (this.thumbEl.getHeight() / this.getScaleLevel());
1115                 
1116                 var x = (this.thumbEl.getLeft(true) > this.previewEl.getLeft(true)) ? 0 : ((this.previewEl.getLeft(true) - this.thumbEl.getLeft(true)) / this.getScaleLevel());
1117                 var y = (this.thumbEl.getTop(true) > this.previewEl.getTop(true)) ? 0 : ((this.previewEl.getTop(true) - this.thumbEl.getTop(true)) / this.getScaleLevel());
1118                 
1119                 var targetWidth = this.minWidth - 2 * x;
1120                 var targetHeight = this.minHeight - 2 * y;
1121                 
1122                 var scale = 1;
1123                 
1124                 if((x == 0 && y == 0) || (x == 0 && y > 0)){
1125                     scale = targetWidth / width;
1126                 }
1127                 
1128                 if(x > 0 && y == 0){
1129                     scale = targetHeight / height;
1130                 }
1131                 
1132                 if(x > 0 && y > 0){
1133                     scale = targetWidth / width;
1134                     
1135                     if(width < height){
1136                         scale = targetHeight / height;
1137                     }
1138                 }
1139                 
1140                 context.scale(scale, scale);
1141                 var sx = Math.min(this.canvasEl.width - this.thumbEl.getWidth(), this.thumbEl.getLeft(true) - this.previewEl.getLeft(true));
1142                 var sy = Math.min(this.canvasEl.height - this.thumbEl.getHeight(), this.thumbEl.getTop(true) - this.previewEl.getTop(true));
1143
1144                 sx = sx < 0 ? 0 : (sx / this.getScaleLevel());
1145                 sy = sy < 0 ? 0 : (sy / this.getScaleLevel());
1146                 
1147                 sy += (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? 0 : Math.abs(this.imageEl.OriginWidth - this.imageEl.OriginHeight);
1148                 
1149                 context.drawImage(imageCanvas, sx, sy, width, height, x, y, width, height);
1150                 
1151                 break;
1152             default : 
1153                 break;
1154         }
1155         
1156         this.cropData = canvas.toDataURL(this.cropType);
1157         
1158         if(this.fireEvent('crop', this, this.cropData) !== false){
1159             this.process(this.file, this.cropData);
1160         }
1161         
1162         return;
1163         
1164     },
1165     
1166     setThumbBoxSize : function()
1167     {
1168         var width, height;
1169         
1170         if(this.isDocument && typeof(this.imageEl) != 'undefined'){
1171             width = (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? Math.max(this.minWidth, this.minHeight) : Math.min(this.minWidth, this.minHeight);
1172             height = (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? Math.min(this.minWidth, this.minHeight) : Math.max(this.minWidth, this.minHeight);
1173             
1174             this.minWidth = width;
1175             this.minHeight = height;
1176             
1177             if(this.rotate == 90 || this.rotate == 270){
1178                 this.minWidth = height;
1179                 this.minHeight = width;
1180             }
1181         }
1182         
1183         height = this.windowSize;
1184         width = Math.ceil(this.minWidth * height / this.minHeight);
1185         
1186         if(this.minWidth > this.minHeight){
1187             width = this.windowSize;
1188             height = Math.ceil(this.minHeight * width / this.minWidth);
1189         }
1190         
1191         this.thumbEl.setStyle({
1192             width : width + 'px',
1193             height : height + 'px'
1194         });
1195
1196         return;
1197             
1198     },
1199     
1200     setThumbBoxPosition : function()
1201     {
1202         var x = Math.ceil((this.bodyEl.getWidth() - this.thumbEl.getWidth()) / 2 );
1203         var y = Math.ceil((this.bodyEl.getHeight() - this.thumbEl.getHeight()) / 2);
1204         
1205         this.thumbEl.setLeft(x);
1206         this.thumbEl.setTop(y);
1207         
1208     },
1209     
1210     baseRotateLevel : function()
1211     {
1212         this.baseRotate = 1;
1213         
1214         if(
1215                 typeof(this.exif) != 'undefined' &&
1216                 typeof(this.exif[Roo.dialog.UploadCropbox['tags']['Orientation']]) != 'undefined' &&
1217                 [1, 3, 6, 8].indexOf(this.exif[Roo.dialog.UploadCropbox['tags']['Orientation']]) != -1
1218         ){
1219             this.baseRotate = this.exif[Roo.dialog.UploadCropbox['tags']['Orientation']];
1220         }
1221         
1222         this.rotate = Roo.dialog.UploadCropbox['Orientation'][this.baseRotate];
1223         
1224     },
1225     
1226     baseScaleLevel : function()
1227     {
1228         var width, height;
1229         
1230         if(this.isDocument){
1231             
1232             if(this.baseRotate == 6 || this.baseRotate == 8){
1233             
1234                 height = this.thumbEl.getHeight();
1235                 this.baseScale = height / this.imageEl.OriginWidth;
1236
1237                 if(this.imageEl.OriginHeight * this.baseScale > this.thumbEl.getWidth()){
1238                     width = this.thumbEl.getWidth();
1239                     this.baseScale = width / this.imageEl.OriginHeight;
1240                 }
1241
1242                 return;
1243             }
1244
1245             height = this.thumbEl.getHeight();
1246             this.baseScale = height / this.imageEl.OriginHeight;
1247
1248             if(this.imageEl.OriginWidth * this.baseScale > this.thumbEl.getWidth()){
1249                 width = this.thumbEl.getWidth();
1250                 this.baseScale = width / this.imageEl.OriginWidth;
1251             }
1252
1253             return;
1254         }
1255         
1256         if(this.baseRotate == 6 || this.baseRotate == 8){
1257             
1258             width = this.thumbEl.getHeight();
1259             this.baseScale = width / this.imageEl.OriginHeight;
1260             
1261             if(this.imageEl.OriginHeight * this.baseScale < this.thumbEl.getWidth()){
1262                 height = this.thumbEl.getWidth();
1263                 this.baseScale = height / this.imageEl.OriginHeight;
1264             }
1265             
1266             if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
1267                 height = this.thumbEl.getWidth();
1268                 this.baseScale = height / this.imageEl.OriginHeight;
1269                 
1270                 if(this.imageEl.OriginWidth * this.baseScale < this.thumbEl.getHeight()){
1271                     width = this.thumbEl.getHeight();
1272                     this.baseScale = width / this.imageEl.OriginWidth;
1273                 }
1274             }
1275             
1276             return;
1277         }
1278         
1279         width = this.thumbEl.getWidth();
1280         this.baseScale = width / this.imageEl.OriginWidth;
1281         
1282         if(this.imageEl.OriginHeight * this.baseScale < this.thumbEl.getHeight()){
1283             height = this.thumbEl.getHeight();
1284             this.baseScale = height / this.imageEl.OriginHeight;
1285         }
1286         
1287         if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
1288             
1289             height = this.thumbEl.getHeight();
1290             this.baseScale = height / this.imageEl.OriginHeight;
1291             
1292             if(this.imageEl.OriginWidth * this.baseScale < this.thumbEl.getWidth()){
1293                 width = this.thumbEl.getWidth();
1294                 this.baseScale = width / this.imageEl.OriginWidth;
1295             }
1296             
1297         }
1298
1299         if(this.imageEl.OriginWidth < this.minWidth || this.imageEl.OriginHeight < this.minHeight) {
1300             this.baseScale = width / this.minWidth;
1301         }
1302
1303         return;
1304     },
1305     
1306     getScaleLevel : function()
1307     {
1308         return this.baseScale * Math.pow(1.02, this.scale);
1309     },
1310     
1311     onTouchStart : function(e)
1312     {
1313         if(!this.canvasLoaded){
1314             this.beforeSelectFile(e);
1315             return;
1316         }
1317         
1318         var touches = e.browserEvent.touches;
1319         
1320         if(!touches){
1321             return;
1322         }
1323         
1324         if(touches.length == 1){
1325             this.onMouseDown(e);
1326             return;
1327         }
1328         
1329         if(touches.length != 2){
1330             return;
1331         }
1332         
1333         var coords = [];
1334         
1335         for(var i = 0, finger; finger = touches[i]; i++){
1336             coords.push(finger.pageX, finger.pageY);
1337         }
1338         
1339         var x = Math.pow(coords[0] - coords[2], 2);
1340         var y = Math.pow(coords[1] - coords[3], 2);
1341         
1342         this.startDistance = Math.sqrt(x + y);
1343         
1344         this.startScale = this.scale;
1345         
1346         this.pinching = true;
1347         this.dragable = false;
1348         
1349     },
1350     
1351     onTouchMove : function(e)
1352     {
1353         if(!this.pinching && !this.dragable){
1354             return;
1355         }
1356         
1357         var touches = e.browserEvent.touches;
1358         
1359         if(!touches){
1360             return;
1361         }
1362         
1363         if(this.dragable){
1364             this.onMouseMove(e);
1365             return;
1366         }
1367         
1368         var coords = [];
1369         
1370         for(var i = 0, finger; finger = touches[i]; i++){
1371             coords.push(finger.pageX, finger.pageY);
1372         }
1373         
1374         var x = Math.pow(coords[0] - coords[2], 2);
1375         var y = Math.pow(coords[1] - coords[3], 2);
1376         
1377         this.endDistance = Math.sqrt(x + y);
1378         
1379         this.scale = this.startScale + Math.floor(Math.log(this.endDistance / this.startDistance) / Math.log(1.1));
1380         
1381         if(!this.zoomable()){
1382             this.scale = this.startScale;
1383             return;
1384         }
1385         
1386         this.draw();
1387         
1388     },
1389     
1390     onTouchEnd : function(e)
1391     {
1392         this.pinching = false;
1393         this.dragable = false;
1394         
1395     },
1396     
1397     process : function(file, crop)
1398     {
1399         if(this.loadMask){
1400             this.maskEl.mask(this.loadingText);
1401         }
1402         
1403         this.xhr = new XMLHttpRequest();
1404         
1405         file.xhr = this.xhr;
1406
1407         this.xhr.open(this.method, this.url, true);
1408         
1409         var headers = {
1410             "Accept": "application/json",
1411             "Cache-Control": "no-cache",
1412             "X-Requested-With": "XMLHttpRequest"
1413         };
1414         
1415         for (var headerName in headers) {
1416             var headerValue = headers[headerName];
1417             if (headerValue) {
1418                 this.xhr.setRequestHeader(headerName, headerValue);
1419             }
1420         }
1421         
1422         var _this = this;
1423         
1424         this.xhr.onload = function()
1425         {
1426             _this.xhrOnLoad(_this.xhr);
1427         }
1428         
1429         this.xhr.onerror = function()
1430         {
1431             _this.xhrOnError(_this.xhr);
1432         }
1433         
1434         var formData = new FormData();
1435
1436         formData.append('returnHTML', 'NO');
1437
1438         if(crop){
1439             formData.append('crop', crop);
1440             var blobBin = atob(crop.split(',')[1]);
1441             var array = [];
1442             for(var i = 0; i < blobBin.length; i++) {
1443                 array.push(blobBin.charCodeAt(i));
1444             }
1445             var croppedFile =new Blob([new Uint8Array(array)], {type: this.cropType});
1446             formData.append(this.paramName, croppedFile, file.name);
1447         }
1448         
1449         if(typeof(file.filename) != 'undefined'){
1450             formData.append('filename', file.filename);
1451         }
1452         
1453         if(typeof(file.mimetype) != 'undefined'){
1454             formData.append('mimetype', file.mimetype);
1455         }
1456
1457         if(this.fireEvent('arrange', this, formData) != false){
1458             this.xhr.send(formData);
1459         };
1460     },
1461     
1462     xhrOnLoad : function(xhr)
1463     {
1464         if(this.loadMask){
1465             this.maskEl.unmask();
1466         }
1467         
1468         if (xhr.readyState !== 4) {
1469             this.fireEvent('exception', this, xhr);
1470             return;
1471         }
1472
1473         var response = Roo.decode(xhr.responseText);
1474         
1475         if(!response.success){
1476             this.fireEvent('exception', this, xhr);
1477             return;
1478         }
1479         
1480         var response = Roo.decode(xhr.responseText);
1481         
1482         this.fireEvent('upload', this, response);
1483         
1484     },
1485     
1486     xhrOnError : function()
1487     {
1488         if(this.loadMask){
1489             this.maskEl.unmask();
1490         }
1491         
1492         Roo.log('xhr on error');
1493         
1494         var response = Roo.decode(xhr.responseText);
1495           
1496         Roo.log(response);
1497         
1498     },
1499     
1500     prepare : function(file)
1501     {   
1502         if(this.loadMask){
1503             this.maskEl.mask(this.loadingText);
1504         }
1505         
1506         this.file = false;
1507         this.exif = {};
1508         
1509         if(typeof(file) === 'string'){
1510             this.loadCanvas(file);
1511             return;
1512         }
1513         
1514         if(!file || !this.urlAPI){
1515             return;
1516         }
1517         
1518         this.file = file;
1519         if(typeof(file.type) != 'undefined' && file.type.length != 0) {
1520             this.cropType = file.type;
1521         }
1522         
1523         var _this = this;
1524         
1525         if(this.fireEvent('prepare', this, this.file) != false){
1526             
1527             var reader = new FileReader();
1528             
1529             reader.onload = function (e) {
1530                 if (e.target.error) {
1531                     Roo.log(e.target.error);
1532                     return;
1533                 }
1534                 
1535                 var buffer = e.target.result,
1536                     dataView = new DataView(buffer),
1537                     offset = 2,
1538                     maxOffset = dataView.byteLength - 4,
1539                     markerBytes,
1540                     markerLength;
1541                 
1542                 if (dataView.getUint16(0) === 0xffd8) {
1543                     while (offset < maxOffset) {
1544                         markerBytes = dataView.getUint16(offset);
1545                         
1546                         if ((markerBytes >= 0xffe0 && markerBytes <= 0xffef) || markerBytes === 0xfffe) {
1547                             markerLength = dataView.getUint16(offset + 2) + 2;
1548                             if (offset + markerLength > dataView.byteLength) {
1549                                 Roo.log('Invalid meta data: Invalid segment size.');
1550                                 break;
1551                             }
1552                             
1553                             if(markerBytes == 0xffe1){
1554                                 _this.parseExifData(
1555                                     dataView,
1556                                     offset,
1557                                     markerLength
1558                                 );
1559                             }
1560                             
1561                             offset += markerLength;
1562                             
1563                             continue;
1564                         }
1565                         
1566                         break;
1567                     }
1568                     
1569                 }
1570                 
1571                 var url = _this.urlAPI.createObjectURL(_this.file);
1572                 
1573                 _this.loadCanvas(url);
1574                 
1575                 return;
1576             }
1577             
1578             reader.readAsArrayBuffer(this.file);
1579             
1580         }
1581         
1582     },
1583     
1584     parseExifData : function(dataView, offset, length)
1585     {
1586         var tiffOffset = offset + 10,
1587             littleEndian,
1588             dirOffset;
1589     
1590         if (dataView.getUint32(offset + 4) !== 0x45786966) {
1591             // No Exif data, might be XMP data instead
1592             return;
1593         }
1594         
1595         // Check for the ASCII code for "Exif" (0x45786966):
1596         if (dataView.getUint32(offset + 4) !== 0x45786966) {
1597             // No Exif data, might be XMP data instead
1598             return;
1599         }
1600         if (tiffOffset + 8 > dataView.byteLength) {
1601             Roo.log('Invalid Exif data: Invalid segment size.');
1602             return;
1603         }
1604         // Check for the two null bytes:
1605         if (dataView.getUint16(offset + 8) !== 0x0000) {
1606             Roo.log('Invalid Exif data: Missing byte alignment offset.');
1607             return;
1608         }
1609         // Check the byte alignment:
1610         switch (dataView.getUint16(tiffOffset)) {
1611         case 0x4949:
1612             littleEndian = true;
1613             break;
1614         case 0x4D4D:
1615             littleEndian = false;
1616             break;
1617         default:
1618             Roo.log('Invalid Exif data: Invalid byte alignment marker.');
1619             return;
1620         }
1621         // Check for the TIFF tag marker (0x002A):
1622         if (dataView.getUint16(tiffOffset + 2, littleEndian) !== 0x002A) {
1623             Roo.log('Invalid Exif data: Missing TIFF marker.');
1624             return;
1625         }
1626         // Retrieve the directory offset bytes, usually 0x00000008 or 8 decimal:
1627         dirOffset = dataView.getUint32(tiffOffset + 4, littleEndian);
1628         
1629         this.parseExifTags(
1630             dataView,
1631             tiffOffset,
1632             tiffOffset + dirOffset,
1633             littleEndian
1634         );
1635     },
1636     
1637     parseExifTags : function(dataView, tiffOffset, dirOffset, littleEndian)
1638     {
1639         var tagsNumber,
1640             dirEndOffset,
1641             i;
1642         if (dirOffset + 6 > dataView.byteLength) {
1643             Roo.log('Invalid Exif data: Invalid directory offset.');
1644             return;
1645         }
1646         tagsNumber = dataView.getUint16(dirOffset, littleEndian);
1647         dirEndOffset = dirOffset + 2 + 12 * tagsNumber;
1648         if (dirEndOffset + 4 > dataView.byteLength) {
1649             Roo.log('Invalid Exif data: Invalid directory size.');
1650             return;
1651         }
1652         for (i = 0; i < tagsNumber; i += 1) {
1653             this.parseExifTag(
1654                 dataView,
1655                 tiffOffset,
1656                 dirOffset + 2 + 12 * i, // tag offset
1657                 littleEndian
1658             );
1659         }
1660         // Return the offset to the next directory:
1661         return dataView.getUint32(dirEndOffset, littleEndian);
1662     },
1663     
1664     parseExifTag : function (dataView, tiffOffset, offset, littleEndian) 
1665     {
1666         var tag = dataView.getUint16(offset, littleEndian);
1667         
1668         this.exif[tag] = this.getExifValue(
1669             dataView,
1670             tiffOffset,
1671             offset,
1672             dataView.getUint16(offset + 2, littleEndian), // tag type
1673             dataView.getUint32(offset + 4, littleEndian), // tag length
1674             littleEndian
1675         );
1676     },
1677     
1678     getExifValue : function (dataView, tiffOffset, offset, type, length, littleEndian)
1679     {
1680         var tagType = Roo.dialog.UploadCropbox.exifTagTypes[type],
1681             tagSize,
1682             dataOffset,
1683             values,
1684             i,
1685             str,
1686             c;
1687     
1688         if (!tagType) {
1689             Roo.log('Invalid Exif data: Invalid tag type.');
1690             return;
1691         }
1692         
1693         tagSize = tagType.size * length;
1694         // Determine if the value is contained in the dataOffset bytes,
1695         // or if the value at the dataOffset is a pointer to the actual data:
1696         dataOffset = tagSize > 4 ?
1697                 tiffOffset + dataView.getUint32(offset + 8, littleEndian) : (offset + 8);
1698         if (dataOffset + tagSize > dataView.byteLength) {
1699             Roo.log('Invalid Exif data: Invalid data offset.');
1700             return;
1701         }
1702         if (length === 1) {
1703             return tagType.getValue(dataView, dataOffset, littleEndian);
1704         }
1705         values = [];
1706         for (i = 0; i < length; i += 1) {
1707             values[i] = tagType.getValue(dataView, dataOffset + i * tagType.size, littleEndian);
1708         }
1709         
1710         if (tagType.ascii) {
1711             str = '';
1712             // Concatenate the chars:
1713             for (i = 0; i < values.length; i += 1) {
1714                 c = values[i];
1715                 // Ignore the terminating NULL byte(s):
1716                 if (c === '\u0000') {
1717                     break;
1718                 }
1719                 str += c;
1720             }
1721             return str;
1722         }
1723         return values;
1724     }
1725     
1726 });
1727
1728 Roo.apply(Roo.dialog.UploadCropbox, {
1729     tags : {
1730         'Orientation': 0x0112
1731     },
1732     
1733     Orientation: {
1734             1: 0, //'top-left',
1735 //            2: 'top-right',
1736             3: 180, //'bottom-right',
1737 //            4: 'bottom-left',
1738 //            5: 'left-top',
1739             6: 90, //'right-top',
1740 //            7: 'right-bottom',
1741             8: 270 //'left-bottom'
1742     },
1743     
1744     exifTagTypes : {
1745         // byte, 8-bit unsigned int:
1746         1: {
1747             getValue: function (dataView, dataOffset) {
1748                 return dataView.getUint8(dataOffset);
1749             },
1750             size: 1
1751         },
1752         // ascii, 8-bit byte:
1753         2: {
1754             getValue: function (dataView, dataOffset) {
1755                 return String.fromCharCode(dataView.getUint8(dataOffset));
1756             },
1757             size: 1,
1758             ascii: true
1759         },
1760         // short, 16 bit int:
1761         3: {
1762             getValue: function (dataView, dataOffset, littleEndian) {
1763                 return dataView.getUint16(dataOffset, littleEndian);
1764             },
1765             size: 2
1766         },
1767         // long, 32 bit int:
1768         4: {
1769             getValue: function (dataView, dataOffset, littleEndian) {
1770                 return dataView.getUint32(dataOffset, littleEndian);
1771             },
1772             size: 4
1773         },
1774         // rational = two long values, first is numerator, second is denominator:
1775         5: {
1776             getValue: function (dataView, dataOffset, littleEndian) {
1777                 return dataView.getUint32(dataOffset, littleEndian) /
1778                     dataView.getUint32(dataOffset + 4, littleEndian);
1779             },
1780             size: 8
1781         },
1782         // slong, 32 bit signed int:
1783         9: {
1784             getValue: function (dataView, dataOffset, littleEndian) {
1785                 return dataView.getInt32(dataOffset, littleEndian);
1786             },
1787             size: 4
1788         },
1789         // srational, two slongs, first is numerator, second is denominator:
1790         10: {
1791             getValue: function (dataView, dataOffset, littleEndian) {
1792                 return dataView.getInt32(dataOffset, littleEndian) /
1793                     dataView.getInt32(dataOffset + 4, littleEndian);
1794             },
1795             size: 8
1796         }
1797     },
1798     
1799     footer : {
1800         STANDARD : [
1801             {
1802                 tag : 'div',
1803                 cls : 'btn-group roo-upload-cropbox-rotate-left',
1804                 action : 'rotate-left',
1805                 cn : [
1806                     {
1807                         tag : 'button',
1808                         cls : 'btn btn-default',
1809                         html : '<i class="fa fa-undo"></i>'
1810                     }
1811                 ]
1812             },
1813             {
1814                 tag : 'div',
1815                 cls : 'btn-group roo-upload-cropbox-picture',
1816                 action : 'picture',
1817                 cn : [
1818                     {
1819                         tag : 'button',
1820                         cls : 'btn btn-default',
1821                         html : '<i class="fa fa-picture-o"></i>'
1822                     }
1823                 ]
1824             },
1825             {
1826                 tag : 'div',
1827                 cls : 'btn-group roo-upload-cropbox-rotate-right',
1828                 action : 'rotate-right',
1829                 cn : [
1830                     {
1831                         tag : 'button',
1832                         cls : 'btn btn-default',
1833                         html : '<i class="fa fa-repeat"></i>'
1834                     }
1835                 ]
1836             }
1837         ],
1838         DOCUMENT : [
1839             {
1840                 tag : 'div',
1841                 cls : 'btn-group roo-upload-cropbox-rotate-left',
1842                 action : 'rotate-left',
1843                 cn : [
1844                     {
1845                         tag : 'button',
1846                         cls : 'btn btn-default',
1847                         html : '<i class="fa fa-undo"></i>'
1848                     }
1849                 ]
1850             },
1851             {
1852                 tag : 'div',
1853                 cls : 'btn-group roo-upload-cropbox-download',
1854                 action : 'download',
1855                 cn : [
1856                     {
1857                         tag : 'button',
1858                         cls : 'btn btn-default',
1859                         html : '<i class="fa fa-download"></i>'
1860                     }
1861                 ]
1862             },
1863             {
1864                 tag : 'div',
1865                 cls : 'btn-group roo-upload-cropbox-crop',
1866                 action : 'crop',
1867                 cn : [
1868                     {
1869                         tag : 'button',
1870                         cls : 'btn btn-default',
1871                         html : '<i class="fa fa-crop"></i>'
1872                     }
1873                 ]
1874             },
1875             {
1876                 tag : 'div',
1877                 cls : 'btn-group roo-upload-cropbox-trash',
1878                 action : 'trash',
1879                 cn : [
1880                     {
1881                         tag : 'button',
1882                         cls : 'btn btn-default',
1883                         html : '<i class="fa fa-trash"></i>'
1884                     }
1885                 ]
1886             },
1887             {
1888                 tag : 'div',
1889                 cls : 'btn-group roo-upload-cropbox-rotate-right',
1890                 action : 'rotate-right',
1891                 cn : [
1892                     {
1893                         tag : 'button',
1894                         cls : 'btn btn-default',
1895                         html : '<i class="fa fa-repeat"></i>'
1896                     }
1897                 ]
1898             }
1899         ],
1900         ROTATOR : [
1901             {
1902                 tag : 'div',
1903                 cls : 'btn-group roo-upload-cropbox-rotate-left',
1904                 action : 'rotate-left',
1905                 cn : [
1906                     {
1907                         tag : 'button',
1908                         cls : 'btn btn-default',
1909                         html : '<i class="fa fa-undo"></i>'
1910                     }
1911                 ]
1912             },
1913             {
1914                 tag : 'div',
1915                 cls : 'btn-group roo-upload-cropbox-rotate-right',
1916                 action : 'rotate-right',
1917                 cn : [
1918                     {
1919                         tag : 'button',
1920                         cls : 'btn btn-default',
1921                         html : '<i class="fa fa-repeat"></i>'
1922                     }
1923                 ]
1924             }
1925         ],
1926         CENTER : [
1927             {
1928                 tag : 'div',
1929                 cls : 'btn-group roo-upload-cropbox-center',
1930                 action : 'center',
1931                 cn : [
1932                     {
1933                         tag : 'button',
1934                         cls : 'btn btn-default',
1935                         html : 'CENTER'
1936                     }
1937                 ]
1938             }
1939         ]
1940     }
1941 });