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