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