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