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