Roo/dialog/UploadCropbox.js
[roojs1] / Roo / dialog / UploadCropbox.js
1
2 /*
3 * Licence: LGPL
4 */
5
6 /**
7  * @class Roo.dialog.UploadCropbox
8  * @extends Roo.BoxComponent
9  * Dialog UploadCropbox class
10  * @cfg {String} emptyText show when image has been loaded
11  * @cfg {String} rotateNotify show when image too small to rotate
12  * @cfg {Number} errorTimeout default 3000
13  * @cfg {Number} minWidth default 300
14  * @cfg {Number} minHeight default 300
15  * @cfg {Number} outputMaxWidth default 1200
16  * @cfg {Number} windowSize default 300
17  * @cfg {Array} buttons default ['rotateLeft', 'pictureBtn', 'rotateRight']
18  * @cfg {Boolean} isDocument (true|false) default false
19  * @cfg {String} url action url
20  * @cfg {String} paramName default 'imageUpload'
21  * @cfg {String} method default POST
22  * @cfg {Boolean} loadMask (true|false) default true
23  * @cfg {Boolean} loadingText default 'Loading...'
24  * 
25  * @constructor
26  * Create a new UploadCropbox
27  * @param {Object} config The config object
28  */
29
30  Roo.dialog.UploadCropbox = function(config){
31     Roo.dialog.UploadCropbox.superclass.constructor.call(this, config);
32     
33     this.addEvents({
34         /**
35          * @event beforeselectfile
36          * Fire before select file
37          * @param {Roo.dialog.UploadCropbox} this
38          */
39         "beforeselectfile" : true,
40         /**
41          * @event initial
42          * Fire after initEvent
43          * @param {Roo.dialog.UploadCropbox} this
44          */
45         "initial" : true,
46         /**
47          * @event crop
48          * Fire after initEvent
49          * @param {Roo.dialog.UploadCropbox} this
50          * @param {String} data
51          */
52         "crop" : true,
53         /**
54          * @event prepare
55          * Fire when preparing the file data
56          * @param {Roo.dialog.UploadCropbox} this
57          * @param {Object} file
58          */
59         "prepare" : true,
60         /**
61          * @event exception
62          * Fire when get exception
63          * @param {Roo.dialog.UploadCropbox} this
64          * @param {XMLHttpRequest} xhr
65          */
66         "exception" : true,
67         /**
68          * @event beforeloadcanvas
69          * Fire before load the canvas
70          * @param {Roo.dialog.UploadCropbox} this
71          * @param {String} src
72          */
73         "beforeloadcanvas" : true,
74         /**
75          * @event trash
76          * Fire when trash image
77          * @param {Roo.dialog.UploadCropbox} this
78          */
79         "trash" : true,
80         /**
81          * @event download
82          * Fire when download the image
83          * @param {Roo.dialog.UploadCropbox} this
84          */
85         "download" : true,
86         /**
87          * @event footerbuttonclick
88          * Fire when footerbuttonclick
89          * @param {Roo.dialog.UploadCropbox} this
90          * @param {String} type
91          */
92         "footerbuttonclick" : true,
93         /**
94          * @event resize
95          * Fire when resize
96          * @param {Roo.dialog.UploadCropbox} this
97          */
98         "resize" : true,
99         /**
100          * @event rotate
101          * Fire when rotate the image
102          * @param {Roo.dialog.UploadCropbox} this
103          * @param {String} pos
104          */
105         "rotate" : true,
106         /**
107          * @event inspect
108          * Fire when inspect the file
109          * @param {Roo.dialog.UploadCropbox} this
110          * @param {Object} file
111          */
112         "inspect" : true,
113         /**
114          * @event upload
115          * Fire when xhr upload the file
116          * @param {Roo.dialog.UploadCropbox} this
117          * @param {Object} data
118          */
119         "upload" : true,
120         /**
121          * @event arrange
122          * Fire when arrange the file data
123          * @param {Roo.dialog.UploadCropbox} this
124          * @param {Object} formData
125          */
126         "arrange" : true,
127         /**
128          * @event loadcanvas
129          * Fire after load the canvas
130          * @param {Roo.dialog.UploadCropbox}
131          * @param {Object} imgEl
132          */
133         "loadcanvas" : true
134     });
135     
136     this.buttons = this.buttons || Roo.dialog.UploadCropbox.footer.STANDARD;
137 };
138
139 Roo.extend(Roo.dialog.UploadCropbox, Roo.Component,  {
140     
141     emptyText : 'Click to upload image',
142     rotateNotify : 'Image is too small to rotate',
143     errorTimeout : 3000,
144     scale : 0,
145     baseScale : 1,
146     rotate : 0,
147     dragable : false,
148     pinching : false,
149     mouseX : 0,
150     mouseY : 0,
151     cropData : false,
152     minWidth : 300,
153     minHeight : 300,
154     outputMaxWidth : 1200,
155     windowSize : 300,
156     file : false,
157     exif : {},
158     baseRotate : 1,
159     cropType : 'image/jpeg',
160     buttons : false,
161     canvasLoaded : false,
162     isDocument : false,
163     method : 'POST',
164     paramName : 'imageUpload',
165     loadMask : true,
166     loadingText : 'Loading...',
167     maskEl : false,
168     
169     getAutoCreate : function()
170     {
171         var cfg = {
172             tag : 'div',
173             cls : 'roo-upload-cropbox',
174             cn : [
175                 {
176                     tag : 'input',
177                     cls : 'roo-upload-cropbox-selector',
178                     type : 'file'
179                 },
180                 {
181                     tag : 'div',
182                     cls : 'roo-upload-cropbox-body',
183                     style : 'cursor:pointer',
184                     cn : [
185                         {
186                             tag : 'div',
187                             cls : 'roo-upload-cropbox-preview'
188                         },
189                         {
190                             tag : 'div',
191                             cls : 'roo-upload-cropbox-thumb'
192                         },
193                         {
194                             tag : 'div',
195                             cls : 'roo-upload-cropbox-empty-notify',
196                             html : this.emptyText
197                         },
198                         {
199                             tag : 'div',
200                             cls : 'roo-upload-cropbox-error-notify alert alert-danger',
201                             html : this.rotateNotify
202                         }
203                     ]
204                 },
205                 {
206                     tag : 'div',
207                     cls : 'roo-upload-cropbox-footer',
208                     cn : {
209                         tag : 'div',
210                         cls : 'btn-group btn-group-justified roo-upload-cropbox-btn-group',
211                         cn : []
212                     }
213                 }
214             ]
215         };
216         
217         return cfg;
218     },
219     
220     onRender : function(ct, position)
221     {
222         Roo.dialog.UploadCropbox.superclass.onRender.call(this, ct, position);
223
224         if(this.el){
225             if (this.el.attr('xtype')) {
226                 this.el.attr('xtypex', this.el.attr('xtype'));
227                 this.el.dom.removeAttribute('xtype');
228                 
229                 this.initEvents();
230             }
231         }
232         else {
233             var cfg = Roo.apply({},  this.getAutoCreate());
234         
235             cfg.id = this.id || Roo.id();
236             
237             if (this.cls) {
238                 cfg.cls = (typeof(cfg.cls) == 'undefined' ? this.cls : cfg.cls) + ' ' + this.cls;
239             }
240             
241             if (this.style) { // fixme needs to support more complex style data.
242                 cfg.style = (typeof(cfg.style) == 'undefined' ? this.style : cfg.style) + '; ' + this.style;
243             }
244             
245             this.el = ct.createChild(cfg, position);
246             
247             this.initEvents();
248         }
249         
250         if (this.buttons.length) {
251             
252             Roo.each(this.buttons, function(bb) {
253                 
254                 var btn = this.el.select('.roo-upload-cropbox-footer div.roo-upload-cropbox-btn-group').first().createChild(bb);
255                 
256                 btn.on('click', this.onFooterButtonClick.createDelegate(this, [bb.action], true));
257                 
258             }, this);
259         }
260         
261         if(this.loadMask){
262             this.maskEl = this.el;
263         }
264     },
265     
266     initEvents : function()
267     {
268         this.urlAPI = (window.createObjectURL && window) || 
269                                 (window.URL && URL.revokeObjectURL && URL) || 
270                                 (window.webkitURL && webkitURL);
271                         
272         this.bodyEl = this.el.select('.roo-upload-cropbox-body', true).first();
273         this.bodyEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
274         
275         this.selectorEl = this.el.select('.roo-upload-cropbox-selector', true).first();
276         this.selectorEl.hide();
277         
278         this.previewEl = this.el.select('.roo-upload-cropbox-preview', true).first();
279         this.previewEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
280         
281         this.thumbEl = this.el.select('.roo-upload-cropbox-thumb', true).first();
282         this.thumbEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
283         this.thumbEl.hide();
284         
285         this.notifyEl = this.el.select('.roo-upload-cropbox-empty-notify', true).first();
286         this.notifyEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
287         
288         this.errorEl = this.el.select('.roo-upload-cropbox-error-notify', true).first();
289         this.errorEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
290         this.errorEl.hide();
291         
292         this.footerEl = this.el.select('.roo-upload-cropbox-footer', true).first();
293         this.footerEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
294         this.footerEl.hide();
295         
296         this.setThumbBoxSize();
297         
298         this.bind();
299         
300         this.resize();
301         
302         this.fireEvent('initial', this);
303     },
304
305     bind : function()
306     {
307         var _this = this;
308         
309         window.addEventListener("resize", function() { _this.resize(); } );
310         
311         this.bodyEl.on('click', this.beforeSelectFile, this);
312         
313         if(Roo.isTouch){
314             this.bodyEl.on('touchstart', this.onTouchStart, this);
315             this.bodyEl.on('touchmove', this.onTouchMove, this);
316             this.bodyEl.on('touchend', this.onTouchEnd, this);
317         }
318         
319         if(!Roo.isTouch){
320             this.bodyEl.on('mousedown', this.onMouseDown, this);
321             this.bodyEl.on('mousemove', this.onMouseMove, this);
322             var mousewheel = (/Firefox/i.test(navigator.userAgent))? 'DOMMouseScroll' : 'mousewheel';
323             this.bodyEl.on(mousewheel, this.onMouseWheel, this);
324             Roo.get(document).on('mouseup', this.onMouseUp, this);
325         }
326         
327         this.selectorEl.on('change', this.onFileSelected, this);
328     },
329     
330     reset : function()
331     {    
332         this.scale = 0;
333         this.baseScale = 1;
334         this.rotate = 0;
335         this.baseRotate = 1;
336         this.dragable = false;
337         this.pinching = false;
338         this.mouseX = 0;
339         this.mouseY = 0;
340         this.cropData = false;
341         this.notifyEl.dom.innerHTML = this.emptyText;
342         
343         // this.selectorEl.dom.value = '';
344         
345     },
346     
347     resize : function()
348     {
349         if(this.fireEvent('resize', this) != false){
350             this.setThumbBoxPosition();
351             this.setCanvasPosition();
352         }
353     },
354     
355     onFooterButtonClick : function(e, el, o, type)
356     {
357         switch (type) {
358             case 'rotate-left' :
359                 this.onRotateLeft(e);
360                 break;
361             case 'rotate-right' :
362                 this.onRotateRight(e);
363                 break;
364             case 'picture' :
365                 this.beforeSelectFile(e);
366                 break;
367             case 'trash' :
368                 this.trash(e);
369                 break;
370             case 'crop' :
371                 this.crop(e);
372                 break;
373             case 'download' :
374                 this.download(e);
375                 break;
376             case 'center' :
377                 this.center(e);
378                 break;
379             default :
380                 break;
381         }
382         
383         this.fireEvent('footerbuttonclick', this, type);
384     },
385     
386     beforeSelectFile : function(e)
387     {
388         e.preventDefault();
389         
390         if(this.fireEvent('beforeselectfile', this) != false){
391             this.selectorEl.dom.click();
392         }
393     },
394     
395     onFileSelected : function(e)
396     {
397         e.preventDefault();
398         
399         if(typeof(this.selectorEl.dom.files) == 'undefined' || !this.selectorEl.dom.files.length){
400             return;
401         }
402         
403         var file = this.selectorEl.dom.files[0];
404         
405         if(this.fireEvent('inspect', this, file) != false){
406             this.prepare(file);
407         }
408         
409     },
410     
411     trash : function(e)
412     {
413         this.fireEvent('trash', this);
414     },
415     
416     download : function(e)
417     {
418         this.fireEvent('download', this);
419     },
420
421     center : function(e)
422     {
423         this.setCanvasPosition();
424     },
425     
426     loadCanvas : function(src)
427     {   
428         if(this.fireEvent('beforeloadcanvas', this, src) != false){
429             
430             this.reset();
431             
432             this.imageEl = document.createElement('img');
433             
434             var _this = this;
435             
436             this.imageEl.addEventListener("load", function(){ _this.onLoadCanvas(); });
437             
438             this.imageEl.src = src;
439         }
440     },
441     
442     onLoadCanvas : function()
443     {   
444         this.imageEl.OriginWidth = this.imageEl.naturalWidth || this.imageEl.width;
445         this.imageEl.OriginHeight = this.imageEl.naturalHeight || this.imageEl.height;
446
447         if(this.fireEvent('loadcanvas', this, this.imageEl) != false){
448         
449             this.bodyEl.un('click', this.beforeSelectFile, this);
450             
451             this.notifyEl.hide();
452             this.thumbEl.show();
453             this.footerEl.show();
454             
455             this.baseRotateLevel();
456             
457             if(this.isDocument){
458                 this.setThumbBoxSize();
459             }
460             
461             this.setThumbBoxPosition();
462             
463             this.baseScaleLevel();
464             
465             this.draw();
466             
467             this.resize();
468             
469             this.canvasLoaded = true;
470         
471         }
472         
473         if(this.loadMask){
474             this.maskEl.unmask();
475         }
476         
477     },
478     
479     setCanvasPosition : function(center = true)
480     {   
481         if(!this.canvasEl){
482             return;
483         }
484
485         var newCenterLeft = Math.ceil((this.bodyEl.getWidth() - this.canvasEl.width) / 2);
486         var newCenterTop = Math.ceil((this.bodyEl.getHeight() - this.canvasEl.height) / 2);
487
488         if(center) {
489             this.previewEl.setLeft(newCenterLeft);
490             this.previewEl.setTop(newCenterTop);
491
492             return;
493         }
494         
495         var oldScaleLevel = this.baseScale * Math.pow(1.02, this.startScale);
496         var oldCanvasWidth = Math.floor(this.imageEl.OriginWidth * oldScaleLevel);
497         var oldCanvasHeight = Math.floor(this.imageEl.OriginHeight * oldScaleLevel);
498
499         var oldCenterLeft = Math.ceil((this.bodyEl.getWidth() - oldCanvasWidth) / 2);
500         var oldCenterTop = Math.ceil((this.bodyEl.getHeight() - oldCanvasHeight) / 2);
501
502         var leftDiff = newCenterLeft - oldCenterLeft;
503         var topDiff = newCenterTop - oldCenterTop;
504
505         var newPreviewLeft = this.previewEl.getLeft(true) + leftDiff;
506         var newPreviewTop = this.previewEl.getTop(true) + topDiff;
507
508         this.previewEl.setLeft(newPreviewLeft);
509         this.previewEl.setTop(newPreviewTop);
510         
511     },
512     
513     onMouseDown : function(e)
514     {   
515         e.stopEvent();
516         
517         this.dragable = true;
518         this.pinching = false;
519         
520         if(this.isDocument && (this.canvasEl.width < this.thumbEl.getWidth() || this.canvasEl.height < this.thumbEl.getHeight())){
521             this.dragable = false;
522             return;
523         }
524         
525         this.mouseX = Roo.isTouch ? e.browserEvent.touches[0].pageX : e.getPageX();
526         this.mouseY = Roo.isTouch ? e.browserEvent.touches[0].pageY : e.getPageY();
527         
528     },
529     
530     onMouseMove : function(e)
531     {   
532         e.stopEvent();
533         
534         if(!this.canvasLoaded){
535             return;
536         }
537         
538         if (!this.dragable){
539             return;
540         }
541
542         var maxPaddingLeft = this.canvasEl.width / 0.9 * 0.05;
543         var maxPaddingTop = maxPaddingLeft * this.minHeight / this.minWidth;
544
545         if ((this.imageEl.OriginWidth / this.imageEl.OriginHeight <= this.minWidth / this.minHeight)) {
546             maxPaddingLeft = (this.canvasEl.height * this.minWidth / this.minHeight - this.canvasEl.width) / 2 + maxPaddingLeft;
547         }
548
549         if ((this.imageEl.OriginWidth / this.imageEl.OriginHeight >= this.minWidth / this.minHeight)) {
550             maxPaddingTop = (this.canvasEl.width * this.minHeight / this.minWidth - this.canvasEl.height) / 2 + maxPaddingTop;
551         }
552         
553         var minX = Math.ceil(this.thumbEl.getLeft(true) + this.thumbEl.getWidth() - this.canvasEl.width - maxPaddingLeft);
554         var minY = Math.ceil(this.thumbEl.getTop(true) + this.thumbEl.getHeight() - this.canvasEl.height - maxPaddingTop);
555         
556         var maxX = Math.ceil(this.thumbEl.getLeft(true) + maxPaddingLeft);
557         var maxY = Math.ceil(this.thumbEl.getTop(true) +  maxPaddingTop);
558
559         if(minX > maxX) {
560             var tempX = minX;
561             minX = maxX;
562             maxX = tempX;
563         }
564
565         if(minY > maxY) {
566             var tempY = minY;
567             minY = maxY;
568             maxY = tempY;
569         }
570
571         var x = Roo.isTouch ? e.browserEvent.touches[0].pageX : e.getPageX();
572         var y = Roo.isTouch ? e.browserEvent.touches[0].pageY : e.getPageY();
573         
574         x = x - this.mouseX;
575         y = y - this.mouseY;
576
577         var bgX = Math.ceil(x + this.previewEl.getLeft(true));
578         var bgY = Math.ceil(y + this.previewEl.getTop(true));
579         
580         bgX = (bgX < minX) ? minX : ((bgX > maxX) ? maxX : bgX);
581         bgY = (bgY < minY) ? minY : ((bgY > maxY) ? maxY : bgY);
582         
583         this.previewEl.setLeft(bgX);
584         this.previewEl.setTop(bgY);
585         
586         this.mouseX = Roo.isTouch ? e.browserEvent.touches[0].pageX : e.getPageX();
587         this.mouseY = Roo.isTouch ? e.browserEvent.touches[0].pageY : e.getPageY();
588     },
589     
590     onMouseUp : function(e)
591     {   
592         e.stopEvent();
593         
594         this.dragable = false;
595     },
596     
597     onMouseWheel : function(e)
598     {   
599         e.stopEvent();
600         
601         this.startScale = this.scale;
602         this.scale = (e.getWheelDelta() > 0) ? (this.scale + 1) : (this.scale - 1);
603         
604         if(!this.zoomable()){
605             this.scale = this.startScale;
606             return;
607         }
608
609         
610         this.draw();
611         
612         return;
613     },
614     
615     zoomable : function()
616     {
617         var minScale = this.thumbEl.getWidth() / this.minWidth;
618         
619         if(this.minWidth < this.minHeight){
620             minScale = this.thumbEl.getHeight() / this.minHeight;
621         }
622         
623         var width = Math.ceil(this.imageEl.OriginWidth * this.getScaleLevel() / minScale);
624         var height = Math.ceil(this.imageEl.OriginHeight * this.getScaleLevel() / minScale);
625  
626         var maxWidth = this.imageEl.OriginWidth;
627         var maxHeight = this.imageEl.OriginHeight;
628
629
630         var newCanvasWidth = Math.floor(this.imageEl.OriginWidth * this.getScaleLevel());
631         var newCanvasHeight = Math.floor(this.imageEl.OriginHeight * this.getScaleLevel());
632
633         var oldCenterLeft = Math.ceil((this.bodyEl.getWidth() - this.canvasEl.width) / 2);
634         var oldCenterTop = Math.ceil((this.bodyEl.getHeight() - this.canvasEl.height) / 2);
635
636         var newCenterLeft = Math.ceil((this.bodyEl.getWidth() - newCanvasWidth) / 2);
637         var newCenterTop = Math.ceil((this.bodyEl.getHeight() - newCanvasHeight) / 2);
638
639         var leftDiff = newCenterLeft - oldCenterLeft;
640         var topDiff = newCenterTop - oldCenterTop;
641
642         var newPreviewLeft = this.previewEl.getLeft(true) + leftDiff;
643         var newPreviewTop = this.previewEl.getTop(true) + topDiff;
644
645         var paddingLeft = newPreviewLeft - this.thumbEl.getLeft(true);
646         var paddingTop = newPreviewTop - this.thumbEl.getTop(true);
647
648         var paddingRight = this.thumbEl.getLeft(true) + this.thumbEl.getWidth() - newCanvasWidth - newPreviewLeft;
649         var paddingBottom = this.thumbEl.getTop(true) + this.thumbEl.getHeight() - newCanvasHeight - newPreviewTop;
650
651         var maxPaddingLeft = newCanvasWidth / 0.9 * 0.05;
652         var maxPaddingTop = maxPaddingLeft * this.minHeight / this.minWidth;
653
654         if ((this.imageEl.OriginWidth / this.imageEl.OriginHeight <= this.minWidth / this.minHeight)) {
655             maxPaddingLeft = (newCanvasHeight * this.minWidth / this.minHeight - newCanvasWidth) / 2 + maxPaddingLeft;
656         }
657
658         if ((this.imageEl.OriginWidth / this.imageEl.OriginHeight >= this.minWidth / this.minHeight)) {
659             maxPaddingTop = (newCanvasWidth * this.minHeight / this.minWidth - newCanvasHeight) / 2 + maxPaddingTop;
660         }
661         
662         if(
663                 this.isDocument &&
664                 (this.rotate == 0 || this.rotate == 180) && 
665                 (
666                     width > this.imageEl.OriginWidth || 
667                     height > this.imageEl.OriginHeight ||
668                     (width < this.minWidth && height < this.minHeight)
669                 )
670         ){
671             return false;
672         }
673         
674         if(
675                 this.isDocument &&
676                 (this.rotate == 90 || this.rotate == 270) && 
677                 (
678                     width > this.imageEl.OriginWidth || 
679                     height > this.imageEl.OriginHeight ||
680                     (width < this.minHeight && height < this.minWidth)
681                 )
682         ){
683             return false;
684         }
685         
686         if(
687                 !this.isDocument &&
688                 (this.rotate == 0 || this.rotate == 180) && 
689                 (
690                     // for zoom out
691                     paddingLeft > maxPaddingLeft ||
692                     paddingRight > maxPaddingLeft ||
693                     paddingTop > maxPaddingTop ||
694                     paddingBottom > maxPaddingTop ||
695                     // for zoom in
696                     width > maxWidth ||
697                     height > maxHeight
698                 )
699         ){
700             return false;
701         }
702         
703         if(
704                 !this.isDocument &&
705                 (this.rotate == 90 || this.rotate == 270) && 
706                 (
707                     width < this.minHeight || 
708                     width > this.imageEl.OriginWidth || 
709                     height < this.minWidth || 
710                     height > this.imageEl.OriginHeight
711                 )
712         ){
713             return false;
714         }
715         
716         return true;
717         
718     },
719     
720     onRotateLeft : function(e)
721     {   
722         if(!this.isDocument && (this.canvasEl.height < this.thumbEl.getWidth() || this.canvasEl.width < this.thumbEl.getHeight())){
723             
724             var minScale = this.thumbEl.getWidth() / this.minWidth;
725             
726             var bw = Math.ceil(this.canvasEl.width / this.getScaleLevel());
727             var bh = Math.ceil(this.canvasEl.height / this.getScaleLevel());
728             
729             this.startScale = this.scale;
730             
731             while (this.getScaleLevel() < minScale){
732             
733                 this.scale = this.scale + 1;
734                 
735                 if(!this.zoomable()){
736                     break;
737                 }
738                 
739                 if(
740                         Math.ceil(bw * this.getScaleLevel()) < this.thumbEl.getHeight() ||
741                         Math.ceil(bh * this.getScaleLevel()) < this.thumbEl.getWidth()
742                 ){
743                     continue;
744                 }
745                 
746                 this.rotate = (this.rotate < 90) ? 270 : this.rotate - 90;
747
748                 this.draw();
749                 
750                 return;
751             }
752             
753             this.scale = this.startScale;
754             
755             this.onRotateFail();
756             
757             return false;
758         }
759         
760         this.rotate = (this.rotate < 90) ? 270 : this.rotate - 90;
761
762         if(this.isDocument){
763             this.setThumbBoxSize();
764             this.setThumbBoxPosition();
765             this.setCanvasPosition();
766         }
767         
768         this.draw();
769         
770         this.fireEvent('rotate', this, 'left');
771         
772     },
773     
774     onRotateRight : function(e)
775     {
776         if(!this.isDocument && (this.canvasEl.height < this.thumbEl.getWidth() || this.canvasEl.width < this.thumbEl.getHeight())){
777             
778             var minScale = this.thumbEl.getWidth() / this.minWidth;
779         
780             var bw = Math.ceil(this.canvasEl.width / this.getScaleLevel());
781             var bh = Math.ceil(this.canvasEl.height / this.getScaleLevel());
782             
783             this.startScale = this.scale;
784             
785             while (this.getScaleLevel() < minScale){
786             
787                 this.scale = this.scale + 1;
788                 
789                 if(!this.zoomable()){
790                     break;
791                 }
792                 
793                 if(
794                         Math.ceil(bw * this.getScaleLevel()) < this.thumbEl.getHeight() ||
795                         Math.ceil(bh * this.getScaleLevel()) < this.thumbEl.getWidth()
796                 ){
797                     continue;
798                 }
799                 
800                 this.rotate = (this.rotate > 180) ? 0 : this.rotate + 90;
801
802                 this.draw();
803                 
804                 return;
805             }
806             
807             this.scale = this.startScale;
808             
809             this.onRotateFail();
810             
811             return false;
812         }
813         
814         this.rotate = (this.rotate > 180) ? 0 : this.rotate + 90;
815
816         if(this.isDocument){
817             this.setThumbBoxSize();
818             this.setThumbBoxPosition();
819             this.setCanvasPosition();
820         }
821         
822         this.draw();
823         
824         this.fireEvent('rotate', this, 'right');
825     },
826     
827     onRotateFail : function()
828     {
829         this.errorEl.show(true);
830         
831         var _this = this;
832         
833         (function() { _this.errorEl.hide(true); }).defer(this.errorTimeout);
834     },
835     
836     draw : function()
837     {
838         this.previewEl.dom.innerHTML = '';
839         
840         var canvasEl = document.createElement("canvas");
841         
842         var contextEl = canvasEl.getContext("2d");
843         
844         canvasEl.width = this.imageEl.OriginWidth * this.getScaleLevel();
845         canvasEl.height = this.imageEl.OriginWidth * this.getScaleLevel();
846         var center = this.imageEl.OriginWidth / 2;
847         
848         if(this.imageEl.OriginWidth < this.imageEl.OriginHeight){
849             canvasEl.width = this.imageEl.OriginHeight * this.getScaleLevel();
850             canvasEl.height = this.imageEl.OriginHeight * this.getScaleLevel();
851             center = this.imageEl.OriginHeight / 2;
852         }
853         
854         contextEl.scale(this.getScaleLevel(), this.getScaleLevel());
855         
856         contextEl.translate(center, center);
857         contextEl.rotate(this.rotate * Math.PI / 180);
858
859         contextEl.drawImage(this.imageEl, 0, 0, this.imageEl.OriginWidth, this.imageEl.OriginHeight, center * -1, center * -1, this.imageEl.OriginWidth, this.imageEl.OriginHeight);
860         
861         this.canvasEl = document.createElement("canvas");
862         
863         this.contextEl = this.canvasEl.getContext("2d");
864         
865         switch (this.rotate) {
866             case 0 :
867                 
868                 this.canvasEl.width = this.imageEl.OriginWidth * this.getScaleLevel();
869                 this.canvasEl.height = this.imageEl.OriginHeight * this.getScaleLevel();
870                 
871                 this.contextEl.drawImage(canvasEl, 0, 0, this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
872                 
873                 break;
874             case 90 : 
875                 
876                 this.canvasEl.width = this.imageEl.OriginHeight * this.getScaleLevel();
877                 this.canvasEl.height = this.imageEl.OriginWidth * this.getScaleLevel();
878                 
879                 if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
880                     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);
881                     break;
882                 }
883                 
884                 this.contextEl.drawImage(canvasEl, 0, 0, this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
885                 
886                 break;
887             case 180 :
888                 
889                 this.canvasEl.width = this.imageEl.OriginWidth * this.getScaleLevel();
890                 this.canvasEl.height = this.imageEl.OriginHeight * this.getScaleLevel();
891                 
892                 if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
893                     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);
894                     break;
895                 }
896                 
897                 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);
898                 
899                 break;
900             case 270 :
901                 
902                 this.canvasEl.width = this.imageEl.OriginHeight * this.getScaleLevel();
903                 this.canvasEl.height = this.imageEl.OriginWidth * this.getScaleLevel();
904         
905                 if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
906                     this.contextEl.drawImage(canvasEl, 0, 0, this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
907                     break;
908                 }
909                 
910                 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);
911                 
912                 break;
913             default : 
914                 break;
915         }
916         
917         this.previewEl.appendChild(this.canvasEl);
918         
919         this.setCanvasPosition(false);
920     },
921     
922     crop : function()
923     {
924         if(!this.canvasLoaded){
925             return;
926         }
927         
928         var imageCanvas = document.createElement("canvas");
929         
930         var imageContext = imageCanvas.getContext("2d");
931         
932         imageCanvas.width = (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? this.imageEl.OriginWidth : this.imageEl.OriginHeight;
933         imageCanvas.height = (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? this.imageEl.OriginWidth : this.imageEl.OriginHeight;
934         
935         var center = imageCanvas.width / 2;
936         
937         imageContext.translate(center, center);
938         
939         imageContext.rotate(this.rotate * Math.PI / 180);
940         
941         imageContext.drawImage(this.imageEl, 0, 0, this.imageEl.OriginWidth, this.imageEl.OriginHeight, center * -1, center * -1, this.imageEl.OriginWidth, this.imageEl.OriginHeight);
942         
943         var canvas = document.createElement("canvas");
944         
945         var context = canvas.getContext("2d");
946
947         canvas.width = this.thumbEl.getWidth() / this.getScaleLevel();
948         
949         canvas.height = this.thumbEl.getHeight() / this.getScaleLevel();
950
951         switch (this.rotate) {
952             case 0 :
953                 
954                 var width = (this.thumbEl.getWidth() / this.getScaleLevel() > this.imageEl.OriginWidth) ? this.imageEl.OriginWidth : (this.thumbEl.getWidth() / this.getScaleLevel());
955                 var height = (this.thumbEl.getHeight() / this.getScaleLevel() > this.imageEl.OriginHeight) ? this.imageEl.OriginHeight : (this.thumbEl.getHeight() / this.getScaleLevel());
956                 
957                 var x = (this.thumbEl.getLeft(true) > this.previewEl.getLeft(true)) ? 0 : ((this.previewEl.getLeft(true) - this.thumbEl.getLeft(true)) / this.getScaleLevel());
958                 var y = (this.thumbEl.getTop(true) > this.previewEl.getTop(true)) ? 0 : ((this.previewEl.getTop(true) - this.thumbEl.getTop(true)) / this.getScaleLevel());
959                 
960                 var sx = this.thumbEl.getLeft(true) - this.previewEl.getLeft(true);
961                 var sy = this.thumbEl.getTop(true) - this.previewEl.getTop(true);
962
963                 sx = sx < 0 ? 0 : (sx / this.getScaleLevel());
964                 sy = sy < 0 ? 0 : (sy / this.getScaleLevel());
965
966                 if(canvas.width > this.outputMaxWidth) {
967                     var scale = this.outputMaxWidth / canvas.width;
968                     canvas.width = canvas.width * scale;
969                     canvas.height = canvas.height * scale;
970                     context.scale(scale, scale);
971                 }
972
973                 context.fillStyle = 'white';
974                 context.fillRect(0, 0, this.thumbEl.getWidth() / this.getScaleLevel(), this.thumbEl.getHeight() / this.getScaleLevel());
975
976
977                 context.drawImage(imageCanvas, sx, sy, width, height, x, y, width, height);
978                 
979                 break;
980             case 90 : 
981                 
982                 var width = (this.thumbEl.getWidth() / this.getScaleLevel() > this.imageEl.OriginHeight) ? this.imageEl.OriginHeight : (this.thumbEl.getWidth() / this.getScaleLevel());
983                 var height = (this.thumbEl.getHeight() / this.getScaleLevel() > this.imageEl.OriginWidth) ? this.imageEl.OriginWidth : (this.thumbEl.getHeight() / this.getScaleLevel());
984                 
985                 var x = (this.thumbEl.getLeft(true) > this.previewEl.getLeft(true)) ? 0 : ((this.previewEl.getLeft(true) - this.thumbEl.getLeft(true)) / this.getScaleLevel());
986                 var y = (this.thumbEl.getTop(true) > this.previewEl.getTop(true)) ? 0 : ((this.previewEl.getTop(true) - this.thumbEl.getTop(true)) / this.getScaleLevel());
987                 
988                 var targetWidth = this.minWidth - 2 * x;
989                 var targetHeight = this.minHeight - 2 * y;
990                 
991                 var scale = 1;
992                 
993                 if((x == 0 && y == 0) || (x == 0 && y > 0)){
994                     scale = targetWidth / width;
995                 }
996                 
997                 if(x > 0 && y == 0){
998                     scale = targetHeight / height;
999                 }
1000                 
1001                 if(x > 0 && y > 0){
1002                     scale = targetWidth / width;
1003                     
1004                     if(width < height){
1005                         scale = targetHeight / height;
1006                     }
1007                 }
1008                 
1009                 context.scale(scale, scale);
1010                 
1011                 var sx = Math.min(this.canvasEl.width - this.thumbEl.getWidth(), this.thumbEl.getLeft(true) - this.previewEl.getLeft(true));
1012                 var sy = Math.min(this.canvasEl.height - this.thumbEl.getHeight(), this.thumbEl.getTop(true) - this.previewEl.getTop(true));
1013
1014                 sx = sx < 0 ? 0 : (sx / this.getScaleLevel());
1015                 sy = sy < 0 ? 0 : (sy / this.getScaleLevel());
1016                 
1017                 sx += (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? Math.abs(this.imageEl.OriginWidth - this.imageEl.OriginHeight) : 0;
1018                 
1019                 context.drawImage(imageCanvas, sx, sy, width, height, x, y, width, height);
1020                 
1021                 break;
1022             case 180 :
1023                 
1024                 var width = (this.thumbEl.getWidth() / this.getScaleLevel() > this.imageEl.OriginWidth) ? this.imageEl.OriginWidth : (this.thumbEl.getWidth() / this.getScaleLevel());
1025                 var height = (this.thumbEl.getHeight() / this.getScaleLevel() > this.imageEl.OriginHeight) ? this.imageEl.OriginHeight : (this.thumbEl.getHeight() / this.getScaleLevel());
1026                 
1027                 var x = (this.thumbEl.getLeft(true) > this.previewEl.getLeft(true)) ? 0 : ((this.previewEl.getLeft(true) - this.thumbEl.getLeft(true)) / this.getScaleLevel());
1028                 var y = (this.thumbEl.getTop(true) > this.previewEl.getTop(true)) ? 0 : ((this.previewEl.getTop(true) - this.thumbEl.getTop(true)) / this.getScaleLevel());
1029                 
1030                 var targetWidth = this.minWidth - 2 * x;
1031                 var targetHeight = this.minHeight - 2 * y;
1032                 
1033                 var scale = 1;
1034                 
1035                 if((x == 0 && y == 0) || (x == 0 && y > 0)){
1036                     scale = targetWidth / width;
1037                 }
1038                 
1039                 if(x > 0 && y == 0){
1040                     scale = targetHeight / height;
1041                 }
1042                 
1043                 if(x > 0 && y > 0){
1044                     scale = targetWidth / width;
1045                     
1046                     if(width < height){
1047                         scale = targetHeight / height;
1048                     }
1049                 }
1050                 
1051                 context.scale(scale, scale);
1052                 
1053                 var sx = Math.min(this.canvasEl.width - this.thumbEl.getWidth(), this.thumbEl.getLeft(true) - this.previewEl.getLeft(true));
1054                 var sy = Math.min(this.canvasEl.height - this.thumbEl.getHeight(), this.thumbEl.getTop(true) - this.previewEl.getTop(true));
1055
1056                 sx = sx < 0 ? 0 : (sx / this.getScaleLevel());
1057                 sy = sy < 0 ? 0 : (sy / this.getScaleLevel());
1058
1059                 sx += (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? 0 : Math.abs(this.imageEl.OriginWidth - this.imageEl.OriginHeight);
1060                 sy += (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? Math.abs(this.imageEl.OriginWidth - this.imageEl.OriginHeight) : 0;
1061                 
1062                 context.drawImage(imageCanvas, sx, sy, width, height, x, y, width, height);
1063                 
1064                 break;
1065             case 270 :
1066                 
1067                 var width = (this.thumbEl.getWidth() / this.getScaleLevel() > this.imageEl.OriginHeight) ? this.imageEl.OriginHeight : (this.thumbEl.getWidth() / this.getScaleLevel());
1068                 var height = (this.thumbEl.getHeight() / this.getScaleLevel() > this.imageEl.OriginWidth) ? this.imageEl.OriginWidth : (this.thumbEl.getHeight() / this.getScaleLevel());
1069                 
1070                 var x = (this.thumbEl.getLeft(true) > this.previewEl.getLeft(true)) ? 0 : ((this.previewEl.getLeft(true) - this.thumbEl.getLeft(true)) / this.getScaleLevel());
1071                 var y = (this.thumbEl.getTop(true) > this.previewEl.getTop(true)) ? 0 : ((this.previewEl.getTop(true) - this.thumbEl.getTop(true)) / this.getScaleLevel());
1072                 
1073                 var targetWidth = this.minWidth - 2 * x;
1074                 var targetHeight = this.minHeight - 2 * y;
1075                 
1076                 var scale = 1;
1077                 
1078                 if((x == 0 && y == 0) || (x == 0 && y > 0)){
1079                     scale = targetWidth / width;
1080                 }
1081                 
1082                 if(x > 0 && y == 0){
1083                     scale = targetHeight / height;
1084                 }
1085                 
1086                 if(x > 0 && y > 0){
1087                     scale = targetWidth / width;
1088                     
1089                     if(width < height){
1090                         scale = targetHeight / height;
1091                     }
1092                 }
1093                 
1094                 context.scale(scale, scale);
1095                 var sx = Math.min(this.canvasEl.width - this.thumbEl.getWidth(), this.thumbEl.getLeft(true) - this.previewEl.getLeft(true));
1096                 var sy = Math.min(this.canvasEl.height - this.thumbEl.getHeight(), this.thumbEl.getTop(true) - this.previewEl.getTop(true));
1097
1098                 sx = sx < 0 ? 0 : (sx / this.getScaleLevel());
1099                 sy = sy < 0 ? 0 : (sy / this.getScaleLevel());
1100                 
1101                 sy += (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? 0 : Math.abs(this.imageEl.OriginWidth - this.imageEl.OriginHeight);
1102                 
1103                 context.drawImage(imageCanvas, sx, sy, width, height, x, y, width, height);
1104                 
1105                 break;
1106             default : 
1107                 break;
1108         }
1109         
1110         this.cropData = canvas.toDataURL(this.cropType);
1111         
1112         if(this.fireEvent('crop', this, this.cropData) !== false){
1113             this.process(this.file, this.cropData);
1114         }
1115         
1116         return;
1117         
1118     },
1119     
1120     setThumbBoxSize : function()
1121     {
1122         var width, height;
1123         
1124         if(this.isDocument && typeof(this.imageEl) != 'undefined'){
1125             width = (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? Math.max(this.minWidth, this.minHeight) : Math.min(this.minWidth, this.minHeight);
1126             height = (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? Math.min(this.minWidth, this.minHeight) : Math.max(this.minWidth, this.minHeight);
1127             
1128             this.minWidth = width;
1129             this.minHeight = height;
1130             
1131             if(this.rotate == 90 || this.rotate == 270){
1132                 this.minWidth = height;
1133                 this.minHeight = width;
1134             }
1135         }
1136         
1137         height = this.windowSize;
1138         width = Math.ceil(this.minWidth * height / this.minHeight);
1139         
1140         if(this.minWidth > this.minHeight){
1141             width = this.windowSize;
1142             height = Math.ceil(this.minHeight * width / this.minWidth);
1143         }
1144         
1145         this.thumbEl.setStyle({
1146             width : width + 'px',
1147             height : height + 'px'
1148         });
1149
1150         return;
1151             
1152     },
1153     
1154     setThumbBoxPosition : function()
1155     {
1156         var x = Math.ceil((this.bodyEl.getWidth() - this.thumbEl.getWidth()) / 2 );
1157         var y = Math.ceil((this.bodyEl.getHeight() - this.thumbEl.getHeight()) / 2);
1158         
1159         this.thumbEl.setLeft(x);
1160         this.thumbEl.setTop(y);
1161         
1162     },
1163     
1164     baseRotateLevel : function()
1165     {
1166         this.baseRotate = 1;
1167         
1168         if(
1169                 typeof(this.exif) != 'undefined' &&
1170                 typeof(this.exif[Roo.dialog.UploadCropbox['tags']['Orientation']]) != 'undefined' &&
1171                 [1, 3, 6, 8].indexOf(this.exif[Roo.dialog.UploadCropbox['tags']['Orientation']]) != -1
1172         ){
1173             this.baseRotate = this.exif[Roo.dialog.UploadCropbox['tags']['Orientation']];
1174         }
1175         
1176         this.rotate = Roo.dialog.UploadCropbox['Orientation'][this.baseRotate];
1177         
1178     },
1179     
1180     baseScaleLevel : function()
1181     {
1182         var width, height;
1183         
1184         if(this.isDocument){
1185             
1186             if(this.baseRotate == 6 || this.baseRotate == 8){
1187             
1188                 height = this.thumbEl.getHeight();
1189                 this.baseScale = height / this.imageEl.OriginWidth;
1190
1191                 if(this.imageEl.OriginHeight * this.baseScale > this.thumbEl.getWidth()){
1192                     width = this.thumbEl.getWidth();
1193                     this.baseScale = width / this.imageEl.OriginHeight;
1194                 }
1195
1196                 return;
1197             }
1198
1199             height = this.thumbEl.getHeight();
1200             this.baseScale = height / this.imageEl.OriginHeight;
1201
1202             if(this.imageEl.OriginWidth * this.baseScale > this.thumbEl.getWidth()){
1203                 width = this.thumbEl.getWidth();
1204                 this.baseScale = width / this.imageEl.OriginWidth;
1205             }
1206
1207             return;
1208         }
1209         
1210         if(this.baseRotate == 6 || this.baseRotate == 8){
1211             
1212             width = this.thumbEl.getHeight();
1213             this.baseScale = width / this.imageEl.OriginHeight;
1214             
1215             if(this.imageEl.OriginHeight * this.baseScale < this.thumbEl.getWidth()){
1216                 height = this.thumbEl.getWidth();
1217                 this.baseScale = height / this.imageEl.OriginHeight;
1218             }
1219             
1220             if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
1221                 height = this.thumbEl.getWidth();
1222                 this.baseScale = height / this.imageEl.OriginHeight;
1223                 
1224                 if(this.imageEl.OriginWidth * this.baseScale < this.thumbEl.getHeight()){
1225                     width = this.thumbEl.getHeight();
1226                     this.baseScale = width / this.imageEl.OriginWidth;
1227                 }
1228             }
1229             
1230             return;
1231         }
1232         
1233         width = this.thumbEl.getWidth();
1234         this.baseScale = width / this.imageEl.OriginWidth;
1235         
1236         if(this.imageEl.OriginHeight * this.baseScale < this.thumbEl.getHeight()){
1237             height = this.thumbEl.getHeight();
1238             this.baseScale = height / this.imageEl.OriginHeight;
1239         }
1240         
1241         if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
1242             
1243             height = this.thumbEl.getHeight();
1244             this.baseScale = height / this.imageEl.OriginHeight;
1245             
1246             if(this.imageEl.OriginWidth * this.baseScale < this.thumbEl.getWidth()){
1247                 width = this.thumbEl.getWidth();
1248                 this.baseScale = width / this.imageEl.OriginWidth;
1249             }
1250             
1251         }
1252
1253         if(this.imageEl.OriginWidth < this.minWidth || this.imageEl.OriginHeight < this.minHeight) {
1254             this.baseScale = width / this.minWidth;
1255         }
1256
1257         return;
1258     },
1259     
1260     getScaleLevel : function()
1261     {
1262         return this.baseScale * Math.pow(1.02, this.scale);
1263     },
1264     
1265     onTouchStart : function(e)
1266     {
1267         if(!this.canvasLoaded){
1268             this.beforeSelectFile(e);
1269             return;
1270         }
1271         
1272         var touches = e.browserEvent.touches;
1273         
1274         if(!touches){
1275             return;
1276         }
1277         
1278         if(touches.length == 1){
1279             this.onMouseDown(e);
1280             return;
1281         }
1282         
1283         if(touches.length != 2){
1284             return;
1285         }
1286         
1287         var coords = [];
1288         
1289         for(var i = 0, finger; finger = touches[i]; i++){
1290             coords.push(finger.pageX, finger.pageY);
1291         }
1292         
1293         var x = Math.pow(coords[0] - coords[2], 2);
1294         var y = Math.pow(coords[1] - coords[3], 2);
1295         
1296         this.startDistance = Math.sqrt(x + y);
1297         
1298         this.startScale = this.scale;
1299         
1300         this.pinching = true;
1301         this.dragable = false;
1302         
1303     },
1304     
1305     onTouchMove : function(e)
1306     {
1307         if(!this.pinching && !this.dragable){
1308             return;
1309         }
1310         
1311         var touches = e.browserEvent.touches;
1312         
1313         if(!touches){
1314             return;
1315         }
1316         
1317         if(this.dragable){
1318             this.onMouseMove(e);
1319             return;
1320         }
1321         
1322         var coords = [];
1323         
1324         for(var i = 0, finger; finger = touches[i]; i++){
1325             coords.push(finger.pageX, finger.pageY);
1326         }
1327         
1328         var x = Math.pow(coords[0] - coords[2], 2);
1329         var y = Math.pow(coords[1] - coords[3], 2);
1330         
1331         this.endDistance = Math.sqrt(x + y);
1332         
1333         this.scale = this.startScale + Math.floor(Math.log(this.endDistance / this.startDistance) / Math.log(1.1));
1334         
1335         if(!this.zoomable()){
1336             this.scale = this.startScale;
1337             return;
1338         }
1339         
1340         this.draw();
1341         
1342     },
1343     
1344     onTouchEnd : function(e)
1345     {
1346         this.pinching = false;
1347         this.dragable = false;
1348         
1349     },
1350     
1351     process : function(file, crop)
1352     {
1353         if(this.loadMask){
1354             this.maskEl.mask(this.loadingText);
1355         }
1356         
1357         this.xhr = new XMLHttpRequest();
1358         
1359         file.xhr = this.xhr;
1360
1361         this.xhr.open(this.method, this.url, true);
1362         
1363         var headers = {
1364             "Accept": "application/json",
1365             "Cache-Control": "no-cache",
1366             "X-Requested-With": "XMLHttpRequest"
1367         };
1368         
1369         for (var headerName in headers) {
1370             var headerValue = headers[headerName];
1371             if (headerValue) {
1372                 this.xhr.setRequestHeader(headerName, headerValue);
1373             }
1374         }
1375         
1376         var _this = this;
1377         
1378         this.xhr.onload = function()
1379         {
1380             _this.xhrOnLoad(_this.xhr);
1381         }
1382         
1383         this.xhr.onerror = function()
1384         {
1385             _this.xhrOnError(_this.xhr);
1386         }
1387         
1388         var formData = new FormData();
1389
1390         formData.append('returnHTML', 'NO');
1391
1392         if(crop){
1393             formData.append('crop', crop);
1394             var blobBin = atob(crop.split(',')[1]);
1395             var array = [];
1396             for(var i = 0; i < blobBin.length; i++) {
1397                 array.push(blobBin.charCodeAt(i));
1398             }
1399             var croppedFile =new Blob([new Uint8Array(array)], {type: this.cropType});
1400             formData.append(this.paramName, croppedFile, file.name);
1401         }
1402         
1403         if(typeof(file.filename) != 'undefined'){
1404             formData.append('filename', file.filename);
1405         }
1406         
1407         if(typeof(file.mimetype) != 'undefined'){
1408             formData.append('mimetype', file.mimetype);
1409         }
1410
1411         if(this.fireEvent('arrange', this, formData) != false){
1412             this.xhr.send(formData);
1413         };
1414     },
1415     
1416     xhrOnLoad : function(xhr)
1417     {
1418         if(this.loadMask){
1419             this.maskEl.unmask();
1420         }
1421         
1422         if (xhr.readyState !== 4) {
1423             this.fireEvent('exception', this, xhr);
1424             return;
1425         }
1426
1427         var response = Roo.decode(xhr.responseText);
1428         
1429         if(!response.success){
1430             this.fireEvent('exception', this, xhr);
1431             return;
1432         }
1433         
1434         var response = Roo.decode(xhr.responseText);
1435         
1436         this.fireEvent('upload', this, response);
1437         
1438     },
1439     
1440     xhrOnError : function()
1441     {
1442         if(this.loadMask){
1443             this.maskEl.unmask();
1444         }
1445         
1446         Roo.log('xhr on error');
1447         
1448         var response = Roo.decode(xhr.responseText);
1449           
1450         Roo.log(response);
1451         
1452     },
1453     
1454     prepare : function(file)
1455     {   
1456         if(this.loadMask){
1457             this.maskEl.mask(this.loadingText);
1458         }
1459         
1460         this.file = false;
1461         this.exif = {};
1462         
1463         if(typeof(file) === 'string'){
1464             this.loadCanvas(file);
1465             return;
1466         }
1467         
1468         Roo.log("A");
1469         if(!file || !this.urlAPI){
1470             return;
1471         }
1472         
1473         Roo.log("B");
1474         this.file = file;
1475         if(typeof(file.type) != 'undefined' && file.type.length != 0) {
1476             this.cropType = file.type;
1477         }
1478         
1479         var _this = this;
1480         
1481         if(this.fireEvent('prepare', this, this.file) != false){
1482             
1483             var reader = new FileReader();
1484             
1485             reader.onload = function (e) {
1486                 if (e.target.error) {
1487                     Roo.log(e.target.error);
1488                     return;
1489                 }
1490                 
1491                 var buffer = e.target.result,
1492                     dataView = new DataView(buffer),
1493                     offset = 2,
1494                     maxOffset = dataView.byteLength - 4,
1495                     markerBytes,
1496                     markerLength;
1497                 
1498                 if (dataView.getUint16(0) === 0xffd8) {
1499                     while (offset < maxOffset) {
1500                         markerBytes = dataView.getUint16(offset);
1501                         
1502                         if ((markerBytes >= 0xffe0 && markerBytes <= 0xffef) || markerBytes === 0xfffe) {
1503                             markerLength = dataView.getUint16(offset + 2) + 2;
1504                             if (offset + markerLength > dataView.byteLength) {
1505                                 Roo.log('Invalid meta data: Invalid segment size.');
1506                                 break;
1507                             }
1508                             
1509                             if(markerBytes == 0xffe1){
1510                                 _this.parseExifData(
1511                                     dataView,
1512                                     offset,
1513                                     markerLength
1514                                 );
1515                             }
1516                             
1517                             offset += markerLength;
1518                             
1519                             continue;
1520                         }
1521                         
1522                         break;
1523                     }
1524                     
1525                 }
1526                 
1527                 Roo.log("C");
1528                 var url = _this.urlAPI.createObjectURL(_this.file);
1529                 
1530                 Roo.log("D");
1531                 _this.loadCanvas(url);
1532                 
1533                 return;
1534             }
1535             
1536             reader.readAsArrayBuffer(this.file);
1537             
1538         }
1539         
1540     },
1541     
1542     parseExifData : function(dataView, offset, length)
1543     {
1544         var tiffOffset = offset + 10,
1545             littleEndian,
1546             dirOffset;
1547     
1548         if (dataView.getUint32(offset + 4) !== 0x45786966) {
1549             // No Exif data, might be XMP data instead
1550             return;
1551         }
1552         
1553         // Check for the ASCII code for "Exif" (0x45786966):
1554         if (dataView.getUint32(offset + 4) !== 0x45786966) {
1555             // No Exif data, might be XMP data instead
1556             return;
1557         }
1558         if (tiffOffset + 8 > dataView.byteLength) {
1559             Roo.log('Invalid Exif data: Invalid segment size.');
1560             return;
1561         }
1562         // Check for the two null bytes:
1563         if (dataView.getUint16(offset + 8) !== 0x0000) {
1564             Roo.log('Invalid Exif data: Missing byte alignment offset.');
1565             return;
1566         }
1567         // Check the byte alignment:
1568         switch (dataView.getUint16(tiffOffset)) {
1569         case 0x4949:
1570             littleEndian = true;
1571             break;
1572         case 0x4D4D:
1573             littleEndian = false;
1574             break;
1575         default:
1576             Roo.log('Invalid Exif data: Invalid byte alignment marker.');
1577             return;
1578         }
1579         // Check for the TIFF tag marker (0x002A):
1580         if (dataView.getUint16(tiffOffset + 2, littleEndian) !== 0x002A) {
1581             Roo.log('Invalid Exif data: Missing TIFF marker.');
1582             return;
1583         }
1584         // Retrieve the directory offset bytes, usually 0x00000008 or 8 decimal:
1585         dirOffset = dataView.getUint32(tiffOffset + 4, littleEndian);
1586         
1587         this.parseExifTags(
1588             dataView,
1589             tiffOffset,
1590             tiffOffset + dirOffset,
1591             littleEndian
1592         );
1593     },
1594     
1595     parseExifTags : function(dataView, tiffOffset, dirOffset, littleEndian)
1596     {
1597         var tagsNumber,
1598             dirEndOffset,
1599             i;
1600         if (dirOffset + 6 > dataView.byteLength) {
1601             Roo.log('Invalid Exif data: Invalid directory offset.');
1602             return;
1603         }
1604         tagsNumber = dataView.getUint16(dirOffset, littleEndian);
1605         dirEndOffset = dirOffset + 2 + 12 * tagsNumber;
1606         if (dirEndOffset + 4 > dataView.byteLength) {
1607             Roo.log('Invalid Exif data: Invalid directory size.');
1608             return;
1609         }
1610         for (i = 0; i < tagsNumber; i += 1) {
1611             this.parseExifTag(
1612                 dataView,
1613                 tiffOffset,
1614                 dirOffset + 2 + 12 * i, // tag offset
1615                 littleEndian
1616             );
1617         }
1618         // Return the offset to the next directory:
1619         return dataView.getUint32(dirEndOffset, littleEndian);
1620     },
1621     
1622     parseExifTag : function (dataView, tiffOffset, offset, littleEndian) 
1623     {
1624         var tag = dataView.getUint16(offset, littleEndian);
1625         
1626         this.exif[tag] = this.getExifValue(
1627             dataView,
1628             tiffOffset,
1629             offset,
1630             dataView.getUint16(offset + 2, littleEndian), // tag type
1631             dataView.getUint32(offset + 4, littleEndian), // tag length
1632             littleEndian
1633         );
1634     },
1635     
1636     getExifValue : function (dataView, tiffOffset, offset, type, length, littleEndian)
1637     {
1638         var tagType = Roo.dialog.UploadCropbox.exifTagTypes[type],
1639             tagSize,
1640             dataOffset,
1641             values,
1642             i,
1643             str,
1644             c;
1645     
1646         if (!tagType) {
1647             Roo.log('Invalid Exif data: Invalid tag type.');
1648             return;
1649         }
1650         
1651         tagSize = tagType.size * length;
1652         // Determine if the value is contained in the dataOffset bytes,
1653         // or if the value at the dataOffset is a pointer to the actual data:
1654         dataOffset = tagSize > 4 ?
1655                 tiffOffset + dataView.getUint32(offset + 8, littleEndian) : (offset + 8);
1656         if (dataOffset + tagSize > dataView.byteLength) {
1657             Roo.log('Invalid Exif data: Invalid data offset.');
1658             return;
1659         }
1660         if (length === 1) {
1661             return tagType.getValue(dataView, dataOffset, littleEndian);
1662         }
1663         values = [];
1664         for (i = 0; i < length; i += 1) {
1665             values[i] = tagType.getValue(dataView, dataOffset + i * tagType.size, littleEndian);
1666         }
1667         
1668         if (tagType.ascii) {
1669             str = '';
1670             // Concatenate the chars:
1671             for (i = 0; i < values.length; i += 1) {
1672                 c = values[i];
1673                 // Ignore the terminating NULL byte(s):
1674                 if (c === '\u0000') {
1675                     break;
1676                 }
1677                 str += c;
1678             }
1679             return str;
1680         }
1681         return values;
1682     }
1683     
1684 });
1685
1686 Roo.apply(Roo.dialog.UploadCropbox, {
1687     tags : {
1688         'Orientation': 0x0112
1689     },
1690     
1691     Orientation: {
1692             1: 0, //'top-left',
1693 //            2: 'top-right',
1694             3: 180, //'bottom-right',
1695 //            4: 'bottom-left',
1696 //            5: 'left-top',
1697             6: 90, //'right-top',
1698 //            7: 'right-bottom',
1699             8: 270 //'left-bottom'
1700     },
1701     
1702     exifTagTypes : {
1703         // byte, 8-bit unsigned int:
1704         1: {
1705             getValue: function (dataView, dataOffset) {
1706                 return dataView.getUint8(dataOffset);
1707             },
1708             size: 1
1709         },
1710         // ascii, 8-bit byte:
1711         2: {
1712             getValue: function (dataView, dataOffset) {
1713                 return String.fromCharCode(dataView.getUint8(dataOffset));
1714             },
1715             size: 1,
1716             ascii: true
1717         },
1718         // short, 16 bit int:
1719         3: {
1720             getValue: function (dataView, dataOffset, littleEndian) {
1721                 return dataView.getUint16(dataOffset, littleEndian);
1722             },
1723             size: 2
1724         },
1725         // long, 32 bit int:
1726         4: {
1727             getValue: function (dataView, dataOffset, littleEndian) {
1728                 return dataView.getUint32(dataOffset, littleEndian);
1729             },
1730             size: 4
1731         },
1732         // rational = two long values, first is numerator, second is denominator:
1733         5: {
1734             getValue: function (dataView, dataOffset, littleEndian) {
1735                 return dataView.getUint32(dataOffset, littleEndian) /
1736                     dataView.getUint32(dataOffset + 4, littleEndian);
1737             },
1738             size: 8
1739         },
1740         // slong, 32 bit signed int:
1741         9: {
1742             getValue: function (dataView, dataOffset, littleEndian) {
1743                 return dataView.getInt32(dataOffset, littleEndian);
1744             },
1745             size: 4
1746         },
1747         // srational, two slongs, first is numerator, second is denominator:
1748         10: {
1749             getValue: function (dataView, dataOffset, littleEndian) {
1750                 return dataView.getInt32(dataOffset, littleEndian) /
1751                     dataView.getInt32(dataOffset + 4, littleEndian);
1752             },
1753             size: 8
1754         }
1755     },
1756     
1757     footer : {
1758         STANDARD : [
1759             {
1760                 tag : 'div',
1761                 cls : 'btn-group roo-upload-cropbox-rotate-left',
1762                 action : 'rotate-left',
1763                 cn : [
1764                     {
1765                         tag : 'button',
1766                         cls : 'btn btn-default',
1767                         html : '<i class="fa fa-undo"></i>'
1768                     }
1769                 ]
1770             },
1771             {
1772                 tag : 'div',
1773                 cls : 'btn-group roo-upload-cropbox-picture',
1774                 action : 'picture',
1775                 cn : [
1776                     {
1777                         tag : 'button',
1778                         cls : 'btn btn-default',
1779                         html : '<i class="fa fa-picture-o"></i>'
1780                     }
1781                 ]
1782             },
1783             {
1784                 tag : 'div',
1785                 cls : 'btn-group roo-upload-cropbox-rotate-right',
1786                 action : 'rotate-right',
1787                 cn : [
1788                     {
1789                         tag : 'button',
1790                         cls : 'btn btn-default',
1791                         html : '<i class="fa fa-repeat"></i>'
1792                     }
1793                 ]
1794             }
1795         ],
1796         DOCUMENT : [
1797             {
1798                 tag : 'div',
1799                 cls : 'btn-group roo-upload-cropbox-rotate-left',
1800                 action : 'rotate-left',
1801                 cn : [
1802                     {
1803                         tag : 'button',
1804                         cls : 'btn btn-default',
1805                         html : '<i class="fa fa-undo"></i>'
1806                     }
1807                 ]
1808             },
1809             {
1810                 tag : 'div',
1811                 cls : 'btn-group roo-upload-cropbox-download',
1812                 action : 'download',
1813                 cn : [
1814                     {
1815                         tag : 'button',
1816                         cls : 'btn btn-default',
1817                         html : '<i class="fa fa-download"></i>'
1818                     }
1819                 ]
1820             },
1821             {
1822                 tag : 'div',
1823                 cls : 'btn-group roo-upload-cropbox-crop',
1824                 action : 'crop',
1825                 cn : [
1826                     {
1827                         tag : 'button',
1828                         cls : 'btn btn-default',
1829                         html : '<i class="fa fa-crop"></i>'
1830                     }
1831                 ]
1832             },
1833             {
1834                 tag : 'div',
1835                 cls : 'btn-group roo-upload-cropbox-trash',
1836                 action : 'trash',
1837                 cn : [
1838                     {
1839                         tag : 'button',
1840                         cls : 'btn btn-default',
1841                         html : '<i class="fa fa-trash"></i>'
1842                     }
1843                 ]
1844             },
1845             {
1846                 tag : 'div',
1847                 cls : 'btn-group roo-upload-cropbox-rotate-right',
1848                 action : 'rotate-right',
1849                 cn : [
1850                     {
1851                         tag : 'button',
1852                         cls : 'btn btn-default',
1853                         html : '<i class="fa fa-repeat"></i>'
1854                     }
1855                 ]
1856             }
1857         ],
1858         ROTATOR : [
1859             {
1860                 tag : 'div',
1861                 cls : 'btn-group roo-upload-cropbox-rotate-left',
1862                 action : 'rotate-left',
1863                 cn : [
1864                     {
1865                         tag : 'button',
1866                         cls : 'btn btn-default',
1867                         html : '<i class="fa fa-undo"></i>'
1868                     }
1869                 ]
1870             },
1871             {
1872                 tag : 'div',
1873                 cls : 'btn-group roo-upload-cropbox-rotate-right',
1874                 action : 'rotate-right',
1875                 cn : [
1876                     {
1877                         tag : 'button',
1878                         cls : 'btn btn-default',
1879                         html : '<i class="fa fa-repeat"></i>'
1880                     }
1881                 ]
1882             }
1883         ],
1884         CENTER : [
1885             {
1886                 tag : 'div',
1887                 cls : 'btn-group roo-upload-cropbox-center',
1888                 action : 'center',
1889                 cn : [
1890                     {
1891                         tag : 'button',
1892                         cls : 'btn btn-default',
1893                         html : 'CENTER'
1894                     }
1895                 ]
1896             }
1897         ]
1898     }
1899 });