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