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