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