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