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