piskel/build/closure/closure_compiled_binary.js
2014-05-08 01:41:14 +02:00

216 lines
136 KiB
JavaScript

var Constants={DEFAULT:{HEIGHT:32,WIDTH:32,FPS:12},MODEL_VERSION:2,MAX_HEIGHT:1024,MAX_WIDTH:1024,MINIMUM_ZOOM:1,PREVIEW_FILM_SIZE:120,ANIMATED_PREVIEW_WIDTH:200,DEFAULT_PEN_COLOR:"#000000",TRANSPARENT_COLOR:"rgba(0, 0, 0, 0)",NO_PALETTE_ID:"__no-palette",PREFERRED_COLOR_FORMAT:"rgb",SELECTION_TRANSPARENT_COLOR:"rgba(255, 255, 255, 0.6)",TOOL_TARGET_HIGHLIGHT_COLOR:"rgba(255, 255, 255, 0.2)",STATIC:{URL:{SAVE:"http://3.piskel-app.appspot.com/store",GET:"http://3.piskel-app.appspot.com/get"}},APPENGINE:{URL:{SAVE:"save"}},
IMAGE_SERVICE_UPLOAD_URL:"http://piskel-imgstore-a.appspot.com/__/upload",IMAGE_SERVICE_GET_URL:"http://piskel-imgstore-a.appspot.com/img/",ZOOMED_OUT_BACKGROUND_COLOR:"#A0A0A0",LEFT_BUTTON:0,MIDDLE_BUTTON:1,RIGHT_BUTTON:2,MOUSEMOVE_THROTTLING:10,ABSTRACT_FUNCTION:function(){throw"abstract method should be implemented";}};var Events={TOOL_SELECTED:"TOOL_SELECTED",TOOL_RELEASED:"TOOL_RELEASED",SELECT_PRIMARY_COLOR:"SELECT_PRIMARY_COLOR",SELECT_SECONDARY_COLOR:"SELECT_SECONDARY_COLOR",PRIMARY_COLOR_SELECTED:"PRIMARY_COLOR_SELECTED",SECONDARY_COLOR_SELECTED:"SECONDARY_COLOR_SELECTED",CURSOR_MOVED:"CURSOR_MOVED",DRAG_START:"DRAG_START",DRAG_END:"DRAG_END",DIALOG_DISPLAY:"DIALOG_DISPLAY",DIALOG_HIDE:"DIALOG_HIDE",PALETTE_LIST_UPDATED:"PALETTE_LIST_UPDATED",USER_SETTINGS_CHANGED:"USER_SETTINGS_CHANGED",CLOSE_SETTINGS_DRAWER:"CLOSE_SETTINGS_DRAWER",
PISKEL_RESET:"PISKEL_RESET",PISKEL_SAVE_STATE:"PISKEL_SAVE_STATE",PISKEL_SAVED:"PISKEL_SAVED",FRAME_SIZE_CHANGED:"FRAME_SIZE_CHANGED",SELECTION_CREATED:"SELECTION_CREATED",SELECTION_MOVE_REQUEST:"SELECTION_MOVE_REQUEST",SELECTION_DISMISSED:"SELECTION_DISMISSED",SHOW_NOTIFICATION:"SHOW_NOTIFICATION",HIDE_NOTIFICATION:"HIDE_NOTIFICATION",ZOOM_CHANGED:"ZOOM_CHANGED"};(function(){$.namespace("pskl").app={init:function(){this.isAppEngineVersion=!!pskl.appEngineToken_;this.shortcutService=new pskl.service.keyboard.ShortcutService;this.shortcutService.init();var a=this.readSizeFromURL_(),b=new pskl.model.piskel.Descriptor("New Piskel",""),b=new pskl.model.Piskel(a.width,a.height,b),c=new pskl.model.Layer("Layer 1"),a=new pskl.model.Frame(a.width,a.height);c.addFrame(a);b.addLayer(c);this.corePiskelController=new pskl.controller.piskel.PiskelController(b);this.corePiskelController.init();
this.piskelController=new pskl.controller.piskel.PublicPiskelController(this.corePiskelController);this.piskelController.init();this.paletteController=new pskl.controller.PaletteController;this.paletteController.init();this.palettesListController=new pskl.controller.PalettesListController;this.palettesListController.init();this.cursorCoordinatesController=new pskl.controller.CursorCoordinatesController(this.piskelController);this.cursorCoordinatesController.init();this.drawingController=new pskl.controller.DrawingController(this.piskelController,
this.paletteController,$("#drawing-canvas-container"));this.drawingController.init();this.animationController=new pskl.controller.AnimatedPreviewController(this.piskelController,$("#preview-canvas-container"));this.animationController.init();this.minimapController=new pskl.controller.MinimapController(this.piskelController,this.animationController,this.drawingController,$("#preview-canvas-container"));this.minimapController.init();this.previewsController=new pskl.controller.PreviewFilmController(this.piskelController,
$("#preview-list"));this.previewsController.init();this.layersListController=new pskl.controller.LayersListController(this.piskelController);this.layersListController.init();this.settingsController=new pskl.controller.settings.SettingsController(this.piskelController);this.settingsController.init();this.dialogsController=new pskl.controller.dialogs.DialogsController(this.piskelController);this.dialogsController.init();this.toolController=new pskl.controller.ToolController;this.toolController.init();
this.selectionManager=new pskl.selection.SelectionManager(this.piskelController);this.selectionManager.init();this.historyService=new pskl.service.HistoryService(this.corePiskelController);this.historyService.init();this.notificationController=new pskl.controller.NotificationController;this.notificationController.init();this.localStorageService=new pskl.service.LocalStorageService(this.piskelController);this.localStorageService.init();this.imageUploadService=new pskl.service.ImageUploadService;this.imageUploadService.init();
this.cheatsheetService=new pskl.service.keyboard.CheatsheetService;this.cheatsheetService.init();this.savedStatusService=new pskl.service.SavedStatusService(this.piskelController);this.savedStatusService.init();this.storageService=this.isAppEngineVersion?new pskl.service.AppEngineStorageService(this.piskelController):new pskl.service.GithubStorageService(this.piskelController);this.storageService.init();a=new pskl.rendering.DrawingLoop;a.addCallback(this.render,this);a.start();this.initTooltips_();
this.isAppEngineVersion?this.finishInitAppEngine_():this.finishInitGithub_()},finishInitGithub_:function(){var a=this.readFramesheetIdFromURL_();a&&($.publish(Events.SHOW_NOTIFICATION,[{content:"Loading animation with id : ["+a+"]"}]),this.loadFramesheetFromService(a))},finishInitAppEngine_:function(){pskl.appEnginePiskelData_&&pskl.appEnginePiskelData_.piskel&&pskl.utils.serialization.Deserializer.deserialize(pskl.appEnginePiskelData_.piskel,function(a){a.setDescriptor(pskl.appEnginePiskelData_.descriptor);
pskl.app.piskelController.setPiskel(a);pskl.app.animationController.setFPS(pskl.appEnginePiskelData_.fps)})},isLoggedIn:function(){return pskl.appEnginePiskelData_&&pskl.appEnginePiskelData_.isLoggedIn},initTooltips_:function(){$("body").tooltip({selector:"[rel=tooltip]"})},render:function(a){this.drawingController.render(a);this.animationController.render(a);this.previewsController.render(a)},readSizeFromURL_:function(){var a,b=this.readUrlParameter_("size").split("x");!b||2!=b.length||isNaN(b[0])||
isNaN(b[1])?a={height:Constants.DEFAULT.HEIGHT,width:Constants.DEFAULT.WIDTH}:(a=parseInt(b[0],10),b=parseInt(b[1],10),a={height:Math.min(b,Constants.MAX_HEIGHT),width:Math.min(a,Constants.MAX_WIDTH)});return a},readFramesheetIdFromURL_:function(){return this.readUrlParameter_("frameId")},readUrlParameter_:function(a){for(var b=window.location.search.substring(1).split("&"),c=0;c<b.length;c++){var d=b[c].split("=");if(d[0]==a)return window.unescape(d[1])}return""},loadFramesheetFromService:function(a){var b=
new XMLHttpRequest;b.open("GET",Constants.STATIC.URL.GET+"?l="+a,!0);b.responseType="text";b.onload=function(b){var a=JSON.parse(this.responseText);pskl.utils.serialization.Deserializer.deserialize(a.framesheet,function(b){pskl.app.piskelController.setPiskel(b);pskl.app.animationController.setFPS(a.fps);$.publish(Events.HIDE_NOTIFICATION)})};b.onerror=function(){$.publish(Events.HIDE_NOTIFICATION)};b.send()},store:function(a){this.storageService.store(a)},getFirstFrameAsPng:function(){var a=this.piskelController.getFrameAt(0),
a=new pskl.rendering.CanvasRenderer(a,1);a.drawTransparentAs("rgba(0,0,0,0)");return a.render().toDataURL("image/png")},getFramesheetAsPng:function(){return(new pskl.rendering.PiskelRenderer(this.piskelController)).renderAsCanvas().toDataURL("image/png")},uploadAsSpritesheetPNG:function(){var a=this.getFramesheetAsPng();this.imageUploadService.upload(a,this.openWindow.bind(this))},openWindow:function(a){var b=["dialog=yes,scrollbars=no,status=no","width="+this.piskelController.getWidth()*this.piskelController.getFrameCount(),
"height="+this.piskelController.getHeight()].join();window.open(a,"piskel-export",b)}}})();(function(){var a=$.namespace("pskl.controller");a.AnimatedPreviewController=function(b,c){this.piskelController=b;this.container=c;this.currentIndex=this.elapsedTime=0;this.setFPS(Constants.DEFAULT.FPS);var a=this.calculateZoom_(),e=this.piskelController.getCurrentFrame(),a={zoom:a,height:e.getHeight()*a,width:e.getWidth()*a};this.renderer=new pskl.rendering.frame.FrameRenderer(this.container,a);$.subscribe(Events.FRAME_SIZE_CHANGED,this.onFrameSizeChange_.bind(this))};a.AnimatedPreviewController.prototype.init=
function(){$("#preview-fps")[0].addEventListener("change",this.onFPSSliderChange.bind(this));document.querySelector(".right-column").style.width=Constants.ANIMATED_PREVIEW_WIDTH+"px"};a.AnimatedPreviewController.prototype.onFPSSliderChange=function(b){this.setFPS(parseInt($("#preview-fps")[0].value,10))};a.AnimatedPreviewController.prototype.setFPS=function(b){this.fps=b;$("#preview-fps").val(this.fps);$("#display-fps").html(this.fps+" FPS")};a.AnimatedPreviewController.prototype.getFPS=function(){return this.fps};
a.AnimatedPreviewController.prototype.render=function(b){this.elapsedTime+=b;b=Math.floor(this.elapsedTime/(1E3/this.fps));b!=this.currentIndex&&(this.currentIndex=b,this.piskelController.hasFrameAt(this.currentIndex)||(this.elapsedTime=this.currentIndex=0),this.renderer.render(this.piskelController.getFrameAt(this.currentIndex)))};a.AnimatedPreviewController.prototype.calculateZoom_=function(){var b=this.piskelController.getCurrentFrame(),c=200/b.getHeight(),b=200/b.getWidth();return Math.min(c,
b)};a.AnimatedPreviewController.prototype.onFrameSizeChange_=function(){var b=this.piskelController.getCurrentFrame(),c=this.calculateZoom_();this.renderer.setDisplaySize(b.getWidth()*c,b.getHeight()*c);this.renderer.setZoom(c);this.renderer.setOffset(0,0)}})();(function(){var a=$.namespace("pskl.controller");a.CursorCoordinatesController=function(b){this.piskelController=b;this.origin=null;this.coordinates={x:-1,y:-1}};a.CursorCoordinatesController.prototype.init=function(){this.coordinatesContainer=document.querySelector(".cursor-coordinates");$.subscribe(Events.CURSOR_MOVED,this.onCursorMoved_.bind(this));$.subscribe(Events.DRAG_START,this.onDragStart_.bind(this));$.subscribe(Events.DRAG_END,this.onDragEnd_.bind(this));$.subscribe(Events.FRAME_SIZE_CHANGED,
this.redraw.bind(this));this.redraw()};a.CursorCoordinatesController.prototype.redraw=function(){var b="";this.origin&&(b+=this.origin.x+":"+this.origin.y+" to ");var c=this.coordinates.x,a=this.coordinates.y;this.piskelController.getCurrentFrame().containsPixel(c,a)&&(b+=c+":"+a,this.origin&&(c=Math.abs(c-this.origin.x)+1,a=Math.abs(a-this.origin.y)+1,b+=" ("+c+"x"+a+")"));this.coordinatesContainer.innerHTML=this.getFrameSizeHTML_()+b};a.CursorCoordinatesController.prototype.getFrameSizeHTML_=function(){var b=
this.piskelController.getWidth(),c=this.piskelController.getHeight();return"["+b+"x"+c+"] "};a.CursorCoordinatesController.prototype.onCursorMoved_=function(b,c,a){this.coordinates={x:c,y:a};this.redraw()};a.CursorCoordinatesController.prototype.onDragStart_=function(b,c,a){this.origin={x:c,y:a};this.redraw()};a.CursorCoordinatesController.prototype.onDragEnd_=function(b,c,a){this.origin=null;this.redraw()}})();(function(){var a=$.namespace("pskl.controller");a.DrawingController=function(b,c,a){this.piskelController=b;this.paletteController=c;this.overlayFrame=pskl.model.Frame.createEmptyFromFrame(b.getCurrentFrame());this.container=a;c={zoom:this.calculateZoom_(),supportGridRendering:!0,height:this.getContainerHeight_(),width:this.getContainerWidth_(),xOffset:0,yOffset:0};this.overlayRenderer=new pskl.rendering.frame.CachedFrameRenderer(this.container,c,["canvas-overlay"]);this.renderer=new pskl.rendering.frame.CachedFrameRenderer(this.container,
c,["drawing-canvas"]);this.layersRenderer=new pskl.rendering.layer.LayersRenderer(this.container,c,b);this.compositeRenderer=new pskl.rendering.CompositeRenderer;this.compositeRenderer.add(this.overlayRenderer).add(this.renderer).add(this.layersRenderer);this.isClicked=!1;this.previousMousemoveTime=0;this.currentToolBehavior=null;this.currentMouseButton_=Constants.LEFT_BUTTON};a.DrawingController.prototype.init=function(){this.initMouseBehavior();$.subscribe(Events.TOOL_SELECTED,$.proxy(function(b,
c){this.currentToolBehavior=c;this.overlayFrame.clear()},this));$(window).resize($.proxy(this.startResizeTimer_,this));$.subscribe(Events.USER_SETTINGS_CHANGED,$.proxy(this.onUserSettingsChange_,this));$.subscribe(Events.FRAME_SIZE_CHANGED,$.proxy(this.onFrameSizeChanged_,this));window.setTimeout(this.afterWindowResize_.bind(this),100)};a.DrawingController.prototype.initMouseBehavior=function(){var b=$("body");this.container.mousedown($.proxy(this.onMousedown_,this));if(pskl.utils.UserAgent.isChrome)this.container.on("mousewheel",
$.proxy(this.onMousewheel_,this));else this.container.on("wheel",$.proxy(this.onMousewheel_,this));window.addEventListener("mouseup",this.onMouseup_.bind(this));window.addEventListener("mousemove",this.onMousemove_.bind(this));b.contextmenu(this.onCanvasContextMenu_)};a.DrawingController.prototype.startResizeTimer_=function(){this.resizeTimer&&window.clearInterval(this.resizeTimer);this.resizeTimer=window.setTimeout($.proxy(this.afterWindowResize_,this),200)};a.DrawingController.prototype.afterWindowResize_=
function(){var b=this.compositeRenderer.getDisplaySize().width;this.compositeRenderer.setDisplaySize(this.getContainerWidth_(),this.getContainerHeight_());this.centerColumnWrapperHorizontally_();b=this.compositeRenderer.getDisplaySize().width/b*this.compositeRenderer.getZoom();this.compositeRenderer.setZoom(b);$.publish(Events.ZOOM_CHANGED)};a.DrawingController.prototype.onUserSettingsChange_=function(b,c,a){c==pskl.UserSettings.SHOW_GRID&&console.warn("DrawingController:onUserSettingsChange_ not implemented !")};
a.DrawingController.prototype.onFrameSizeChanged_=function(){this.compositeRenderer.setDisplaySize(this.getContainerWidth_(),this.getContainerHeight_());this.compositeRenderer.setZoom(this.calculateZoom_());this.compositeRenderer.setOffset(0,0);$.publish(Events.ZOOM_CHANGED)};a.DrawingController.prototype.onMousedown_=function(b){var c=this.piskelController.getCurrentFrame(),a=this.renderer.getCoordinates(b.clientX,b.clientY);b.button===Constants.MIDDLE_BUTTON?c.containsPixel(a.x,a.y)&&$.publish(Events.SELECT_PRIMARY_COLOR,
[c.getPixel(a.x,a.y)]):(this.isClicked=!0,this.setCurrentButton(b),this.currentToolBehavior.hideHighlightedPixel(this.overlayFrame),this.currentToolBehavior.applyToolAt(a.x,a.y,this.getCurrentColor_(),c,this.overlayFrame,b))};a.DrawingController.prototype.onMousemove_=function(b){var c=(new Date).getTime();if(c-this.previousMousemoveTime>Constants.MOUSEMOVE_THROTTLING){var a=this.renderer.getCoordinates(b.clientX,b.clientY),e=this.piskelController.getCurrentFrame();this.isClicked?this.currentToolBehavior.moveToolAt(a.x,
a.y,this.getCurrentColor_(b),e,this.overlayFrame,b):this.currentToolBehavior.moveUnactiveToolAt(a.x,a.y,this.getCurrentColor_(b),e,this.overlayFrame,b);$.publish(Events.CURSOR_MOVED,[a.x,a.y]);this.previousMousemoveTime=c}};a.DrawingController.prototype.onMousewheel_=function(b){b=b.originalEvent;b=b.wheelDeltaY||-2*b.deltaY;var c=this.renderer.getZoom(),a=this.calculateZoom_()/10;0<b?this.compositeRenderer.setZoom(c+a):0>b&&this.compositeRenderer.setZoom(c-a);$.publish(Events.ZOOM_CHANGED)};a.DrawingController.prototype.onMouseup_=
function(b){if(this.isClicked){this.isClicked=!1;this.setCurrentButton(b);var c=this.renderer.getCoordinates(b.clientX,b.clientY);this.currentToolBehavior.releaseToolAt(c.x,c.y,this.getCurrentColor_(),this.piskelController.getCurrentFrame(),this.overlayFrame,b);$.publish(Events.TOOL_RELEASED)}};a.DrawingController.prototype.getSpriteCoordinates=function(b){return this.renderer.getCoordinates(b.clientX,b.clientY)};a.DrawingController.prototype.setCurrentButton=function(b){this.currentMouseButton_=
b.button};a.DrawingController.prototype.getCurrentColor_=function(){return this.currentMouseButton_==Constants.RIGHT_BUTTON?this.paletteController.getSecondaryColor():this.currentMouseButton_==Constants.LEFT_BUTTON?this.paletteController.getPrimaryColor():Constants.DEFAULT_PEN_COLOR};a.DrawingController.prototype.onCanvasContextMenu_=function(b){if($(b.target).closest("#drawing-canvas-container").length)return b.preventDefault(),b.stopPropagation(),b.cancelBubble=!0,!1};a.DrawingController.prototype.render=
function(){var b=this.piskelController.getCurrentFrame();b.isSameSize(this.overlayFrame)||(this.overlayFrame=pskl.model.Frame.createEmptyFromFrame(b));this.layersRenderer.render();this.renderer.render(b);this.overlayRenderer.render(this.overlayFrame)};a.DrawingController.prototype.calculateZoom_=function(){var b=this.piskelController.getCurrentFrame().getHeight(),c=this.piskelController.getCurrentFrame().getWidth();return Math.min(this.getAvailableWidth_()/c,this.getAvailableHeight_()/b)};a.DrawingController.prototype.getAvailableHeight_=
function(){return $("#main-wrapper").height()};a.DrawingController.prototype.getAvailableWidth_=function(){var b=$(".left-column").outerWidth(!0),c=$(".right-column").outerWidth(!0),a=$("#tool-section").outerWidth(!0),e=$("#application-action-section").outerWidth(!0);return $("#main-wrapper").width()-b-c-a-e-10};a.DrawingController.prototype.getContainerHeight_=function(){return this.calculateZoom_()*this.piskelController.getCurrentFrame().getHeight()};a.DrawingController.prototype.getContainerWidth_=
function(){return this.calculateZoom_()*this.piskelController.getCurrentFrame().getWidth()};a.DrawingController.prototype.centerColumnWrapperHorizontally_=function(){var b=this.getContainerHeight_(),b=Math.floor(($("#main-wrapper").height()-b)/2);$("#column-wrapper").css({top:b+"px"})};a.DrawingController.prototype.getRenderer=function(){return this.compositeRenderer};a.DrawingController.prototype.setOffset=function(b,c){this.compositeRenderer.setOffset(b,c);$.publish(Events.ZOOM_CHANGED)}})();(function(){var a=$.namespace("pskl.controller");a.LayersListController=function(b){this.piskelController=b};a.LayersListController.prototype.init=function(){this.layerItemTemplate_=pskl.utils.Template.get("layer-item-template");this.rootEl=document.querySelectorAll(".layers-list-container")[0];this.layersListEl=document.querySelectorAll(".layers-list")[0];this.rootEl.addEventListener("click",this.onClick_.bind(this));$.subscribe(Events.PISKEL_RESET,this.renderLayerList_.bind(this));this.renderLayerList_()};
a.LayersListController.prototype.renderLayerList_=function(){this.layersListEl.innerHTML="";this.piskelController.getLayers().forEach(this.addLayerItem.bind(this))};a.LayersListController.prototype.addLayerItem=function(b,c){var a=this.piskelController.getCurrentLayer()===b,a=pskl.utils.Template.replace(this.layerItemTemplate_,{layername:b.getName(),layerindex:c,"isselected:current-layer-item":a}),a=pskl.utils.Template.createFromHTML(a);this.layersListEl.insertBefore(a,this.layersListEl.firstChild)};
a.LayersListController.prototype.onClick_=function(b){b=b.target||b.srcElement;if(b.classList.contains("button"))this.onButtonClick_(b);else b.classList.contains("layer-item")?(b=b.dataset.layerIndex,this.piskelController.setCurrentLayerIndex(parseInt(b,10))):b.classList.contains("edit-icon")&&(b=b.parentNode.dataset.layerIndex,this.renameLayerAt_(b))};a.LayersListController.prototype.renameLayerAt_=function(b){var c=this.piskelController.getLayerAt(b);if(c=window.prompt("Please enter the layer name",
c.getName()))this.piskelController.renameLayerAt(b,c),this.renderLayerList_()};a.LayersListController.prototype.onButtonClick_=function(b){b=b.getAttribute("data-action");"up"==b?this.piskelController.moveLayerUp():"down"==b?this.piskelController.moveLayerDown():"add"==b?this.piskelController.createLayer():"delete"==b&&this.piskelController.removeCurrentLayer()}})();(function(){var a=$.namespace("pskl.controller");a.MinimapController=function(b,c,a,e){this.piskelController=b;this.animationController=c;this.drawingController=a;this.container=e;this.isClicked=!1};a.MinimapController.prototype.init=function(){this.cropFrame=document.createElement("DIV");this.cropFrame.className="minimap-crop-frame";this.cropFrame.style.display="none";$(this.container).append(this.cropFrame);$(this.container).mousedown(this.onMinimapMousedown_.bind(this));$("body").mousemove(this.onMinimapMousemove_.bind(this));
$("body").mouseup(this.onMinimapMouseup_.bind(this));$.subscribe(Events.ZOOM_CHANGED,$.proxy(this.renderMinimap_,this))};a.MinimapController.prototype.renderMinimap_=function(){var b=this.getDrawingAreaZoomRatio_();1<b?this.displayCropFrame_(b,this.drawingController.getRenderer().getOffset()):this.hideCropFrame_()};a.MinimapController.prototype.displayCropFrame_=function(b,c){this.cropFrame.style.display="block";this.cropFrame.style.top=c.y*this.animationController.renderer.getZoom()+"px";this.cropFrame.style.left=
c.x*this.animationController.renderer.getZoom()+"px";var a=this.getDrawingAreaZoomRatio_();this.cropFrame.style.width=this.container.width()/a+"px";this.cropFrame.style.height=this.container.height()/a+"px"};a.MinimapController.prototype.hideCropFrame_=function(){this.cropFrame.style.display="none"};a.MinimapController.prototype.onMinimapMousemove_=function(b){this.isClicked&&1<this.getDrawingAreaZoomRatio_()&&(b=this.getCoordinatesCenteredAround_(b.clientX,b.clientY),this.drawingController.setOffset(b.x,
b.y))};a.MinimapController.prototype.onMinimapMousedown_=function(b){this.isClicked=!0};a.MinimapController.prototype.onMinimapMouseup_=function(b){this.isClicked=!1};a.MinimapController.prototype.getCoordinatesCenteredAround_=function(b,c){var a=this.animationController.renderer.getCoordinates(b,c),e=this.getDrawingAreaZoomRatio_(),f=this.piskelController.getCurrentFrame().getWidth(),g=this.piskelController.getCurrentFrame().getHeight();return{x:a.x-f/e/2,y:a.y-g/e/2}};a.MinimapController.prototype.getDrawingAreaZoomRatio_=
function(){var b=this.drawingController.getRenderer().getZoom();return this.piskelController.getCurrentFrame().getHeight()*b/this.drawingController.getRenderer().getDisplaySize().height}})();(function(){var a=$.namespace("pskl.controller");a.NotificationController=function(){};a.NotificationController.prototype.init=function(){$.subscribe(Events.SHOW_NOTIFICATION,$.proxy(this.displayMessage_,this));$.subscribe(Events.HIDE_NOTIFICATION,$.proxy(this.removeMessage_,this))};a.NotificationController.prototype.displayMessage_=function(b,c){this.removeMessage_();var a=document.createElement("div");a.id="user-message";a.className="user-message";a.innerHTML=c.content;a.innerHTML+="<div title='Close message' class='close'>x</div>";
document.body.appendChild(a);$(a).find(".close").click($.proxy(this.removeMessage_,this));c.behavior&&c.behavior(a)};a.NotificationController.prototype.removeMessage_=function(b){b=$("#user-message");b.length&&b.remove()}})();(function(){var a=$.namespace("pskl.controller");a.PaletteController=function(){this.primaryColor=Constants.DEFAULT_PEN_COLOR;this.secondaryColor=Constants.TRANSPARENT_COLOR};a.PaletteController.prototype.init=function(){$.subscribe(Events.SELECT_PRIMARY_COLOR,this.onColorSelected_.bind(this,{isPrimary:!0}));$.subscribe(Events.SELECT_SECONDARY_COLOR,this.onColorSelected_.bind(this,{isPrimary:!1}));pskl.app.shortcutService.addShortcut("X",this.swapColors.bind(this));pskl.app.shortcutService.addShortcut("D",
this.resetColors.bind(this));var b={showPalette:!0,showButtons:!1,showInput:!0,palette:[["rgba(0,0,0,0)"]],clickoutFiresChange:!0,beforeShow:function(b){b.setAlpha(1)}},c=$("#color-picker");c.spectrum($.extend({color:Constants.DEFAULT_PEN_COLOR},b));c.change({isPrimary:!0},$.proxy(this.onPickerChange_,this));this.setTitleOnPicker_(Constants.DEFAULT_PEN_COLOR,c);c=$("#secondary-color-picker");c.spectrum($.extend({color:Constants.TRANSPARENT_COLOR},b));c.change({isPrimary:!1},$.proxy(this.onPickerChange_,
this));this.setTitleOnPicker_(Constants.TRANSPARENT_COLOR,c);$(".swap-colors-icon").click(this.swapColors.bind(this))};a.PaletteController.prototype.onPickerChange_=function(b,c){var a=$(b.target);b.data.isPrimary?this.setPrimaryColor(a.val()):this.setSecondaryColor(a.val())};a.PaletteController.prototype.onColorSelected_=function(b,c,a){$(c.target);b.isPrimary?this.setPrimaryColor(a):this.setSecondaryColor(a)};a.PaletteController.prototype.setPrimaryColor=function(b){this.primaryColor=b;this.updateColorPicker_(b,
$("#color-picker"));$.publish(Events.PRIMARY_COLOR_SELECTED,[b])};a.PaletteController.prototype.setSecondaryColor=function(b){this.secondaryColor=b;this.updateColorPicker_(b,$("#secondary-color-picker"));$.publish(Events.SECONDARY_COLOR_SELECTED,[b])};a.PaletteController.prototype.getPrimaryColor=function(){return this.primaryColor};a.PaletteController.prototype.getSecondaryColor=function(){return this.secondaryColor};a.PaletteController.prototype.swapColors=function(){var b=this.getPrimaryColor();
this.setPrimaryColor(this.getSecondaryColor());this.setSecondaryColor(b)};a.PaletteController.prototype.resetColors=function(){this.setPrimaryColor(Constants.DEFAULT_PEN_COLOR);this.setSecondaryColor(Constants.TRANSPARENT_COLOR)};a.PaletteController.prototype.updateColorPicker_=function(b,c){b==Constants.TRANSPARENT_COLOR?(c.spectrum("set",Constants.TRANSPARENT_COLOR),c.val(Constants.TRANSPARENT_COLOR)):c.spectrum("set",b);this.setTitleOnPicker_(b,c)};a.PaletteController.prototype.setTitleOnPicker_=
function(b,c){c.next(".sp-replacer").attr("title",b)}})();(function(){var a=$.namespace("pskl.controller");a.PalettesListController=function(){};a.PalettesListController.prototype.init=function(){this.paletteColorTemplate_=pskl.utils.Template.get("palette-color-template");this.colorListContainer_=document.querySelector(".palettes-list-colors");this.colorPaletteSelect_=document.querySelector(".palettes-list-select");this.paletteListOptGroup_=document.querySelector(".palettes-list-select-group");this.colorPaletteSelect_.addEventListener("change",this.onPaletteSelected_.bind(this));
this.colorListContainer_.addEventListener("mouseup",this.onColorContainerMouseup.bind(this));this.colorListContainer_.addEventListener("contextmenu",this.onColorContainerContextMenu.bind(this));$.subscribe(Events.PALETTE_LIST_UPDATED,this.onPaletteListUpdated.bind(this));$.subscribe(Events.PRIMARY_COLOR_SELECTED,this.onColorUpdated.bind(this,"primary"));$.subscribe(Events.SECONDARY_COLOR_SELECTED,this.onColorUpdated.bind(this,"secondary"));this.fillPaletteList();this.selectPaletteFromUserSettings();
this.fillColorListContainer()};a.PalettesListController.prototype.fillPaletteList=function(){var b=[{id:Constants.NO_PALETTE_ID,name:"No palette"}],b=b.concat(this.retrievePalettes()),b=b.map(function(b){return pskl.utils.Template.replace('<option value="{{id}}">{{name}}</option>',b)}).join("");this.paletteListOptGroup_.innerHTML=b};a.PalettesListController.prototype.fillColorListContainer=function(){var b="",c=this.getSelectedPalette();c&&(b=c.colors.map(function(b){return pskl.utils.Template.replace(this.paletteColorTemplate_,
{color:b})}.bind(this)).join(""));this.colorListContainer_.innerHTML=b};a.PalettesListController.prototype.getSelectedPalette=function(b){b=this.colorPaletteSelect_.value;var c=this.retrievePalettes();return this.getPaletteById(b,c)};a.PalettesListController.prototype.selectPalette=function(b){this.colorPaletteSelect_.value=b};a.PalettesListController.prototype.selectPaletteFromUserSettings=function(){this.selectPalette(pskl.UserSettings.get(pskl.UserSettings.SELECTED_PALETTE))};a.PalettesListController.prototype.onPaletteSelected_=
function(b){b=this.colorPaletteSelect_.value;"__manage-palettes"===b?($.publish(Events.DIALOG_DISPLAY,"manage-palettes"),this.selectPaletteFromUserSettings()):pskl.UserSettings.set(pskl.UserSettings.SELECTED_PALETTE,b);this.fillColorListContainer()};a.PalettesListController.prototype.onColorContainerContextMenu=function(b){b.preventDefault()};a.PalettesListController.prototype.onColorContainerMouseup=function(b){var c=b.target.dataset.color;c&&(b.button==Constants.LEFT_BUTTON?$.publish(Events.SELECT_PRIMARY_COLOR,
[c]):b.button==Constants.RIGHT_BUTTON&&$.publish(Events.SELECT_SECONDARY_COLOR,[c]))};a.PalettesListController.prototype.onColorUpdated=function(b,c,a){if(c=this.colorListContainer_.querySelector('.palettes-list-color[data-color="'+a+'"]'))"primary"===b?(this.removeClass_("primary",".palettes-list-color"),c.classList.add("primary"),c.classList.remove("secondary")):"secondary"===b&&(this.removeClass_("secondary",".palettes-list-color"),c.classList.add("secondary"),c.classList.remove("primary"))};a.PalettesListController.prototype.removeClass_=
function(b,c){var a=document.querySelector(c+"."+b);a&&a.classList.remove(b)};a.PalettesListController.prototype.onPaletteListUpdated=function(){this.fillPaletteList();this.selectPaletteFromUserSettings();this.fillColorListContainer()};a.PalettesListController.prototype.getPaletteById=function(b,c){var a=null;c.forEach(function(c){c.id===b&&(a=c)});return a};a.PalettesListController.prototype.retrievePalettes=function(){var b=window.localStorage.getItem("piskel.palettes");return JSON.parse(b)||[]}})();(function(){var a=$.namespace("pskl.controller");a.PreviewFilmController=function(b,c){this.piskelController=b;this.container=c;this.refreshZoom_();this.redrawFlag=!0};a.PreviewFilmController.prototype.init=function(){$.subscribe(Events.TOOL_RELEASED,this.flagForRedraw_.bind(this));$.subscribe(Events.PISKEL_RESET,this.flagForRedraw_.bind(this));$.subscribe(Events.USER_SETTINGS_CHANGED,this.flagForRedraw_.bind(this));$.subscribe(Events.PISKEL_RESET,this.refreshZoom_.bind(this));$("#preview-list-scroller").scroll(this.updateScrollerOverflows.bind(this));
this.container.get(0).addEventListener("click",this.onContainerClick_.bind(this));this.updateScrollerOverflows()};a.PreviewFilmController.prototype.flagForRedraw_=function(){this.redrawFlag=!0};a.PreviewFilmController.prototype.refreshZoom_=function(){this.zoom=this.calculateZoom_()};a.PreviewFilmController.prototype.render=function(){this.redrawFlag&&(this.createPreviews_(),this.redrawFlag=!1)};a.PreviewFilmController.prototype.updateScrollerOverflows=function(){var b=$("#preview-list-scroller"),
c=b.height(),a=b.scrollTop(),e=$("#preview-list").height(),f=$(".top-overflow").height(),g=b=!1;c<e&&(a>f&&(b=!0),e-a-c>f&&(g=!0));c=$("#preview-list-wrapper");c.toggleClass("top-overflow-visible",b);c.toggleClass("bottom-overflow-visible",g)};a.PreviewFilmController.prototype.onContainerClick_=function(b){var c=pskl.utils.Dom.getParentWithData(b.target,"tileAction");c&&(b=c.dataset.tileAction,c=parseInt(c.dataset.tileNumber,10),"clone"===b?(this.piskelController.duplicateFrameAt(c),this.piskelController.setCurrentFrameIndex(c+
1),this.updateScrollerOverflows()):"delete"===b?(this.piskelController.removeFrameAt(c),this.updateScrollerOverflows()):"select"===b?this.piskelController.setCurrentFrameIndex(c):"newframe"===b&&(this.piskelController.addFrame(),this.piskelController.setCurrentFrameIndex(this.piskelController.getFrameCount()-1),this.updateScrollerOverflows()))};a.PreviewFilmController.prototype.createPreviews_=function(){this.container.html("");$(".tooltip").remove();for(var b=this.piskelController.getFrameCount(),
c=0;c<b;c++)this.container.append(this.createPreviewTile_(c));c=document.createElement("div");c.id="add-frame-action";c.className="add-frame-action";c.setAttribute("data-tile-action","newframe");c.innerHTML="<p class='label'>Add new frame</p>";this.container.append(c);1<b&&this.initDragndropBehavior_();this.updateScrollerOverflows()};a.PreviewFilmController.prototype.initDragndropBehavior_=function(){$("#preview-list").sortable({placeholder:"preview-tile-drop-proxy",update:$.proxy(this.onUpdate_,
this),items:".preview-tile"});$("#preview-list").disableSelection()};a.PreviewFilmController.prototype.onUpdate_=function(b,c){var a=parseInt(c.item.data("tile-number"),10),e=$(".preview-tile").index(c.item);this.piskelController.moveFrame(a,e);this.piskelController.setCurrentFrameIndex(e)};a.PreviewFilmController.prototype.createPreviewTile_=function(b){var c=this.piskelController.getCurrentLayer().getFrameAt(b),a=document.createElement("li");a.setAttribute("data-tile-number",b);a.setAttribute("data-tile-action",
"select");a.classList.add("preview-tile");this.piskelController.getCurrentFrame()==c&&a.classList.add("selected");var e=document.createElement("div");e.classList.add("canvas-container",pskl.UserSettings.get(pskl.UserSettings.CANVAS_BACKGROUND));var f=document.createElement("div");f.className="canvas-background";e.appendChild(f);f=document.createElement("button");f.setAttribute("rel","tooltip");f.setAttribute("data-placement","right");f.setAttribute("data-tile-number",b);f.setAttribute("data-tile-action",
"clone");f.setAttribute("title","Duplicate this frame");f.className="tile-overlay duplicate-frame-action";a.appendChild(f);c=new pskl.rendering.CanvasRenderer(c,this.zoom);c.drawTransparentAs(Constants.TRANSPARENT_COLOR);c=c.render();c.classList.add("tile-view","canvas");e.appendChild(c);a.appendChild(e);if(0<b||1<this.piskelController.getFrameCount())e=document.createElement("button"),e.setAttribute("rel","tooltip"),e.setAttribute("data-placement","right"),e.setAttribute("title","Delete this frame"),
e.setAttribute("data-tile-number",b),e.setAttribute("data-tile-action","delete"),e.className="tile-overlay delete-frame-action",a.appendChild(e),e=document.createElement("div"),e.className="tile-overlay dnd-action",a.appendChild(e);e=document.createElement("div");e.className="tile-overlay tile-count";e.innerHTML=b+1;a.appendChild(e);return a};a.PreviewFilmController.prototype.calculateZoom_=function(){var b=this.piskelController.getCurrentFrame(),c=b.getHeight(),b=b.getWidth(),a=Math.max(b,c);return pskl.PixelUtils.calculateZoom(Constants.PREVIEW_FILM_SIZE*
c/a,Constants.PREVIEW_FILM_SIZE*b/a,c,b)||1}})();(function(){var a=$.namespace("pskl.controller");a.ToolController=function(){var b=function(b,a,e){return{id:b,shortcut:a,instance:e}};this.tools=[b("simplePen","P",new pskl.drawingtools.SimplePen),b("verticalMirrorPen","V",new pskl.drawingtools.VerticalMirrorPen),b("eraser","E",new pskl.drawingtools.Eraser),b("paintBucket","B",new pskl.drawingtools.PaintBucket),b("stroke","L",new pskl.drawingtools.Stroke),b("rectangle","R",new pskl.drawingtools.Rectangle),b("circle","C",new pskl.drawingtools.Circle),
b("move","M",new pskl.drawingtools.Move),b("rectangleSelect","S",new pskl.drawingtools.RectangleSelect),b("shapeSelect","Z",new pskl.drawingtools.ShapeSelect),b("colorPicker","O",new pskl.drawingtools.ColorPicker)];this.currentSelectedTool=this.tools[0];this.previousSelectedTool=this.tools[0]};a.ToolController.prototype.init=function(){this.createToolsDom_();this.addKeyboardShortcuts_();this.selectTool_(this.tools[0]);$("#tool-section").mousedown($.proxy(this.onToolIconClicked_,this))};a.ToolController.prototype.activateToolOnStage_=
function(b){var c=$("body"),a=c.data("selected-tool-class");a&&(c.removeClass(a),c.removeClass(pskl.drawingtools.Move.TOOL_ID));c.addClass(b.instance.toolId);c.data("selected-tool-class",b.instance.toolId)};a.ToolController.prototype.selectTool_=function(b){this.currentSelectedTool=b;this.activateToolOnStage_(this.currentSelectedTool);var c=$("#tool-section .tool-icon.selected"),a=$("[data-tool-id="+b.instance.toolId+"]");c.removeClass("selected");a.addClass("selected");$.publish(Events.TOOL_SELECTED,
[b.instance])};a.ToolController.prototype.onToolIconClicked_=function(b){b=$(b.target).closest(".tool-icon");b.length&&(b=b.data().toolId,(b=this.getToolById_(b))&&this.selectTool_(b))};a.ToolController.prototype.onKeyboardShortcut_=function(b){for(var c=0;c<this.tools.length;c++){var a=this.tools[c];a.shortcut.toLowerCase()===b.toLowerCase()&&this.selectTool_(a)}};a.ToolController.prototype.getToolById_=function(b){for(var c=0;c<this.tools.length;c++){var a=this.tools[c];if(a.instance.toolId==b)return a}return null};
a.ToolController.prototype.createToolsDom_=function(){for(var b="",c=0;c<this.tools.length;c++)b+=this.getToolMarkup_(this.tools[c]);$("#tools-container").html(b)};a.ToolController.prototype.getToolMarkup_=function(b){var c=b.instance.toolId,a=["tool-icon",c];this.currentSelectedTool==b&&a.push("selected");var e=pskl.utils.Template.get("drawing-tool-item-template");return pskl.utils.Template.replace(e,{cssclass:a.join(" "),toolid:c,title:this.getTooltipText_(b)})};a.ToolController.prototype.getTooltipText_=
function(b){return b.instance.helpText+" ("+b.shortcut+")"};a.ToolController.prototype.addKeyboardShortcuts_=function(){for(var b=0;b<this.tools.length;b++)pskl.app.shortcutService.addShortcut(this.tools[b].shortcut,this.onKeyboardShortcut_.bind(this))}})();(function(){var a=$.namespace("pskl.controller.dialogs"),b={"manage-palettes":{template:"templates/dialogs/manage-palettes.html",controller:a.PaletteManagerController}};a.DialogsController=function(b){this.piskelController=b;this.currentDialog_=null};a.DialogsController.prototype.init=function(){this.dialogContainer_=document.getElementById("dialog-container");this.dialogWrapper_=document.getElementById("dialog-container-wrapper");$.subscribe(Events.DIALOG_DISPLAY,this.onDialogDisplayEvent_.bind(this));
$.subscribe(Events.DIALOG_HIDE,this.onDialogHideEvent_.bind(this));pskl.app.shortcutService.addShortcut("alt+P",this.onDialogDisplayEvent_.bind(this,null,"manage-palettes"))};a.DialogsController.prototype.onDialogDisplayEvent_=function(c,a){if(!this.isDisplayed()){var e=b[a];e?(this.dialogContainer_.innerHTML=pskl.utils.Template.get(e.template),e=new e.controller(this.piskelController),e.init(),this.showDialogWrapper_(),this.currentDialog_={id:a,controller:e}):console.error("Could not find dialog configuration for dialogId : "+
a)}};a.DialogsController.prototype.onDialogHideEvent_=function(){this.hideDialog()};a.DialogsController.prototype.showDialogWrapper_=function(){pskl.app.shortcutService.addShortcut("ESC",this.hideDialog.bind(this));this.dialogWrapper_.classList.add("show")};a.DialogsController.prototype.hideDialog=function(){var b=this.currentDialog_;b&&b.controller.destroy();this.hideDialogWrapper_();this.currentDialog_=null};a.DialogsController.prototype.hideDialogWrapper_=function(){pskl.app.shortcutService.removeShortcut("ESC");
this.dialogWrapper_.classList.remove("show")};a.DialogsController.prototype.isDisplayed=function(){return null!==this.currentDialog_}})();(function(){var a=$.namespace("pskl.controller.dialogs"),b=window.tinycolor;a.PaletteManagerController=function(b){this.piskelController=b;this.palettes=this.retrieveUserPalettes();this.originalPalettes=this.retrieveUserPalettes();this.selectedPaletteId=null;this.spectrumContainers=[]};a.PaletteManagerController.prototype.init=function(){this.palettesList=document.querySelector(".palette-manager-list");this.paletteBody=document.querySelector(".palette-manager-details-body");this.paletteHead=document.querySelector(".palette-manager-details-head");
this.createButton=document.querySelector('.palette-manager-actions-button[data-action="create"]');this.saveAllButton=document.querySelector('.palette-manager-actions-button[data-action="save-all"]');this.closeButton=document.querySelector(".palette-manager-close");this.colorCardTemplate=pskl.utils.Template.get("palette-color-card-template");this.newColorTemplate=pskl.utils.Template.get("palette-new-color-template");this.paletteHeadTemplate=pskl.utils.Template.get("palette-details-head-template");
this.palettesList.addEventListener("click",this.onPaletteListClick.bind(this));this.paletteBody.addEventListener("click",this.delegatedPaletteBodyClick.bind(this));this.paletteHead.addEventListener("click",this.delegatedPaletteHeadClick.bind(this));this.createButton.addEventListener("click",this.onCreateClick_.bind(this));this.saveAllButton.addEventListener("click",this.saveAll.bind(this));this.closeButton.addEventListener("click",this.closeDialog.bind(this));this.createPaletteListMarkup();0<this.palettes.length?
this.selectPalette(this.palettes[0].id):this.createPalette("New palette")};a.PaletteManagerController.prototype.destroy=function(){this.destroySpectrumPickers()};a.PaletteManagerController.prototype.closeDialog=function(){$.publish(Events.DIALOG_HIDE)};a.PaletteManagerController.prototype.onCreateClick_=function(b){this.createPalette()};a.PaletteManagerController.prototype.createPalette=function(b){b||(b=window.prompt("Please enter a name for your palette","New palette"));b&&(b=this.createPaletteObject(b),
this.palettes.push(b),this.createPaletteListMarkup(),this.selectPalette(b.id))};a.PaletteManagerController.prototype.createPaletteObject=function(b){return{id:"palette-"+Date.now()+"-"+Math.floor(1E3*Math.random()),name:b,colors:[]}};a.PaletteManagerController.prototype.redraw=function(){this.createPaletteListMarkup();this.selectPalette(this.selectedPaletteId)};a.PaletteManagerController.prototype.selectPalette=function(b){this.deselectCurrentPalette();var a=this.palettesList.querySelector("[data-palette-id="+
b+"]");a&&(this.selectedPaletteId=b,a.classList.add("selected"),this.refreshPaletteDetails())};a.PaletteManagerController.prototype.refreshPaletteDetails=function(){this.createPaletteHeadMarkup();this.createPaletteBodyMarkup();this.initPaletteDetailsEvents();this.initPaletteCardsSpectrum()};a.PaletteManagerController.prototype.createPaletteListMarkup=function(){var b=this.palettes.map(function(b){b={id:b.id,name:this.isPaletteModified(b)?b.name+" *":b.name};return pskl.utils.Template.replace('<li data-palette-id="{{id}}">{{name}}</li>',
b)}.bind(this)).join("");this.palettesList.innerHTML=b};a.PaletteManagerController.prototype.createPaletteHeadMarkup=function(){var b=this.getSelectedPalette(),b={name:b.name,"save:disabled":!this.isPaletteModified(b),"revert:disabled":!this.isPaletteModified(b),"delete:disabled":2>this.palettes.length},b=pskl.utils.Template.replace(this.paletteHeadTemplate,b);this.paletteHead.innerHTML=b};a.PaletteManagerController.prototype.isPaletteModified=function(b){var a=!1,e=this.getPaletteById(b.id,this.originalPalettes);
e?(a=e.name!==b.name,b=b.colors.join("")!==e.colors.join(""),a=a||b):a=!0;return a};a.PaletteManagerController.prototype.createPaletteBodyMarkup=function(){var b=this.getSelectedPalette(),b=this.getColorCardsMarkup(b.colors),b=b+pskl.utils.Template.replace(this.newColorTemplate,{classname:"palette-manager-new-color"});this.paletteBody.innerHTML=b};a.PaletteManagerController.prototype.initPaletteDetailsEvents=function(){this.paletteBody.querySelector(".palette-manager-new-color").addEventListener("click",
this.onNewCardClick.bind(this));2>this.palettes.length&&this.paletteHead.querySelector('.palette-manager-palette-button[data-action="delete"]').setAttribute("disabled","disabled")};a.PaletteManagerController.prototype.onNewCardClick=function(){var b=this.getSelectedPalette();this.addColorInSelectedPalette(b&&0<b.colors.length?b.colors[b.colors.length-1]:"#FFFFFF")};a.PaletteManagerController.prototype.delegatedPaletteBodyClick=function(b){b=b.target;b.classList.contains("palette-manager-delete-card")&&
(b=parseInt(b.parentNode.dataset.colorId,10),this.removeColorInSelectedPalette(b))};a.PaletteManagerController.prototype.delegatedPaletteHeadClick=function(b){b=b.target;b.classList.contains("edit-icon")?this.renameSelectedPalette():b.classList.contains("palette-manager-palette-button")&&(b=b.dataset.action,"save"===b?(this.savePalette(this.getSelectedPalette().id),this.redraw()):"revert"===b?this.revertChanges():"delete"===b&&this.deleteSelectedPalette())};a.PaletteManagerController.prototype.getSpectrumSelector_=
function(){return":not(.palette-manager-new-color)>.palette-manager-color-square"};a.PaletteManagerController.prototype.initPaletteCardsSpectrum=function(){var b=this,a=$(this.getSpectrumSelector_());a.spectrum({clickoutFiresChange:!0,showInput:!0,showButtons:!1,change:function(a){var d=parseInt(this.parentNode.dataset.colorId,10);b.updateColorInSelectedPalette(d,a)},beforeShow:function(){var e=parseInt(this.parentNode.dataset.colorId,10),e=b.getSelectedPalette().colors[e];a.spectrum("set",e)}});
this.spectrumContainers.push(a)};a.PaletteManagerController.prototype.destroySpectrumPickers=function(){this.spectrumContainers.forEach(function(b){b.spectrum("destroy")});this.spectrumContainers=[]};a.PaletteManagerController.prototype.updateColorInSelectedPalette=function(b,a){var e=this.getSelectedPalette(),f="#"+a.toHex().toUpperCase();e.colors.splice(b,1,f);this.redraw()};a.PaletteManagerController.prototype.addColorInSelectedPalette=function(b){this.getSelectedPalette().colors.push(b);this.redraw()};
a.PaletteManagerController.prototype.removeColorInSelectedPalette=function(b){this.getSelectedPalette().colors.splice(b,1);this.redraw()};a.PaletteManagerController.prototype.renameSelectedPalette=function(){var b=this.getSelectedPalette(),a=window.prompt('Please enter a new name for palette "'+b.name+'"',b.name);a&&(b.name=a,this.redraw())};a.PaletteManagerController.prototype.getSelectedPalette=function(){return this.getPaletteById(this.selectedPaletteId,this.palettes)};a.PaletteManagerController.prototype.getColorCardsMarkup=
function(a){return a.map(function(a,c){var f={colorId:c,hex:a,rgb:b(a).toRgbString(),hsl:b(a).toHslString()};return pskl.utils.Template.replace(this.colorCardTemplate,f)}.bind(this)).join("")};a.PaletteManagerController.prototype.getPaletteById=function(b,a){var e=null;a.forEach(function(a){a.id===b&&(e=a)});return e};a.PaletteManagerController.prototype.removePaletteById=function(b,a){var e=this.getPaletteById(b,a);e&&(e=a.indexOf(e),a.splice(e,1))};a.PaletteManagerController.prototype.deselectCurrentPalette=
function(){var b=this.palettesList.querySelector(".selected");b&&(this.selectedPaletteId=null,b.classList.remove("selected"))};a.PaletteManagerController.prototype.revertChanges=function(){var b=this.getSelectedPalette(),a=this.getPaletteById(b.id,this.originalPalettes);b.name=a.name;b.colors=a.colors.slice(0);this.redraw()};a.PaletteManagerController.prototype.deleteSelectedPalette=function(){var b=this.getSelectedPalette();1<this.palettes.length&&window.confirm('Are you sure you want to delete "'+
b.name+'" ?')&&(this.removePaletteById(b.id,this.palettes),this.removePaletteById(b.id,this.originalPalettes),this.persistToLocalStorage(),this.createPaletteListMarkup(),this.selectPalette(this.palettes[0].id))};a.PaletteManagerController.prototype.onPaletteListClick=function(b){b=b.target;b.dataset.paletteId&&this.selectPalette(b.dataset.paletteId)};a.PaletteManagerController.prototype.saveAll=function(){this.palettes.forEach(function(b){this.savePalette(b.id)}.bind(this));this.redraw()};a.PaletteManagerController.prototype.savePalette=
function(b){var a=this.getPaletteById(b,this.palettes);(b=this.getPaletteById(b,this.originalPalettes))?(b.name=a.name,b.colors=a.colors):this.originalPalettes.push(a);this.persistToLocalStorage();$.publish(Events.SHOW_NOTIFICATION,[{content:"Palette "+a.name+" successfully saved !"}]);window.setTimeout($.publish.bind($,Events.HIDE_NOTIFICATION),2E3)};a.PaletteManagerController.prototype.persistToLocalStorage=function(){window.localStorage.setItem("piskel.palettes",JSON.stringify(this.originalPalettes));
this.originalPalettes=this.retrieveUserPalettes();$.publish(Events.PALETTE_LIST_UPDATED)};a.PaletteManagerController.prototype.retrieveUserPalettes=function(){var b=window.localStorage.getItem("piskel.palettes");return JSON.parse(b)||[]}})();(function(){var a=$.namespace("pskl.controller.piskel");a.PiskelController=function(b){if(b)this.setPiskel(b);else throw"A piskel instance is mandatory for instanciating PiskelController";};a.PiskelController.prototype.setPiskel=function(b){this.piskel=b;this.currentFrameIndex=this.currentLayerIndex=0;this.layerIdCounter=1};a.PiskelController.prototype.init=function(){};a.PiskelController.prototype.getHeight=function(){return this.piskel.getHeight()};a.PiskelController.prototype.getWidth=function(){return this.piskel.getWidth()};
a.PiskelController.prototype.getFPS=function(){return pskl.app.animationController.getFPS()};a.PiskelController.prototype.getLayers=function(){return this.piskel.getLayers()};a.PiskelController.prototype.getCurrentLayer=function(){return this.getLayerAt(this.currentLayerIndex)};a.PiskelController.prototype.getLayerAt=function(b){return this.piskel.getLayerAt(b)};a.PiskelController.prototype.getCurrentFrame=function(){return this.getCurrentLayer().getFrameAt(this.currentFrameIndex)};a.PiskelController.prototype.getCurrentLayerIndex=
function(){return this.currentLayerIndex};a.PiskelController.prototype.getCurrentFrameIndex=function(){return this.currentFrameIndex};a.PiskelController.prototype.getPiskel=function(){return this.piskel};a.PiskelController.prototype.getFrameAt=function(b){var a=this.getLayers().map(function(a){return a.getFrameAt(b)});return pskl.utils.FrameUtils.merge(a)};a.PiskelController.prototype.hasFrameAt=function(b){return!!this.getCurrentLayer().getFrameAt(b)};a.PiskelController.prototype.addFrame=function(){this.addFrameAt(this.getFrameCount())};
a.PiskelController.prototype.addFrameAtCurrentIndex=function(){this.addFrameAt(this.currentFrameIndex+1)};a.PiskelController.prototype.addFrameAt=function(b){this.getLayers().forEach(function(a){a.addFrameAt(this.createEmptyFrame_(),b)}.bind(this))};a.PiskelController.prototype.createEmptyFrame_=function(){var b=this.piskel.getWidth(),a=this.piskel.getHeight();return new pskl.model.Frame(b,a)};a.PiskelController.prototype.removeFrameAt=function(b){this.getLayers().forEach(function(a){a.removeFrameAt(b)});
this.currentFrameIndex>=b&&0<this.currentFrameIndex&&this.setCurrentFrameIndex(this.currentFrameIndex-1)};a.PiskelController.prototype.duplicateCurrentFrame=function(){this.duplicateFrameAt(this.currentFrameIndex)};a.PiskelController.prototype.duplicateFrameAt=function(b){this.getLayers().forEach(function(a){a.duplicateFrameAt(b)})};a.PiskelController.prototype.moveFrame=function(b,a){this.getLayers().forEach(function(d){d.moveFrame(b,a)})};a.PiskelController.prototype.getFrameCount=function(){return this.piskel.getLayerAt(0).length()};
a.PiskelController.prototype.setCurrentFrameIndex=function(b){this.currentFrameIndex=b};a.PiskelController.prototype.selectNextFrame=function(){var b=this.currentFrameIndex+1;b<this.getFrameCount()&&this.setCurrentFrameIndex(b)};a.PiskelController.prototype.selectPreviousFrame=function(){var b=this.currentFrameIndex-1;0<=b&&this.setCurrentFrameIndex(b)};a.PiskelController.prototype.setCurrentLayerIndex=function(b){this.currentLayerIndex=b};a.PiskelController.prototype.selectLayer=function(b){b=this.getLayers().indexOf(b);
-1!=b&&this.setCurrentLayerIndex(b)};a.PiskelController.prototype.renameLayerAt=function(b,a){var d=this.getLayerByIndex(b);d&&d.setName(a)};a.PiskelController.prototype.getLayerByIndex=function(b){var a=this.getLayers();return a[b]?a[b]:null};a.PiskelController.prototype.generateLayerName_=function(){for(var b="Layer "+this.layerIdCounter;this.hasLayerForName_(b);)this.layerIdCounter++,b="Layer "+this.layerIdCounter;return b};a.PiskelController.prototype.createLayer=function(b){b||(b=this.generateLayerName_());
if(this.hasLayerForName_(b))throw"Layer name should be unique";b=new pskl.model.Layer(b);for(var a=0;a<this.getFrameCount();a++)b.addFrame(this.createEmptyFrame_());this.piskel.addLayer(b);this.setCurrentLayerIndex(this.piskel.getLayers().length-1)};a.PiskelController.prototype.hasLayerForName_=function(b){return 0<this.piskel.getLayersByName(b).length};a.PiskelController.prototype.moveLayerUp=function(){var b=this.getCurrentLayer();this.piskel.moveLayerUp(b);this.selectLayer(b)};a.PiskelController.prototype.moveLayerDown=
function(){var b=this.getCurrentLayer();this.piskel.moveLayerDown(b);this.selectLayer(b)};a.PiskelController.prototype.removeCurrentLayer=function(){if(1<this.getLayers().length){var b=this.getCurrentLayer();this.piskel.removeLayer(b);this.setCurrentLayerIndex(0)}};a.PiskelController.prototype.serialize=function(b){return pskl.utils.Serializer.serializePiskel(this.piskel,b)}})();(function(){var a=$.namespace("pskl.controller.piskel");a.PublicPiskelController=function(b){this.piskelController=b;pskl.utils.wrap(this,this.piskelController)};a.PublicPiskelController.prototype.init=function(){pskl.app.shortcutService.addShortcut("up",this.selectPreviousFrame.bind(this));pskl.app.shortcutService.addShortcut("down",this.selectNextFrame.bind(this));pskl.app.shortcutService.addShortcut("n",this.addFrameAtCurrentIndex.bind(this));pskl.app.shortcutService.addShortcut("shift+n",this.duplicateCurrentFrame.bind(this))};
a.PublicPiskelController.prototype.setPiskel=function(b){this.piskelController.setPiskel(b);$.publish(Events.FRAME_SIZE_CHANGED);$.publish(Events.PISKEL_RESET);$.publish(Events.PISKEL_SAVE_STATE,{type:"FULL"})};a.PublicPiskelController.prototype.addFrame=function(){this.addFrameAt(this.piskelController.getFrameCount())};a.PublicPiskelController.prototype.addFrameAtCurrentIndex=function(){this.addFrameAt(this.getCurrentFrameIndex())};a.PublicPiskelController.prototype.addFrameAt=function(b){this.piskelController.addFrameAt(b);
this.raiseSaveStateEvent_(this.piskelController.addFrameAt,[b]);$.publish(Events.PISKEL_RESET)};a.PublicPiskelController.prototype.removeFrameAt=function(b){this.piskelController.removeFrameAt(b);this.raiseSaveStateEvent_(this.piskelController.removeFrameAt,[b]);$.publish(Events.PISKEL_RESET)};a.PublicPiskelController.prototype.duplicateCurrentFrame=function(){this.piskelController.duplicateFrameAt(this.getCurrentFrameIndex())};a.PublicPiskelController.prototype.raiseSaveStateEvent_=function(b,a){$.publish(Events.PISKEL_SAVE_STATE,
{type:"REPLAY",scope:this,replay:{fn:b,args:a}})};a.PublicPiskelController.prototype.replay=function(b,a){a.fn.apply(this.piskelController,a.args)};a.PublicPiskelController.prototype.duplicateFrameAt=function(b){this.piskelController.duplicateFrameAt(b);this.raiseSaveStateEvent_(this.piskelController.duplicateFrameAt,[b]);$.publish(Events.PISKEL_RESET)};a.PublicPiskelController.prototype.moveFrame=function(b,a){this.piskelController.moveFrame(b,a);this.raiseSaveStateEvent_(this.piskelController.moveFrame,
[b,a]);$.publish(Events.PISKEL_RESET)};a.PublicPiskelController.prototype.setCurrentFrameIndex=function(b){this.piskelController.setCurrentFrameIndex(b);$.publish(Events.PISKEL_RESET)};a.PublicPiskelController.prototype.selectNextFrame=function(){this.piskelController.selectNextFrame();$.publish(Events.PISKEL_RESET)};a.PublicPiskelController.prototype.selectPreviousFrame=function(){this.piskelController.selectPreviousFrame();$.publish(Events.PISKEL_RESET)};a.PublicPiskelController.prototype.setCurrentLayerIndex=
function(b){this.piskelController.setCurrentLayerIndex(b);$.publish(Events.PISKEL_RESET)};a.PublicPiskelController.prototype.selectLayer=function(b){this.piskelController.selectLayer(b);$.publish(Events.PISKEL_RESET)};a.PublicPiskelController.prototype.renameLayerAt=function(b,a){this.piskelController.renameLayerAt(b,a);this.raiseSaveStateEvent_(this.piskelController.renameLayerAt,[b,a])};a.PublicPiskelController.prototype.createLayer=function(b){this.piskelController.createLayer(b);this.raiseSaveStateEvent_(this.piskelController.createLayer,
[b]);$.publish(Events.PISKEL_RESET)};a.PublicPiskelController.prototype.moveLayerUp=function(){this.piskelController.moveLayerUp();this.raiseSaveStateEvent_(this.piskelController.moveLayerUp,[]);$.publish(Events.PISKEL_RESET)};a.PublicPiskelController.prototype.moveLayerDown=function(){this.piskelController.moveLayerDown();this.raiseSaveStateEvent_(this.piskelController.moveLayerDown,[]);$.publish(Events.PISKEL_RESET)};a.PublicPiskelController.prototype.removeCurrentLayer=function(){this.piskelController.removeCurrentLayer();
this.raiseSaveStateEvent_(this.piskelController.removeCurrentLayer,[]);$.publish(Events.PISKEL_RESET)};a.PublicPiskelController.prototype.getCurrentLayerIndex=function(){return this.piskelController.currentLayerIndex};a.PublicPiskelController.prototype.getCurrentFrameIndex=function(){return this.piskelController.currentFrameIndex};a.PublicPiskelController.prototype.getPiskel=function(){return this.piskelController.piskel}})();(function(){var a=$.namespace("pskl.controller.settings");a.ApplicationSettingsController=function(){};a.ApplicationSettingsController.prototype.init=function(){var b=pskl.UserSettings.get(pskl.UserSettings.CANVAS_BACKGROUND);$("#background-picker-wrapper").find(".background-picker[data-background-class="+b+"]").addClass("selected");b=pskl.UserSettings.get(pskl.UserSettings.GRID_WIDTH);$("#grid-width").val(b);$("#grid-width").change(this.onGridWidthChange.bind(this));$("#background-picker-wrapper").click(this.onBackgroundClick.bind(this))};
a.ApplicationSettingsController.prototype.onGridWidthChange=function(b){b=$("#grid-width").val();pskl.UserSettings.set(pskl.UserSettings.GRID_WIDTH,parseInt(b,10))};a.ApplicationSettingsController.prototype.onBackgroundClick=function(b){b=$(b.target).closest(".background-picker");if(b.length){var a=b.data("background-class");pskl.UserSettings.set(pskl.UserSettings.CANVAS_BACKGROUND,a);$(".background-picker").removeClass("selected");b.addClass("selected")}}})();(function(){var a=$.namespace("pskl.controller.settings");a.GifExportController=function(b){this.piskelController=b};a.GifExportController.RESOLUTIONS=[{zoom:1},{zoom:5},{zoom:10,"default":!0},{zoom:20}];a.GifExportController.prototype.init=function(){this.radioTemplate_=pskl.utils.Template.get("gif-export-radio-template");this.uploadStatusContainerEl=document.querySelector(".gif-upload-status");this.previewContainerEl=document.querySelector(".gif-export-preview");this.radioGroupEl=document.querySelector(".gif-export-radio-group");
this.uploadForm=$("[name=gif-export-upload-form]");this.uploadForm.submit(this.onUploadFormSubmit_.bind(this));this.exportProgressStatusEl=document.querySelector(".gif-export-progress-status");this.exportProgressBarEl=document.querySelector(".gif-export-progress-bar");this.createRadioElements_()};a.GifExportController.prototype.onUploadFormSubmit_=function(b){b.originalEvent.preventDefault();b=this.getSelectedZoom_();var a=this.piskelController.getFPS();this.renderAsImageDataAnimatedGIF(b,a,this.onGifRenderingCompleted_.bind(this))};
a.GifExportController.prototype.onGifRenderingCompleted_=function(b){this.updatePreview_(b);this.previewContainerEl.classList.add("preview-upload-ongoing");pskl.app.imageUploadService.upload(b,this.onImageUploadCompleted_.bind(this))};a.GifExportController.prototype.onImageUploadCompleted_=function(b){this.updatePreview_(b);this.updateStatus_(b);this.previewContainerEl.classList.remove("preview-upload-ongoing")};a.GifExportController.prototype.updatePreview_=function(b){this.previewContainerEl.innerHTML=
"<div><img style='max-width:240px;' src='"+b+"'/></div>"};a.GifExportController.prototype.getSelectedZoom_=function(){var b=this.uploadForm.get(0).querySelectorAll("[name=gif-zoom-level]"),b=Array.prototype.slice.call(b,0).filter(function(b){return!!b.checked});if(1==b.length)return b[0].value;throw"Unexpected error when retrieving selected zoom";};a.GifExportController.prototype.createRadioElements_=function(){for(var b=a.GifExportController.RESOLUTIONS,c=0;c<b.length;c++){var d=this.createRadioForResolution_(b[c]);
this.radioGroupEl.appendChild(d)}};a.GifExportController.prototype.createRadioForResolution_=function(b){var a=b.zoom,d=a*this.piskelController.getWidth()+"x"+a*this.piskelController.getHeight(),a=pskl.utils.Template.replace(this.radioTemplate_,{value:a,label:d}),a=pskl.utils.Template.createFromHTML(a);b["default"]&&a.getElementsByTagName("input")[0].setAttribute("checked","checked");return a};a.GifExportController.prototype.blobToBase64_=function(b,a){var d=new FileReader;d.onload=function(){a(d.result)};
d.readAsDataURL(b)};a.GifExportController.prototype.renderAsImageDataAnimatedGIF=function(b,a,d){for(var e=new window.GIF({workers:2,quality:10,width:this.piskelController.getWidth()*b,height:this.piskelController.getHeight()*b}),f=0;f<this.piskelController.getFrameCount();f++){var g=this.piskelController.getFrameAt(f),g=(new pskl.rendering.CanvasRenderer(g,b)).render();e.addFrame(g.getContext("2d"),{delay:1E3/a})}e.on("progress",function(b){this.updateProgressStatus_((100*b).toFixed(2))}.bind(this));
e.on("finished",function(b){this.hideProgressStatus_();this.blobToBase64_(b,d)}.bind(this));e.render()};a.GifExportController.prototype.updateProgressStatus_=function(b){this.exportProgressStatusEl.innerHTML=b+"%";this.exportProgressBarEl.style.width=b+"%"};a.GifExportController.prototype.hideProgressStatus_=function(){this.exportProgressStatusEl.innerHTML="";this.exportProgressBarEl.style.width="0"};a.GifExportController.prototype.updateStatus_=function(b,a){if(b){var d=pskl.utils.Template.replace("<a class='image-link' href='{{link}}' target='_blank'>{{shortLink}}</a>",
{link:b,shortLink:this.shorten_(b,60,"...")});this.uploadStatusContainerEl.innerHTML="Your image is now available at : "+d}};a.GifExportController.prototype.shorten_=function(b,a,d){b.length>a&&(b=b.substring(0,a),b+=d);return b}})();(function(){var a=$.namespace("pskl.controller.settings");a.ImportController=function(b){this.piskelController=b;this.importedImage_=null};a.ImportController.prototype.init=function(){this.importForm=$("[name=import-form]");this.hiddenFileInput=$("[name=file-upload-input]");this.fileInputButton=$(".file-input-button");this.fileInputStatus=$(".file-input-status");this.fileInputStatus.html("No file selected ...");this.importPreview=$(".import-section-preview");this.resizeWidth=$("[name=resize-width]");
this.resizeHeight=$("[name=resize-height]");this.smoothResize=$("[name=smooth-resize-checkbox]");this.submitButton=$("[name=import-submit]");this.importForm.submit(this.onImportFormSubmit_.bind(this));this.hiddenFileInput.change(this.onFileUploadChange_.bind(this));this.fileInputButton.click(this.onFileInputClick_.bind(this));this.resizeWidth.keyup(this.onResizeInputKeyUp_.bind(this,"width"));this.resizeHeight.keyup(this.onResizeInputKeyUp_.bind(this,"height"))};a.ImportController.prototype.reset_=
function(){this.importForm.get(0).reset();this.fileInputStatus.html("No file selected ...");$.publish(Events.CLOSE_SETTINGS_DRAWER)};a.ImportController.prototype.onResizeInputKeyUp_=function(b,a){this.importedImage_&&this.synchronizeResizeFields_(a.target.value,b)};a.ImportController.prototype.synchronizeResizeFields_=function(b,a){b=parseInt(b,10);isNaN(b)&&(b=0);var d=this.importedImage_.height,e=this.importedImage_.width;"width"===a?this.resizeHeight.val(Math.round(b*d/e)):this.resizeWidth.val(Math.round(b*
e/d))};a.ImportController.prototype.onImportFormSubmit_=function(b){b.originalEvent.preventDefault();this.importImageToPiskel_()};a.ImportController.prototype.onFileUploadChange_=function(b){this.importFromFile_()};a.ImportController.prototype.onFileInputClick_=function(b){this.hiddenFileInput.click()};a.ImportController.prototype.importFromFile_=function(){var b=this.hiddenFileInput.get(0).files;if(1==b.length)if(b=b[0],this.isImage_(b))this.readImageFile_(b),this.enableDisabledSections_();else throw this.reset_(),
"File is not an image : "+b.type;};a.ImportController.prototype.enableDisabledSections_=function(){this.resizeWidth.removeAttr("disabled");this.resizeHeight.removeAttr("disabled");this.smoothResize.removeAttr("disabled");this.submitButton.removeAttr("disabled");this.fileInputButton.removeClass("button-primary");this.fileInputButton.blur();$(".import-section-disabled").removeClass("import-section-disabled")};a.ImportController.prototype.readImageFile_=function(b){pskl.utils.FileUtils.readFile(b,this.processImageSource_.bind(this))};
a.ImportController.prototype.processImageSource_=function(b){this.importedImage_=new Image;this.importedImage_.onload=this.onImageLoaded_.bind(this);this.importedImage_.src=b};a.ImportController.prototype.onImageLoaded_=function(b){b=this.importedImage_.width;var a=this.importedImage_.height;this.importedImage_.onload=function(){};var d=this.hiddenFileInput.val(),d=this.extractFileNameFromPath_(d);this.fileInputStatus.html(d);this.resizeWidth.val(b);this.resizeHeight.val(a);this.importPreview.width("auto");
this.importPreview.html("");this.importPreview.append(this.createImagePreview_())};a.ImportController.prototype.createImagePreview_=function(){var b=document.createElement("IMG");b.src=this.importedImage_.src;b.setAttribute("height",60);return b};a.ImportController.prototype.extractFileNameFromPath_=function(b){var a=[],a=-1!==b.indexOf("/")?b.split("/"):-1!==b.indexOf("\\")?b.split("\\"):[b];return a[a.length-1]};a.ImportController.prototype.importImageToPiskel_=function(){var b=this.importedImage_;
if(b&&window.confirm("You are about to create a new Piskel, unsaved changes will be lost.")){var a=new window.SuperGif({gif:b});a.load({success:function(){var b=a.getFrames().map(function(b){return pskl.CanvasUtils.createFromImageData(b.data)});this.createPiskelFromImages_(b)}.bind(this),error:function(){this.createPiskelFromImages_([b])}.bind(this)})}};a.ImportController.prototype.createFramesFromImages_=function(b){var a=this.resizeWidth.val(),d=this.resizeHeight.val(),e=!!this.smoothResize.prop("checked");
return b.map(function(b){b=pskl.utils.ImageResizer.resize(b,a,d,e);return pskl.utils.FrameUtils.createFromImage(b)})};a.ImportController.prototype.createPiskelFromImages_=function(b){b=this.createFramesFromImages_(b);b=pskl.model.Layer.fromFrames("Layer 1",b);var a=new pskl.model.piskel.Descriptor("Imported piskel","");b=pskl.model.Piskel.fromLayers([b],a);pskl.app.piskelController.setPiskel(b);pskl.app.animationController.setFPS(Constants.DEFAULT.FPS);this.reset_()};a.ImportController.prototype.isImage_=
function(b){return 0===b.type.indexOf("image")}})();(function(){var a=$.namespace("pskl.controller.settings");a.LocalStorageController=function(){};a.LocalStorageController.prototype.init=function(){this.localStorageItemTemplate_=pskl.utils.Template.get("local-storage-item-template");this.service_=pskl.app.localStorageService;this.piskelsList=$(".local-piskels-list");this.fillLocalPiskelsList_();this.piskelsList.click(this.onPiskelsListClick_.bind(this))};a.LocalStorageController.prototype.onPiskelsListClick_=function(b){var a=b.target.getAttribute("data-action");
b=b.target.getAttribute("data-name");"load"===a?window.confirm("This will erase your current piskel. Continue ?")&&(this.service_.load(b),$.publish(Events.CLOSE_SETTINGS_DRAWER)):"delete"===a&&window.confirm("This will permanently DELETE this piskel from your computer. Continue ?")&&(this.service_.remove(b),$.publish(Events.CLOSE_SETTINGS_DRAWER))};a.LocalStorageController.prototype.fillLocalPiskelsList_=function(){var b="",a=this.service_.getKeys(),d=function(b){return 10>b?"0"+b:""+b};a.sort(function(b,
a){return b.date<a.date?1:b.date>a.date?-1:0});a.forEach(function(a){var c=new Date(a.date),c=pskl.utils.Template.replace("{{Y}}/{{M}}/{{D}} {{H}}:{{m}}",{Y:c.getFullYear(),M:d(c.getMonth()+1),D:d(c.getDate()),H:d(c.getHours()),m:d(c.getMinutes())});b+=pskl.utils.Template.replace(this.localStorageItemTemplate_,{name:a.name,date:c})}.bind(this));this.piskelsList.get(0).tBodies[0].innerHTML=b}})();(function(){var a=$.namespace("pskl.controller.settings");a.PngExportController=function(b){this.piskelController=b};a.PngExportController.prototype.init=function(){this.previewContainerEl=document.querySelectorAll(".png-export-preview")[0];this.uploadStatusContainerEl=document.querySelectorAll(".png-upload-status")[0];document.querySelector(".png-upload-button").addEventListener("click",this.onPngUploadButtonClick_.bind(this));document.querySelector(".png-download-button").addEventListener("click",
this.onPngDownloadButtonClick_.bind(this));document.querySelector(".zip-generate-button").addEventListener("click",this.onZipButtonClick_.bind(this));this.updatePreview_(this.getFramesheetAsBase64Png())};a.PngExportController.prototype.onPngDownloadButtonClick_=function(b){var a=this.getPiskelName_()+".png";(new pskl.rendering.PiskelRenderer(this.piskelController)).renderAsCanvas().toBlob(function(b){pskl.utils.FileUtils.downloadAsFile(a,b)})};a.PngExportController.prototype.onPngUploadButtonClick_=
function(b){this.previewContainerEl.classList.add("preview-upload-ongoing");pskl.app.imageUploadService.upload(this.getFramesheetAsBase64Png(),this.onImageUploadCompleted_.bind(this))};a.PngExportController.prototype.onZipButtonClick_=function(){for(var b=new window.JSZip,a=0;a<this.piskelController.getFrameCount();a++){var d=this.piskelController.getFrameAt(a),d=this.getFrameAsCanvas_(d);b.file("sprite_"+(a+1)+".png",pskl.CanvasUtils.getBase64FromCanvas(d)+"\n",{base64:!0})}a=this.getPiskelName_()+
".zip";b=b.generate({type:"blob"});pskl.utils.FileUtils.downloadAsFile(a,b)};a.PngExportController.prototype.getFrameAsCanvas_=function(b){b=new pskl.rendering.CanvasRenderer(b,1);b.drawTransparentAs(Constants.TRANSPARENT_COLOR);return b.render()};a.PngExportController.prototype.getPiskelName_=function(){return this.piskelController.getPiskel().getDescriptor().name};a.PngExportController.prototype.getFramesheetAsBase64Png=function(){return(new pskl.rendering.PiskelRenderer(this.piskelController)).renderAsCanvas().toDataURL("image/png")};
a.PngExportController.prototype.onImageUploadCompleted_=function(b){this.updatePreview_(b);this.updateStatus_(b);this.previewContainerEl.classList.remove("preview-upload-ongoing")};a.PngExportController.prototype.updateStatus_=function(b,a){if(b){var d=pskl.utils.Template.replace("<a class='image-link' href='{{link}}' target='_blank'>{{shortLink}}</a>",{link:b,shortLink:this.shorten_(b,60,"...")});this.uploadStatusContainerEl.innerHTML="Your image is now available at : "+d}};a.PngExportController.prototype.updatePreview_=
function(b){this.previewContainerEl.innerHTML="<img class='light-picker-background' style='max-width:240px;' src='"+b+"'/>"};a.PngExportController.prototype.shorten_=function(b,a,d){b.length>a&&(b=b.substring(0,a),b+=d);return b}})();(function(){var a=$.namespace("pskl.controller.settings");a.ResizeController=function(b){this.piskelController=b};a.ResizeController.prototype.init=function(){this.resizeWidth=$("[name=resize-width]");this.resizeHeight=$("[name=resize-height]");this.resizeWidth.val(this.piskelController.getWidth());this.resizeHeight.val(this.piskelController.getHeight());this.cancelButton=$(".resize-cancel-button");this.cancelButton.click(this.onCancelButtonClicked_.bind(this));this.resizeForm=$("[name=resize-form]");
this.resizeForm.submit(this.onResizeFormSubmit_.bind(this))};a.ResizeController.prototype.onResizeFormSubmit_=function(b){b.originalEvent.preventDefault();b=parseInt(this.resizeWidth.val(),10);for(var a=parseInt(this.resizeHeight.val(),10),d=[],e=this.piskelController.getLayers(),f=0;f<e.length;f++){for(var g=[],h=e[f].getFrames(),k=0;k<h.length;k++){var l=new pskl.model.Frame(b,a);this.copyFromFrameToFrame(h[k],l);g.push(l)}g=pskl.model.Layer.fromFrames(e[f].getName(),g);d.push(g)}b=pskl.model.Piskel.fromLayers(d,
this.piskelController.getPiskel().getDescriptor());pskl.app.piskelController.setPiskel(b);$.publish(Events.CLOSE_SETTINGS_DRAWER)};a.ResizeController.prototype.copyFromFrameToFrame=function(b,a){b.forEachPixel(function(b,e,f){e<a.getWidth()&&f<a.getHeight()&&a.setPixel(e,f,b)})};a.ResizeController.prototype.onCancelButtonClicked_=function(b){$.publish(Events.CLOSE_SETTINGS_DRAWER)}})();(function(){var a=$.namespace("pskl.controller.settings");a.SaveController=function(b){this.piskelController=b};a.SaveController.prototype.init=function(){this.saveForm=$("form[name=save-form]");this.nameInput=$("#save-name");this.descriptionInput=$("#save-description");this.isPublicCheckbox=$("input[name=save-public-checkbox]");this.saveCloudButton=$("#save-cloud-button");this.saveLocalButton=$("#save-local-button");this.piskelName=$(".piskel-name").get(0);this.status=$("#save-status");var b=this.piskelController.getPiskel().getDescriptor();
this.nameInput.val(b.name);this.descriptionInput.val(b.description);this.isPublicCheckbox.prop("checked",b.isPublic);pskl.app.isLoggedIn()?this.saveForm.submit(this.onSaveFormSubmit_.bind(this)):(this.saveCloudButton.attr("disabled","disabled"),this.status.html("You are not logged in. Only Local Save is available."));this.saveLocalButton.click(this.onSaveLocalClick_.bind(this))};a.SaveController.prototype.onSaveFormSubmit_=function(b){b.preventDefault();b.stopPropagation();b=this.getName();var a=
this.getDescription(),d=!!this.isPublicCheckbox.prop("checked");b=new pskl.model.piskel.Descriptor(b,a,d);this.piskelController.getPiskel().setDescriptor(b);this.beforeSaving_();pskl.app.store({success:this.onSaveSuccess_.bind(this),error:this.onSaveError_.bind(this),after:this.afterSaving_.bind(this)})};a.SaveController.prototype.onSaveLocalClick_=function(b){b=pskl.app.localStorageService;var a=!0,d=this.getName(),e=this.getDescription();b.getPiskel(d)&&(a=window.confirm("There is already a piskel saved as "+
d+". Override ?"));a&&(this.beforeSaving_(),b.save(d,e,pskl.app.piskelController.serialize()),window.setTimeout(function(){this.onSaveSuccess_();this.afterSaving_()}.bind(this),1E3))};a.SaveController.prototype.getName=function(){return this.nameInput.val()};a.SaveController.prototype.getDescription=function(){return this.descriptionInput.val()};a.SaveController.prototype.beforeSaving_=function(){this.saveCloudButton.attr("disabled",!0);this.status.html("Saving ...");this.piskelName&&this.piskelName.classList.add("piskel-name-saving")};
a.SaveController.prototype.onSaveSuccess_=function(){$.publish(Events.CLOSE_SETTINGS_DRAWER);$.publish(Events.SHOW_NOTIFICATION,[{content:"Successfully saved !"}]);$.publish(Events.PISKEL_SAVED)};a.SaveController.prototype.onSaveError_=function(b){$.publish(Events.SHOW_NOTIFICATION,[{content:"Saving failed ("+b+")"}])};a.SaveController.prototype.afterSaving_=function(){this.saveCloudButton.attr("disabled",!1);this.status.html("");this.piskelName&&this.piskelName.classList.remove("piskel-name-saving");
window.setTimeout($.publish.bind($,Events.HIDE_NOTIFICATION),2E3)}})();(function(){var a=$.namespace("pskl.controller.settings"),b={user:{template:"templates/settings/application.html",controller:a.ApplicationSettingsController},resize:{template:"templates/settings/resize.html",controller:a.ResizeController},gif:{template:"templates/settings/export-gif.html",controller:a.GifExportController},png:{template:"templates/settings/export-png.html",controller:a.PngExportController},"import":{template:"templates/settings/import.html",controller:a.ImportController},localstorage:{template:"templates/settings/localstorage.html",
controller:a.LocalStorageController},save:{template:"templates/settings/save.html",controller:a.SaveController}};a.SettingsController=function(b){this.piskelController=b;this.drawerContainer=document.getElementById("drawer-container");this.settingsContainer=$("[data-pskl-controller=settings]");this.isExpanded=!1;this.currentSetting=null};a.SettingsController.prototype.init=function(){$("[data-setting]").click(this.onSettingIconClick.bind(this));$("body").click(this.onBodyClick.bind(this));$.subscribe(Events.CLOSE_SETTINGS_DRAWER,
this.closeDrawer.bind(this))};a.SettingsController.prototype.onSettingIconClick=function(b){var a=b.originalEvent.currentTarget.getAttribute("data-setting");this.currentSetting!=a?this.loadSetting(a):this.closeDrawer();b.originalEvent.stopPropagation();b.originalEvent.preventDefault()};a.SettingsController.prototype.onBodyClick=function(b){var a=b.target;b=pskl.utils.Dom.isParent(a,this.drawerContainer);a=a.getAttribute("data-setting");this.isExpanded&&!b&&!a&&this.closeDrawer()};a.SettingsController.prototype.loadSetting=
function(a){this.drawerContainer.innerHTML=pskl.utils.Template.get(b[a].template);(new b[a].controller(this.piskelController)).init();this.settingsContainer.addClass("expanded");$(".has-expanded-drawer").removeClass("has-expanded-drawer");$("[data-setting="+a+"]").addClass("has-expanded-drawer");this.isExpanded=!0;this.currentSetting=a};a.SettingsController.prototype.closeDrawer=function(){this.settingsContainer.removeClass("expanded");$(".has-expanded-drawer").removeClass("has-expanded-drawer");
this.isExpanded=!1;this.currentSetting=null}})();(function(){var a=$.namespace("pskl.drawingtools");a.BaseTool=function(){this.toolId="tool-base"};a.BaseTool.prototype.applyToolAt=function(b,a,d,e,f,g){};a.BaseTool.prototype.moveToolAt=function(b,a,d,e,f,g){};a.BaseTool.prototype.replay=Constants.ABSTRACT_FUNCTION;a.BaseTool.prototype.moveUnactiveToolAt=function(b,a,d,e,f,g){f.containsPixel(b,a)?(isNaN(this.highlightedPixelCol)||isNaN(this.highlightedPixelRow)||this.highlightedPixelRow==a&&this.highlightedPixelCol==b||f.clear(),f.setPixel(b,a,Constants.TOOL_TARGET_HIGHLIGHT_COLOR),
this.highlightedPixelCol=b,this.highlightedPixelRow=a):this.hideHighlightedPixel(f)};a.BaseTool.prototype.hideHighlightedPixel=function(b){if(null!==this.highlightedPixelRow&&null!==this.highlightedPixelCol){try{b.setPixel(this.highlightedPixelCol,this.highlightedPixelRow,Constants.TRANSPARENT_COLOR)}catch(a){console.warn("ns.BaseTool.prototype.hideHighlightedPixel failed")}this.highlightedPixelCol=this.highlightedPixelRow=null}};a.BaseTool.prototype.raiseSaveStateEvent=function(b){$.publish(Events.PISKEL_SAVE_STATE,
{type:"REPLAY",scope:this,replay:b})};a.BaseTool.prototype.releaseToolAt=function(b,a,d,e,f,g){};a.BaseTool.prototype.getLinePixels_=function(b,a,d,e){for(var f=[],g=Math.abs(a-b),h=Math.abs(e-d),k=b<a?1:-1,l=d<e?1:-1,m=g-h;;){f.push({col:b,row:d});if(b==a&&d==e)break;var n=2*m;n>-h&&(m-=h,b+=k);n<g&&(m+=g,d+=l)}return f}})();(function(){var a=$.namespace("pskl.drawingtools");a.Circle=function(){a.ShapeTool.call(this);this.toolId="tool-circle";this.helpText="Circle tool"};pskl.utils.inherit(a.Circle,a.ShapeTool);a.Circle.prototype.draw_=function(b,a,d,e){b=this.getCirclePixels_(this.startCol,this.startRow,b,a);for(a=0;a<b.length;a++)e.setPixel(b[a].col,b[a].row,d)};a.Circle.prototype.getCirclePixels_=function(b,a,d,e){b=pskl.PixelUtils.getOrderedRectangleCoordinates(b,a,d,e);a=(b.x0+b.x1)/2;d=(b.y0+b.y1)/2;e=b.x1-a;var f=
b.y1-d,g=[],h,k,l;for(h=b.x0;h<b.x1;h++)l=Math.acos((h-a)/e),k=Math.round(f*Math.sin(l)+d),g.push({col:h,row:k}),g.push({col:2*a-h,row:2*d-k});for(k=b.y0;k<b.y1;k++)l=Math.asin((k-d)/f),h=Math.round(e*Math.cos(l)+a),g.push({col:h,row:k}),g.push({col:2*a-h,row:2*d-k});return g}})();(function(){var a=$.namespace("pskl.drawingtools");a.ColorPicker=function(){this.toolId="tool-colorpicker";this.helpText="Color picker"};pskl.utils.inherit(a.ColorPicker,a.BaseTool);a.ColorPicker.prototype.applyToolAt=function(b,a,d,e,f,g){e.containsPixel(b,a)&&(b=e.getPixel(b,a),g.button==Constants.LEFT_BUTTON?$.publish(Events.SELECT_PRIMARY_COLOR,[b]):g.button==Constants.RIGHT_BUTTON&&$.publish(Events.SELECT_SECONDARY_COLOR,[b]))}})();(function(){var a=$.namespace("pskl.drawingtools");a.Eraser=function(){this.toolId="tool-eraser";this.helpText="Eraser tool"};pskl.utils.inherit(a.Eraser,a.SimplePen);a.Eraser.prototype.applyToolAt=function(b,a,d,e,f,g){this.superclass.applyToolAt.call(this,b,a,Constants.TRANSPARENT_COLOR,e,f,g)}})();(function(){var a=$.namespace("pskl.drawingtools");a.Move=function(){this.toolId=a.Move.TOOL_ID;this.helpText="Move tool";this.startRow=this.startCol=null};a.Move.TOOL_ID="tool-move";pskl.utils.inherit(a.Move,a.BaseTool);a.Move.prototype.applyToolAt=function(b,a,d,e,f,g){this.startCol=b;this.startRow=a;this.frameClone=e.clone()};a.Move.prototype.moveToolAt=function(b,a,d,e,f,g){this.shiftFrame(b-this.startCol,a-this.startRow,e,this.frameClone)};a.Move.prototype.shiftFrame=function(b,a,d,e){for(var f,
g=0;g<d.getWidth();g++)for(var h=0;h<d.getHeight();h++)f=e.containsPixel(g-b,h-a)?e.getPixel(g-b,h-a):Constants.TRANSPARENT_COLOR,d.setPixel(g,h,f)};a.Move.prototype.releaseToolAt=function(b,a,d,e,f,g){this.moveToolAt(b,a,d,e,f);this.raiseSaveStateEvent({colDiff:b-this.startCol,rowDiff:a-this.startRow})};a.Move.prototype.replay=function(b,a){this.shiftFrame(a.colDiff,a.rowDiff,b,b.clone())}})();(function(){var a=$.namespace("pskl.drawingtools");a.PaintBucket=function(){this.toolId="tool-paint-bucket";this.helpText="Paint bucket tool"};pskl.utils.inherit(a.PaintBucket,a.BaseTool);a.PaintBucket.prototype.applyToolAt=function(b,a,d,e,f,g){pskl.PixelUtils.paintSimilarConnectedPixelsFromFrame(e,b,a,d);this.raiseSaveStateEvent({col:b,row:a,color:d})};a.PaintBucket.prototype.replay=function(b,a){pskl.PixelUtils.paintSimilarConnectedPixelsFromFrame(b,a.col,a.row,a.color)}})();(function(){var a=$.namespace("pskl.drawingtools");a.Rectangle=function(){a.ShapeTool.call(this);this.toolId="tool-rectangle";this.helpText="Rectangle tool"};pskl.utils.inherit(a.Rectangle,a.ShapeTool);a.Rectangle.prototype.draw_=function(b,a,d,e){b=pskl.PixelUtils.getBoundRectanglePixels(this.startCol,this.startRow,b,a);for(a=0;a<b.length;a++)e.setPixel(b[a].col,b[a].row,d)}})();(function(){var a=$.namespace("pskl.drawingtools");a.ShapeTool=function(){this.startRow=this.startCol=null};pskl.utils.inherit(a.ShapeTool,a.BaseTool);a.ShapeTool.prototype.applyToolAt=function(b,a,d,e,f,g){$.publish(Events.DRAG_START,[b,a]);this.startCol=b;this.startRow=a;f.setPixel(b,a,d)};a.ShapeTool.prototype.moveToolAt=function(b,a,d,e,f,g){b=this.getCoordinates_(b,a,g);$.publish(Events.CURSOR_MOVED,[b.col,b.row]);f.clear();d==Constants.TRANSPARENT_COLOR&&(d=Constants.SELECTION_TRANSPARENT_COLOR);
this.draw_(b.col,b.row,d,f)};a.ShapeTool.prototype.releaseToolAt=function(b,a,d,e,f,g){f.clear();g.shiftKey&&(a=this.getScaledCoordinates_(b,a),b=a.col,a=a.row);g=this.getCoordinates_(b,a,g);this.draw_(g.col,g.row,d,e);$.publish(Events.DRAG_END,[b,a]);this.raiseSaveStateEvent({col:b,row:a,startCol:this.startCol,startRow:this.startRow,color:d})};a.ShapeTool.prototype.replay=function(b,a){this.startCol=a.startCol;this.startRow=a.startRow;this.draw_(a.col,a.row,a.color,b)};a.ShapeTool.prototype.getCoordinates_=
function(b,a,d){return d.shiftKey?this.getScaledCoordinates_(b,a):{col:b,row:a}};a.ShapeTool.prototype.getScaledCoordinates_=function(b,a){var d=this.startCol-b,e=Math.abs(d),f=this.startRow-a,g=Math.abs(f),h=Math.min(e,g);a=this.startRow-f/g*h;b=this.startCol-d/e*h;return{col:b,row:a}};a.ShapeTool.prototype.draw_=Constants.ABSTRACT_FUNCTION})();(function(){var a=$.namespace("pskl.drawingtools");a.SimplePen=function(){this.toolId="tool-pen";this.helpText="Pen tool";this.previousRow=this.previousCol=null;this.pixels=[]};pskl.utils.inherit(a.SimplePen,a.BaseTool);a.SimplePen.prototype.applyToolAt=function(b,a,d,e,f,g){e.setPixel(b,a,d);this.previousCol=b;this.previousRow=a;this.pixels.push({col:b,row:a})};a.SimplePen.prototype.moveToolAt=function(b,a,d,e,f,g){if(1<Math.abs(b-this.previousCol)||1<Math.abs(a-this.previousRow)){g=this.getLinePixels_(b,
this.previousCol,a,this.previousRow);for(var h=0,k=g.length;h<k;h++){var l=g[h];this.applyToolAt(l.col,l.row,d,e,f)}}else this.applyToolAt(b,a,d,e,f);this.previousCol=b;this.previousRow=a};a.SimplePen.prototype.releaseToolAt=function(b,a,d,e,f,g){this.raiseSaveStateEvent({pixels:this.pixels.slice(0),color:d});this.pixels=[]};a.SimplePen.prototype.replay=function(b,a){a.pixels.forEach(function(d){b.setPixel(d.col,d.row,a.color)})}})();(function(){var a=$.namespace("pskl.drawingtools");a.Stroke=function(){this.toolId="tool-stroke";this.helpText="Stroke tool";this.startRow=this.startCol=null};pskl.utils.inherit(a.Stroke,a.BaseTool);a.Stroke.prototype.applyToolAt=function(b,a,d,e,f,g){this.startCol=b;this.startRow=a;f.setPixel(b,a,d)};a.Stroke.prototype.moveToolAt=function(b,a,d,e,f,g){f.clear();b=this.getLinePixels_(this.startCol,b,this.startRow,a);for(a=0;a<b.length;a++)d==Constants.TRANSPARENT_COLOR&&(d=Constants.SELECTION_TRANSPARENT_COLOR),
f.setPixel(b[a].col,b[a].row,d)};a.Stroke.prototype.releaseToolAt=function(b,a,d,e,f,g){b=this.getLinePixels_(this.startCol,b,this.startRow,a);for(a=0;a<b.length;a++)e.setPixel(b[a].col,b[a].row,d);f.clear();this.raiseSaveStateEvent({pixels:b,color:d})};a.Stroke.prototype.replay=function(b,a){a.pixels.forEach(function(d){b.setPixel(d.col,d.row,a.color)})}})();(function(){var a=$.namespace("pskl.drawingtools");a.VerticalMirrorPen=function(){this.superclass.constructor.call(this);this.toolId="tool-vertical-mirror-pen";this.helpText="vertical mirror pen tool";this.swap=null};pskl.utils.inherit(a.VerticalMirrorPen,a.SimplePen);a.VerticalMirrorPen.prototype.setMirrorContext=function(){this.swap=this.previousCol;this.previousCol=this.mirroredPreviousCol};a.VerticalMirrorPen.prototype.unsetMirrorContext=function(){this.mirroredPreviousCol=this.previousCol;this.previousCol=
this.swap};a.VerticalMirrorPen.prototype.applyToolAt=function(b,a,d,e,f,g){this.superclass.applyToolAt.call(this,b,a,d,e,f);this.mirroredPreviousCol=b=this.getSymmetricCol_(b,e);this.setMirrorContext();this.superclass.applyToolAt.call(this,b,a,d,e,f);this.unsetMirrorContext()};a.VerticalMirrorPen.prototype.getSymmetricCol_=function(b,a){return a.getWidth()-b-1}})();(function(){var a=$.namespace("pskl.drawingtools");a.BaseSelect=function(){this.secondaryToolId=pskl.drawingtools.Move.TOOL_ID;this.BodyRoot=$("body");this.startRow=this.startCol=null};pskl.utils.inherit(a.BaseSelect,a.BaseTool);a.BaseSelect.prototype.applyToolAt=function(b,a,d,e,f,g){this.startCol=b;this.startRow=a;this.lastCol=b;this.lastRow=a;f.getPixel(b,a)!=Constants.SELECTION_TRANSPARENT_COLOR?(this.mode="select",this.onSelectStart_(b,a,d,e,f)):(this.mode="moveSelection",this.onSelectionDragStart_(b,
a,d,e,f))};a.BaseSelect.prototype.moveToolAt=function(b,a,d,e,f,g){if("select"==this.mode)this.onSelect_(b,a,d,e,f);else if("moveSelection"==this.mode)this.onSelectionDrag_(b,a,d,e,f)};a.BaseSelect.prototype.releaseToolAt=function(b,a,d,e,f,g){if("select"==this.mode)this.onSelectEnd_(b,a,d,e,f);else if("moveSelection"==this.mode)this.onSelectionDragEnd_(b,a,d,e,f)};a.BaseSelect.prototype.moveUnactiveToolAt=function(b,a,d,e,f,g){f.containsPixel(b,a)&&(f.getPixel(b,a)!=Constants.SELECTION_TRANSPARENT_COLOR?
(this.BodyRoot.addClass(this.toolId),this.BodyRoot.removeClass(this.secondaryToolId)):(this.BodyRoot.addClass(this.secondaryToolId),this.BodyRoot.removeClass(this.toolId)))};a.BaseSelect.prototype.hideHighlightedPixel=function(){};a.BaseSelect.prototype.drawSelectionOnOverlay_=function(b,a){for(var d=b.pixels,e=0,f=d.length;e<f;e++)a.setPixel(d[e].col,d[e].row,Constants.SELECTION_TRANSPARENT_COLOR)};a.BaseSelect.prototype.shiftOverlayFrame_=function(b,a,d,e){for(var f,g=0;g<d.getWidth();g++)for(var h=
0;h<d.getHeight();h++)f=e.containsPixel(g-b,h-a)?e.getPixel(g-b,h-a):Constants.TRANSPARENT_COLOR,d.setPixel(g,h,f)};a.BaseSelect.prototype.onSelectStart_=function(b,a,d,e,f){};a.BaseSelect.prototype.onSelect_=function(b,a,d,e,f){};a.BaseSelect.prototype.onSelectEnd_=function(b,a,d,e,f){};a.BaseSelect.prototype.onSelectionDragStart_=function(b,a,d,e,f){this.overlayFrameReference=f.clone()};a.BaseSelect.prototype.onSelectionDrag_=function(b,a,d,e,f){d=b-this.lastCol;e=a-this.lastRow;this.shiftOverlayFrame_(b-
this.startCol,a-this.startRow,f,this.overlayFrameReference);$.publish(Events.SELECTION_MOVE_REQUEST,[d,e]);this.lastCol=b;this.lastRow=a};a.BaseSelect.prototype.onSelectionDragEnd_=function(b,a,d,e,f){this.onSelectionDrag_(b,a,d,e,f)}})();(function(){var a=$.namespace("pskl.drawingtools");a.RectangleSelect=function(){this.toolId="tool-rectangle-select";this.helpText="Rectangle selection tool";a.BaseSelect.call(this)};pskl.utils.inherit(a.RectangleSelect,a.BaseSelect);a.RectangleSelect.prototype.onSelectStart_=function(b,a,d,e,f){$.publish(Events.DRAG_START,[b,a]);f.setPixel(b,a,d)};a.RectangleSelect.prototype.onSelect_=function(b,a,d,e,f){f.clear();this.startCol==b&&this.startRow==a?$.publish(Events.SELECTION_DISMISSED):(b=new pskl.selection.RectangularSelection(this.startCol,
this.startRow,b,a),$.publish(Events.SELECTION_CREATED,[b]),this.drawSelectionOnOverlay_(b,f))};a.RectangleSelect.prototype.onSelectEnd_=function(b,a,d,e,f){this.onSelect_(b,a,d,e,f);$.publish(Events.DRAG_END,[b,a])}})();(function(){var a=$.namespace("pskl.drawingtools");a.ShapeSelect=function(){this.toolId="tool-shape-select";this.helpText="Shape selection tool";a.BaseSelect.call(this)};pskl.utils.inherit(a.ShapeSelect,a.BaseSelect);a.ShapeSelect.prototype.onSelectStart_=function(b,a,d,e,f){$.publish(Events.SELECTION_DISMISSED);f.clear();b=pskl.PixelUtils.getSimilarConnectedPixelsFromFrame(e,b,a);b=new pskl.selection.ShapeSelection(b);$.publish(Events.SELECTION_CREATED,[b]);this.drawSelectionOnOverlay_(b,f)}})();(function(){var a=$.namespace("pskl.model"),b=0;a.Frame=function(c,d){if(c&&d)this.width=c,this.height=d,this.id=b++,this.version=0,this.pixels=a.Frame.createEmptyPixelGrid_(c,d),this.previousStates=[this.getPixels()],this.stateIndex=0;else throw"Bad arguments in pskl.model.Frame constructor : "+c+", "+d;};a.Frame.fromPixelGrid=function(b){if(b.length&&b[0].length){var a=new pskl.model.Frame(b.length,b[0].length);a.setPixels(b);return a}throw"Bad arguments in pskl.model.Frame.fromPixelGrid : "+b;
};a.Frame.createEmptyPixelGrid_=function(b,a){for(var e=[],f=0;f<b;f++){for(var g=[],h=0;h<a;h++)g.push(Constants.TRANSPARENT_COLOR);e[f]=g}return e};a.Frame.createEmptyFromFrame=function(b){return new a.Frame(b.getWidth(),b.getHeight())};a.Frame.prototype.clone=function(){var b=new a.Frame(this.width,this.height);b.setPixels(this.getPixels());return b};a.Frame.prototype.getPixels=function(){return this.clonePixels_(this.pixels)};a.Frame.prototype.setPixels=function(b){this.pixels=this.clonePixels_(b);
this.version++};a.Frame.prototype.clear=function(){var b=a.Frame.createEmptyPixelGrid_(this.getWidth(),this.getHeight());this.setPixels(b)};a.Frame.prototype.clonePixels_=function(b){for(var a=[],e=0;e<b.length;e++)a[e]=b[e].slice(0,b[e].length);return a};a.Frame.prototype.getHash=function(){return[this.id,this.version].join("-")};a.Frame.prototype.setPixel=function(b,a,e){this.containsPixel(b,a)&&this.pixels[b][a]!==e&&(this.pixels[b][a]=e,this.version++)};a.Frame.prototype.getPixel=function(b,a){return this.containsPixel(b,
a)?this.pixels[b][a]:null};a.Frame.prototype.forEachPixel=function(b){for(var a=0;a<this.getWidth();a++)for(var e=0;e<this.getHeight();e++)b(this.getPixel(a,e),a,e)};a.Frame.prototype.getWidth=function(){return this.width};a.Frame.prototype.getHeight=function(){return this.height};a.Frame.prototype.containsPixel=function(b,a){return 0<=b&&0<=a&&b<this.width&&a<this.height};a.Frame.prototype.saveState=function(){this.previousStates.length=this.stateIndex+1;this.previousStates.push(this.getPixels());
this.stateIndex=this.previousStates.length-1};a.Frame.prototype.loadPreviousState=function(){0<this.stateIndex&&(this.stateIndex--,this.setPixels(this.previousStates[this.stateIndex]))};a.Frame.prototype.loadNextState=function(){this.stateIndex<this.previousStates.length-1&&(this.stateIndex++,this.setPixels(this.previousStates[this.stateIndex]))};a.Frame.prototype.isSameSize=function(b){return this.getHeight()==b.getHeight()&&this.getWidth()==b.getWidth()}})();(function(){var a=$.namespace("pskl.model");a.Layer=function(b){if(b)this.name=b,this.frames=[];else throw"Invalid arguments in Layer constructor : 'name' is mandatory";};a.Layer.fromFrames=function(b,c){var d=new a.Layer(b);c.forEach(d.addFrame.bind(d));return d};a.Layer.prototype.getName=function(){return this.name};a.Layer.prototype.setName=function(b){this.name=b};a.Layer.prototype.getFrames=function(){return this.frames};a.Layer.prototype.getFrameAt=function(b){return this.frames[b]};a.Layer.prototype.addFrame=
function(b){this.frames.push(b)};a.Layer.prototype.addFrameAt=function(b,a){this.frames.splice(a,0,b)};a.Layer.prototype.removeFrame=function(b){b=this.frames.indexOf(b);this.removeFrameAt(b)};a.Layer.prototype.removeFrameAt=function(b){if(this.frames[b])this.frames.splice(b,1);else throw"Invalid index in removeFrameAt : "+b+" (size : "+this.length()+")";};a.Layer.prototype.moveFrame=function(b,a){var d=this.frames.splice(b,1)[0];this.frames.splice(a,0,d)};a.Layer.prototype.swapFramesAt=function(b,
a){var d=this.frames[b],e=this.frames[a];if(d&&e)this.frames[a]=d,this.frames[b]=e;else throw console.log("frames",this.frames),console.log("fromIndex",b,"toIndex",a),"Frame not found in moveFrameAt";};a.Layer.prototype.duplicateFrame=function(b){b=this.frames.indexOf(b);this.duplicateFrameAt(b)};a.Layer.prototype.duplicateFrameAt=function(b){var a=this.frames[b];if(a)a=a.clone(),this.addFrameAt(a,b);else throw"Frame not found in duplicateFrameAt";};a.Layer.prototype.length=function(){return this.frames.length}})();(function(){var a=$.namespace("pskl.model");a.Piskel=function(b,a,d){if(b&&a&&d)this.layers=[],this.width=b,this.height=a,this.descriptor=d;else throw"Missing arguments in Piskel constructor : "+Array.prototype.join.call(arguments,",");};a.Piskel.fromLayers=function(b,a){var d=null;if(0<b.length&&0<b[0].length())d=b[0].getFrameAt(0),d=new pskl.model.Piskel(d.getWidth(),d.getHeight(),a),b.forEach(d.addLayer.bind(d));else throw"Piskel.fromLayers expects array of non empty pskl.model.Layer as first argument";
return d};a.Piskel.prototype.getLayers=function(){return this.layers};a.Piskel.prototype.getHeight=function(){return this.height};a.Piskel.prototype.getWidth=function(){return this.width};a.Piskel.prototype.getLayers=function(){return this.layers};a.Piskel.prototype.getLayerAt=function(b){return this.layers[b]};a.Piskel.prototype.getLayersByName=function(b){return this.layers.filter(function(a){return a.getName()==b})};a.Piskel.prototype.addLayer=function(b){this.layers.push(b)};a.Piskel.prototype.moveLayerUp=
function(b){var a=this.layers.indexOf(b);-1<a&&a<this.layers.length-1&&(this.layers[a]=this.layers[a+1],this.layers[a+1]=b)};a.Piskel.prototype.moveLayerDown=function(b){var a=this.layers.indexOf(b);0<a&&(this.layers[a]=this.layers[a-1],this.layers[a-1]=b)};a.Piskel.prototype.removeLayer=function(b){b=this.layers.indexOf(b);-1!=b&&this.layers.splice(b,1)};a.Piskel.prototype.removeLayerAt=function(b){this.layers.splice(b,1)};a.Piskel.prototype.getDescriptor=function(){return this.descriptor};a.Piskel.prototype.setDescriptor=
function(b){this.descriptor=b;$(".piskel-name").html(this.descriptor.name)}})();(function(){$.namespace("pskl.model.piskel").Descriptor=function(a,b,c){this.name=a;this.description=b;this.isPublic=c}})();(function(){var a=$.namespace("pskl.rendering");a.AbstractRenderer=function(){};a.AbstractRenderer.prototype.clear=Constants.ABSTRACT_FUNCTION;a.AbstractRenderer.prototype.getCoordinates=Constants.ABSTRACT_FUNCTION;a.AbstractRenderer.prototype.setGridWidth=Constants.ABSTRACT_FUNCTION;a.AbstractRenderer.prototype.getGridWidth=Constants.ABSTRACT_FUNCTION;a.AbstractRenderer.prototype.setZoom=Constants.ABSTRACT_FUNCTION;a.AbstractRenderer.prototype.getZoom=Constants.ABSTRACT_FUNCTION;a.AbstractRenderer.prototype.moveOffset=
Constants.ABSTRACT_FUNCTION;a.AbstractRenderer.prototype.setOffset=Constants.ABSTRACT_FUNCTION;a.AbstractRenderer.prototype.getOffset=Constants.ABSTRACT_FUNCTION;a.AbstractRenderer.prototype.setDisplaySize=Constants.ABSTRACT_FUNCTION;a.AbstractRenderer.prototype.getDisplaySize=Constants.ABSTRACT_FUNCTION})();(function(){var a=$.namespace("pskl.rendering");a.CanvasRenderer=function(b,a){this.frame=b;this.zoom=a;this.transparentColor_="white"};a.CanvasRenderer.prototype.drawTransparentAs=function(b){this.transparentColor_=b};a.CanvasRenderer.prototype.render=function(){var b=this.createCanvas_(),a=b.getContext("2d");this.frame.forEachPixel(function(b,e,f){this.renderPixel_(b,e,f,a)}.bind(this));return b};a.CanvasRenderer.prototype.renderPixel_=function(b,a,d,e){b==Constants.TRANSPARENT_COLOR&&(b=this.transparentColor_);
e.fillStyle=b;e.fillRect(a*this.zoom,d*this.zoom,this.zoom,this.zoom)};a.CanvasRenderer.prototype.createCanvas_=function(){var b=this.frame.getWidth()*this.zoom,a=this.frame.getHeight()*this.zoom;return pskl.CanvasUtils.createCanvas(b,a)}})();(function(){var a=$.namespace("pskl.rendering");a.CompositeRenderer=function(){this.renderers=[]};pskl.utils.inherit(pskl.rendering.CompositeRenderer,pskl.rendering.AbstractRenderer);a.CompositeRenderer.prototype.add=function(b){this.renderers.push(b);return this};a.CompositeRenderer.prototype.clear=function(){this.renderers.forEach(function(b){b.clear()})};a.CompositeRenderer.prototype.setZoom=function(b){this.renderers.forEach(function(a){a.setZoom(b)})};a.CompositeRenderer.prototype.getZoom=function(){return this.getSampleRenderer_().getZoom()};
a.CompositeRenderer.prototype.setDisplaySize=function(b,a){this.renderers.forEach(function(d){d.setDisplaySize(b,a)})};a.CompositeRenderer.prototype.getDisplaySize=function(){return this.getSampleRenderer_().getDisplaySize()};a.CompositeRenderer.prototype.moveOffset=function(b,a){this.renderers.forEach(function(d){d.moveOffset(b,a)})};a.CompositeRenderer.prototype.setOffset=function(b,a){this.renderers.forEach(function(d){d.setOffset(b,a)})};a.CompositeRenderer.prototype.getOffset=function(){return this.getSampleRenderer_().getOffset()};
a.CompositeRenderer.prototype.setGridWidth=function(b){this.renderers.forEach(function(a){a.setGridWidth(b)})};a.CompositeRenderer.prototype.getGridWidth=function(){return this.getSampleRenderer_().getGridWidth()};a.CompositeRenderer.prototype.getSampleRenderer_=function(){if(0<this.renderers.length)return this.renderers[0];throw"Renderer manager is empty";}})();(function(){var a=$.namespace("pskl.rendering");a.DrawingLoop=function(){this.requestAnimationFrame=this.getRequestAnimationFrameShim_();this.isRunning=!1;this.previousTime=0;this.callbacks=[]};a.DrawingLoop.prototype.addCallback=function(b,a,d){b={fn:b,scope:a,args:d};this.callbacks.push(b);return b};a.DrawingLoop.prototype.removeCallback=function(b){b=this.callbacks.indexOf(b);-1!=b&&this.callbacks.splice(b,1)};a.DrawingLoop.prototype.start=function(){this.isRunning=!0;this.loop_()};a.DrawingLoop.prototype.loop_=
function(){var b=Date.now();this.executeCallbacks_(b-this.previousTime);this.previousTime=b;this.requestAnimationFrame.call(window,this.loop_.bind(this))};a.DrawingLoop.prototype.executeCallbacks_=function(b){for(var a=0;a<this.callbacks.length;a++){var d=this.callbacks[a];d.fn.call(d.scope,b,d.args)}};a.DrawingLoop.prototype.stop=function(){this.isRunning=!1};a.DrawingLoop.prototype.getRequestAnimationFrameShim_=function(){return window.requestAnimationFrame||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||
window.msRequestAnimationFrame||function(b){window.setTimeout(b,1E3/60)}}})();(function(){var a=$.namespace("pskl.rendering");a.FramesheetRenderer=function(b){if(0<b.length)this.frames=b;else throw"FramesheetRenderer : Invalid argument : frames is empty";};a.FramesheetRenderer.prototype.renderAsCanvas=function(){for(var b=this.createCanvas_(),a=0;a<this.frames.length;a++){var d=this.frames[a];this.drawFrameInCanvas_(d,b,a*d.getWidth(),0)}return b};a.FramesheetRenderer.prototype.drawFrameInCanvas_=function(b,a,d,e){var f=a.getContext("2d");b.forEachPixel(function(b,a,c){b!=
Constants.TRANSPARENT_COLOR&&(f.fillStyle=b,f.fillRect(a+d,c+e,1,1))})};a.FramesheetRenderer.prototype.createCanvas_=function(){var b=this.frames[0],a=this.frames.length*b.getWidth(),b=b.getHeight();return pskl.CanvasUtils.createCanvas(a,b)}})();(function(){var a=$.namespace("pskl.rendering");a.PiskelRenderer=function(b){for(var c=[],d=0;d<b.getFrameCount();d++)c.push(b.getFrameAt(d));a.FramesheetRenderer.call(this,c)};pskl.utils.inherit(a.PiskelRenderer,a.FramesheetRenderer)})();(function(){var a=$.namespace("pskl.rendering.frame");a.CachedFrameRenderer=function(b,a,d){pskl.rendering.frame.FrameRenderer.call(this,b,a,d);this.serializedFrame=""};pskl.utils.inherit(pskl.rendering.frame.CachedFrameRenderer,pskl.rendering.frame.FrameRenderer);a.CachedFrameRenderer.prototype.setDisplaySize=function(b,a){this.displayWidth===b&&this.displayHeight===a||this.superclass.setDisplaySize.call(this,b,a)};a.CachedFrameRenderer.prototype.render=function(b){var a=this.getOffset(),d=this.getDisplaySize(),
a=[this.getZoom(),this.getGridWidth(),a.x,a.y,d.width,d.height,b.getHash()].join("-");this.serializedFrame!=a&&(this.serializedFrame=a,this.superclass.render.call(this,b))}})();(function(){var a=$.namespace("pskl.rendering.frame");a.FrameRenderer=function(b,a,d){this.defaultRenderingOptions={supportGridRendering:!1,zoom:1};a=$.extend(!0,{},this.defaultRenderingOptions,a);if(void 0===b)throw"Bad FrameRenderer initialization. <container> undefined.";if(isNaN(a.zoom))throw"Bad FrameRenderer initialization. <zoom> not well defined.";this.container=b;this.zoom=a.zoom;this.offset={x:0,y:0};this.margin={x:0,y:0};this.supportGridRendering=a.supportGridRendering;this.classes=d||
[];this.classes.push("canvas");this.displayCanvas=this.canvas=null;this.setDisplaySize(a.width,a.height);this.setGridWidth(pskl.UserSettings.get(pskl.UserSettings.GRID_WIDTH));this.updateBackgroundClass_(pskl.UserSettings.get(pskl.UserSettings.CANVAS_BACKGROUND));$.subscribe(Events.USER_SETTINGS_CHANGED,$.proxy(this.onUserSettingsChange_,this))};pskl.utils.inherit(pskl.rendering.frame.FrameRenderer,pskl.rendering.AbstractRenderer);a.FrameRenderer.prototype.render=function(b){b&&(this.clear(),this.renderFrame_(b))};
a.FrameRenderer.prototype.clear=function(){pskl.CanvasUtils.clear(this.canvas);pskl.CanvasUtils.clear(this.displayCanvas)};a.FrameRenderer.prototype.setZoom=function(b){if(b>Constants.MINIMUM_ZOOM){var a=this.offset.x+this.displayWidth/(2*this.zoom),d=this.offset.y+this.displayHeight/(2*this.zoom);this.zoom=b;this.setOffset(a-this.displayWidth/(2*this.zoom),d-this.displayHeight/(2*this.zoom))}};a.FrameRenderer.prototype.getZoom=function(){return this.zoom};a.FrameRenderer.prototype.setDisplaySize=
function(b,a){this.displayWidth=b;this.displayHeight=a;this.displayCanvas&&($(this.displayCanvas).remove(),this.displayCanvas=null);this.createDisplayCanvas_()};a.FrameRenderer.prototype.getDisplaySize=function(){return{height:this.displayHeight,width:this.displayWidth}};a.FrameRenderer.prototype.getOffset=function(){return{x:this.offset.x,y:this.offset.y}};a.FrameRenderer.prototype.moveOffset=function(b,a){this.setOffset(this.offset.x+b,this.offset.y+a)};a.FrameRenderer.prototype.setOffset=function(b,
a){this.canvas&&(b=pskl.utils.Math.minmax(b,0,this.canvas.width-this.displayWidth/this.zoom),a=pskl.utils.Math.minmax(a,0,this.canvas.height-this.displayHeight/this.zoom));this.offset.x=b;this.offset.y=a};a.FrameRenderer.prototype.setGridWidth=function(b){this.gridWidth_=b};a.FrameRenderer.prototype.getGridWidth=function(){return this.supportGridRendering?this.gridWidth_:0};a.FrameRenderer.prototype.updateMargins_=function(){this.margin.x=Math.max(0,this.displayWidth-this.zoom*this.canvas.width)/
2;this.margin.y=Math.max(0,this.displayHeight-this.zoom*this.canvas.height)/2};a.FrameRenderer.prototype.createDisplayCanvas_=function(){this.displayCanvas=pskl.CanvasUtils.createCanvas(this.displayWidth,this.displayHeight,this.classes);pskl.CanvasUtils.disableImageSmoothing(this.displayCanvas);this.container.append(this.displayCanvas)};a.FrameRenderer.prototype.onUserSettingsChange_=function(b,a,d){a==pskl.UserSettings.CANVAS_BACKGROUND?this.updateBackgroundClass_(d):a==pskl.UserSettings.GRID_WIDTH&&
this.setGridWidth(d)};a.FrameRenderer.prototype.updateBackgroundClass_=function(b){var a=this.container.data("current-background-class");a&&this.container.removeClass(a);this.container.addClass(b);this.container.data("current-background-class",b)};a.FrameRenderer.prototype.renderPixel_=function(b,a,d,e){b!=Constants.TRANSPARENT_COLOR&&(e.fillStyle=b,e.fillRect(a,d,1,1))};a.FrameRenderer.prototype.getCoordinates=function(b,a){var d=this.container.offset();b-=d.left;a-=d.top;b-=this.margin.x;a-=this.margin.y;
d=this.zoom;b+=this.offset.x*d;a+=this.offset.y*d;return{x:Math.floor(b/d),y:Math.floor(a/d)}};a.FrameRenderer.prototype.renderFrame_=function(b){this.canvas&&b.getWidth()==this.canvas.width&&b.getHeight()==this.canvas.height||(this.canvas=pskl.CanvasUtils.createCanvas(b.getWidth(),b.getHeight()));for(var a=this.canvas.getContext("2d"),d=0,e=b.getWidth();d<e;d++)for(var f=0,g=b.getHeight();f<g;f++){var h=b.getPixel(d,f);this.renderPixel_(h,d,f,a)}this.updateMargins_();a=this.displayCanvas.getContext("2d");
a.save();this.canvas.width*this.zoom<this.displayCanvas.width&&(a.fillStyle=Constants.ZOOMED_OUT_BACKGROUND_COLOR,a.fillRect(0,0,this.displayCanvas.width,this.displayCanvas.height));a.translate(this.margin.x-this.offset.x*this.zoom,this.margin.y-this.offset.y*this.zoom);a.clearRect(0,0,this.canvas.width*this.zoom,this.canvas.height*this.zoom);b=pskl.utils.UserAgent.isIE&&10===pskl.utils.UserAgent.version;d=this.getGridWidth();0<d||b?(b=pskl.utils.ImageResizer.resizeNearestNeighbour(this.canvas,this.zoom,
d),a.drawImage(b,0,0)):(a.scale(this.zoom,this.zoom),a.drawImage(this.canvas,0,0));a.restore()}})();(function(){var a=$.namespace("pskl.rendering.layer");a.LayersRenderer=function(b,a,d){pskl.rendering.CompositeRenderer.call(this);this.piskelController=d;this.belowRenderer=new pskl.rendering.frame.FrameRenderer(b,a,["layers-canvas","layers-below-canvas"]);this.aboveRenderer=new pskl.rendering.frame.FrameRenderer(b,a,["layers-canvas","layers-above-canvas"]);this.add(this.belowRenderer);this.add(this.aboveRenderer);this.serializedRendering=""};pskl.utils.inherit(pskl.rendering.layer.LayersRenderer,
pskl.rendering.CompositeRenderer);a.LayersRenderer.prototype.render=function(){var b=this.getOffset(),a=this.getDisplaySize(),d=this.piskelController.getLayers(),e=this.piskelController.getCurrentFrameIndex(),f=this.piskelController.getCurrentLayerIndex(),b=[this.getZoom(),this.getGridWidth(),b.x,b.y,a.width,a.height,e,f,d.length].join("-");this.serializedRendering!=b&&(this.serializedRendering=b,this.clear(),b=d.slice(0,f),0<b.length&&(b=this.getFrameForLayersAt_(e,b),this.belowRenderer.render(b)),
d=d.slice(f+1,d.length),0<d.length&&(e=this.getFrameForLayersAt_(e,d),this.aboveRenderer.render(e)))};a.LayersRenderer.prototype.setDisplaySize=function(b,a){var d=this.getDisplaySize();d.width===b&&d.height===a||this.superclass.setDisplaySize.call(this,b,a)};a.LayersRenderer.prototype.getFrameForLayersAt_=function(b,a){var d=a.map(function(a){return a.getFrameAt(b)});return pskl.utils.FrameUtils.merge(d)}})();(function(){var a=$.namespace("pskl.selection");a.BaseSelection=function(){this.reset()};a.BaseSelection.prototype.reset=function(){this.pixels=[];this.hasPastedContent=!1};a.BaseSelection.prototype.move=function(b,a){for(var d,e=[],f=0,g=this.pixels.length;f<g;f++)d=this.pixels[f],d.col+=b,d.row+=a,e.push(d);this.pixels=e};a.BaseSelection.prototype.fillSelectionFromFrame=function(b){this.pixels.forEach(function(a){a.color=b.getPixel(a.col,a.row)});this.hasPastedContent=!0}})();(function(){var a=$.namespace("pskl.selection");a.RectangularSelection=function(b,a,d,e){this.pixels=pskl.PixelUtils.getRectanglePixels(b,a,d,e)};pskl.utils.inherit(a.RectangularSelection,a.BaseSelection)})();(function(){var a=$.namespace("pskl.selection");a.SelectionManager=function(b){this.piskelController=b;this.currentSelection=null};a.SelectionManager.prototype.init=function(){$.subscribe(Events.SELECTION_CREATED,$.proxy(this.onSelectionCreated_,this));$.subscribe(Events.SELECTION_DISMISSED,$.proxy(this.onSelectionDismissed_,this));$.subscribe(Events.SELECTION_MOVE_REQUEST,$.proxy(this.onSelectionMoved_,this));pskl.app.shortcutService.addShortcut("ctrl+V",this.paste.bind(this));pskl.app.shortcutService.addShortcut("ctrl+X",
this.cut.bind(this));pskl.app.shortcutService.addShortcut("ctrl+C",this.copy.bind(this));pskl.app.shortcutService.addShortcut("del",this.erase.bind(this));$.subscribe(Events.TOOL_SELECTED,$.proxy(this.onToolSelected_,this))};a.SelectionManager.prototype.cleanSelection_=function(){this.currentSelection&&this.currentSelection.reset()};a.SelectionManager.prototype.onToolSelected_=function(b,a){a instanceof pskl.drawingtools.BaseSelect||this.cleanSelection_()};a.SelectionManager.prototype.onSelectionDismissed_=
function(b){this.cleanSelection_()};a.SelectionManager.prototype.erase=function(){for(var b=this.currentSelection.pixels,a=this.piskelController.getCurrentFrame(),d=0,e=b.length;d<e;d++)a.setPixel(b[d].col,b[d].row,Constants.TRANSPARENT_COLOR);$.publish(Events.PISKEL_SAVE_STATE,{type:"REPLAY",scope:this,replay:{type:"REPLAY_ERASE",pixels:JSON.parse(JSON.stringify(b.slice(0)))}})};a.SelectionManager.prototype.cut=function(){if(this.currentSelection)this.currentSelection.fillSelectionFromFrame(this.piskelController.getCurrentFrame()),
this.erase();else throw"Bad state for CUT callback in SelectionManager";};a.SelectionManager.prototype.paste=function(){if(this.currentSelection&&this.currentSelection.hasPastedContent){var b=this.currentSelection.pixels,a=this.piskelController.getCurrentFrame();$.publish(Events.PISKEL_SAVE_STATE,{type:"REPLAY",scope:this,replay:{type:"REPLAY_PASTE",pixels:JSON.parse(JSON.stringify(b.slice(0)))}});b.forEach(function(b){a.setPixel(b.col,b.row,b.color)})}};a.SelectionManager.prototype.replay=function(b,
a){a.pixels.forEach(function(d){b.setPixel(d.col,d.row,"REPLAY_PASTE"===a.type?d.color:Constants.TRANSPARENT_COLOR)})};a.SelectionManager.prototype.copy=function(){if(this.currentSelection&&this.piskelController.getCurrentFrame())this.currentSelection.fillSelectionFromFrame(this.piskelController.getCurrentFrame());else throw"Bad state for CUT callback in SelectionManager";};a.SelectionManager.prototype.onSelectionCreated_=function(b,a){if(a)this.currentSelection=a;else throw"No selection set in SelectionManager";
};a.SelectionManager.prototype.onSelectionMoved_=function(b,a,d){if(this.currentSelection)this.currentSelection.move(a,d);else throw"Bad state: No currentSelection set when trying to move it in SelectionManager";}})();(function(){var a=$.namespace("pskl.selection");a.ShapeSelection=function(b){this.pixels=b};pskl.utils.inherit(a.ShapeSelection,a.BaseSelection)})();(function(){var a=$.namespace("pskl.service");a.AppEngineStorageService=function(b){this.piskelController=b};a.AppEngineStorageService.prototype.init=function(){};a.AppEngineStorageService.prototype.store=function(b){var a=this.prepareFormData_(),d=new XMLHttpRequest;d.open("POST",Constants.APPENGINE.URL.SAVE,!0);d.onload=function(a){if(200==this.status)b.success(),b.after();else this.onerror(a)};d.onerror=function(a){b.error(this.status);b.after()};d.send(a)};a.AppEngineStorageService.prototype.prepareFormData_=
function(){var b=this.piskelController.getPiskel().getDescriptor(),a=new FormData;a.append("framesheet",this.piskelController.serialize());a.append("fps",this.piskelController.getFPS());a.append("name",b.name);a.append("description",b.description);b.isPublic&&a.append("public",!0);a.append("frames",this.piskelController.getFrameCount());a.append("first_frame_as_png",pskl.app.getFirstFrameAsPng());a.append("framesheet_as_png",pskl.app.getFramesheetAsPng());return a}})();(function(){var a=$.namespace("pskl.service");a.GithubStorageService=function(b){this.piskelController=b};a.GithubStorageService.prototype.init=function(){};a.GithubStorageService.prototype.store=function(b){b=new XMLHttpRequest;var a=new FormData;a.append("framesheet_content",this.piskelController.serialize());a.append("fps_speed",this.piskelController.getFPS());b.open("POST",Constants.STATIC.URL.SAVE,!0);b.onload=function(b){if(200==this.status)b=window.location.href.replace(window.location.search,
""),window.location.href=b+"?frameId="+this.responseText;else this.onerror(b)};b.onerror=function(b){$.publish(Events.SHOW_NOTIFICATION,[{content:"Saving failed ("+this.status+")"}])};b.send(a)}})();(function(){var a=$.namespace("pskl.service");a.HistoryService=function(b){this.piskelController=b;this.stateQueue=[];this.currentIndex=-1;this.saveState__b=this.saveState.bind(this);this.lastLoadState=-1};a.HistoryService.prototype.init=function(){$.subscribe(Events.PISKEL_SAVE_STATE,this.saveState__b);pskl.app.shortcutService.addShortcut("ctrl+Z",this.undo.bind(this));pskl.app.shortcutService.addShortcut("ctrl+Y",this.redo.bind(this))};a.HistoryService.prototype.saveState=function(b,a){this.stateQueue=
this.stateQueue.slice(0,this.currentIndex+1);this.currentIndex+=1;var d={action:a,frameIndex:this.piskelController.currentFrameIndex,layerIndex:this.piskelController.currentLayerIndex};if("FULL"===a.type||0===this.currentIndex%50)d.piskel=this.piskelController.serialize(!1);this.stateQueue.push(d)};a.HistoryService.prototype.undo=function(){this.loadState(this.currentIndex-1)};a.HistoryService.prototype.redo=function(){this.loadState(this.currentIndex+1)};a.HistoryService.prototype.loadState=function(b){if(this.isLoadStateAllowed_(b)){this.lastLoadState=
Date.now();var a=this.getPreviousSnapshotIndex_(b);if(0>a)throw"Could not find previous SNAPSHOT saved in history stateQueue";var d=this.stateQueue[a].piskel;"string"===typeof d&&(this.stateQueue[a].piskel=JSON.parse(d),d=this.stateQueue[a].piskel);this.loadPiskel(d,this.onPiskelLoadedCallback.bind(this,b,a))}};a.HistoryService.prototype.isLoadStateAllowed_=function(b){var a=50<Date.now()-this.lastLoadState;b=0<=b&&b<this.stateQueue.length;return a&&b};a.HistoryService.prototype.getPreviousSnapshotIndex_=
function(b){for(;this.stateQueue[b]&&!this.stateQueue[b].piskel;)b-=1;return b};a.HistoryService.prototype.onPiskelLoadedCallback=function(b,a,d){for(a+=1;a<=b;a++)d=this.stateQueue[a],this.setupState(d),this.replayState(d);this.setupState(this.stateQueue[b]);this.currentIndex=b;$.publish(Events.PISKEL_RESET)};a.HistoryService.prototype.setupState=function(b){this.piskelController.setCurrentFrameIndex(b.frameIndex);this.piskelController.setCurrentLayerIndex(b.layerIndex)};a.HistoryService.prototype.loadPiskel=
function(b,a){var d=this.piskelController.piskel.getDescriptor();pskl.utils.serialization.Deserializer.deserialize(b,function(b){b.setDescriptor(d);this.piskelController.setPiskel(b);a(b)}.bind(this))};a.HistoryService.prototype.replayState=function(b){var a=b.action;b=this.piskelController.getLayerAt(b.layerIndex).getFrameAt(b.frameIndex);a.scope.replay(b,a.replay)}})();(function(){var a=$.namespace("pskl.service");a.ImageUploadService=function(){};a.ImageUploadService.prototype.init=function(){};a.ImageUploadService.prototype.upload=function(b,a,d){var e=new XMLHttpRequest,f=new FormData;f.append("data",b);e.open("POST",Constants.IMAGE_SERVICE_UPLOAD_URL,!0);e.onload=function(b){200==this.status?a(Constants.IMAGE_SERVICE_GET_URL+this.responseText):d()};e.send(f)}})();(function(){var a=$.namespace("pskl.service");a.LocalStorageService=function(b){if(void 0===b)throw"Bad LocalStorageService initialization: <undefined piskelController>";this.piskelController=b};a.LocalStorageService.prototype.init=function(){};a.LocalStorageService.prototype.save=function(b,a,d){this.removeFromKeys_(b);this.addToKeys_(b,a,Date.now());window.localStorage.setItem("piskel."+b,d)};a.LocalStorageService.prototype.load=function(b){var a=this.getPiskel(b),d=this.getKey_(b);pskl.utils.serialization.Deserializer.deserialize(JSON.parse(a),
function(a){a.setDescriptor(new pskl.model.piskel.Descriptor(b,d.description,!0));pskl.app.piskelController.setPiskel(a)})};a.LocalStorageService.prototype.remove=function(a){this.removeFromKeys_(a);window.localStorage.removeItem("piskel."+a)};a.LocalStorageService.prototype.saveKeys_=function(a){window.localStorage.setItem("piskel.keys",JSON.stringify(a))};a.LocalStorageService.prototype.removeFromKeys_=function(a){var c=this.getKeys().filter(function(c){return c.name!==a});this.saveKeys_(c)};a.LocalStorageService.prototype.getKey_=
function(a){var c=this.getKeys().filter(function(c){return c.name===a});return 0<c.length?c[0]:null};a.LocalStorageService.prototype.addToKeys_=function(a,c,d){var e=this.getKeys();e.push({name:a,description:c,date:d});this.saveKeys_(e)};a.LocalStorageService.prototype.getPiskel=function(a){return window.localStorage.getItem("piskel."+a)};a.LocalStorageService.prototype.getKeys=function(a){a=window.localStorage.getItem("piskel.keys");return JSON.parse(a)||[]}})();(function(){var a=$.namespace("pskl.service");a.SavedStatusService=function(a){this.piskelController=a};a.SavedStatusService.prototype.init=function(){$.subscribe(Events.TOOL_RELEASED,this.onToolReleased.bind(this));$.subscribe(Events.PISKEL_RESET,this.onPiskelReset.bind(this));$.subscribe(Events.PISKEL_SAVED,this.onPiskelSaved.bind(this));window.addEventListener("beforeunload",this.onBeforeUnload.bind(this))};a.SavedStatusService.prototype.onPiskelReset=function(){var a=this.piskelController.getPiskel();
a.firstResetDone_?this.updateDirtyStatus(!0):a.firstResetDone_=!0};a.SavedStatusService.prototype.onToolReleased=function(){this.updateDirtyStatus(!0)};a.SavedStatusService.prototype.onPiskelSaved=function(){this.updateDirtyStatus(!1)};a.SavedStatusService.prototype.updateDirtyStatus=function(a){var c=this.piskelController.getPiskel();c.isDirty_!==a&&(c.isDirty_=a,this.updatePiskelName())};a.SavedStatusService.prototype.updatePiskelName=function(){var a=this.piskelController.getPiskel(),c=a.getDescriptor().name;
a.isDirty_?$(".piskel-name").html(c+" *"):$(".piskel-name").html(c)};a.SavedStatusService.prototype.onBeforeUnload=function(a){if(this.piskelController.getPiskel().isDirty_)return(a||window.event).returnValue="Your Piskel seems to have unsaved changes"}})();(function(){var a=$.namespace("pskl.service.keyboard");a.CheatsheetService=function(){this.isDisplayed_=!1};a.CheatsheetService.prototype.init=function(){this.cheatsheetEl_=document.getElementById("cheatsheet-wrapper");if(!this.cheatsheetEl_)throw"cheatsheetEl_ DOM element could not be retrieved";this.initMarkup_();pskl.app.shortcutService.addShortcut("shift+?",this.toggleCheatsheet_.bind(this));pskl.app.shortcutService.addShortcut("?",this.toggleCheatsheet_.bind(this));$(".cheatsheet-link").click(this.toggleCheatsheet_.bind(this));
$.subscribe(Events.TOGGLE_HELP,this.toggleCheatsheet_.bind(this));$.subscribe(Events.ESCAPE,this.onEscape_.bind(this))};a.CheatsheetService.prototype.toggleCheatsheet_=function(){this.isDisplayed_?this.hideCheatsheet_():this.showCheatsheet_()};a.CheatsheetService.prototype.onEscape_=function(){this.isDisplayed_&&this.hideCheatsheet_()};a.CheatsheetService.prototype.showCheatsheet_=function(){pskl.app.shortcutService.addShortcut("ESC",this.hideCheatsheet_.bind(this));this.cheatsheetEl_.style.display=
"block";this.isDisplayed_=!0};a.CheatsheetService.prototype.hideCheatsheet_=function(){pskl.app.shortcutService.removeShortcut("ESC");this.cheatsheetEl_.style.display="none";this.isDisplayed_=!1};a.CheatsheetService.prototype.initMarkup_=function(){this.initMarkupForTools_();this.initMarkupForMisc_();this.initMarkupForSelection_()};a.CheatsheetService.prototype.toDescriptor_=function(a,c,d){return{shortcut:a,description:c,icon:d}};a.CheatsheetService.prototype.getDomFromDescriptor_=function(a){var c=
pskl.utils.Template.get("cheatsheet-shortcut-template");a=pskl.utils.Template.replace(c,{shortcutIcon:a.icon,shortcutDescription:a.description,shortcutKey:a.shortcut});return pskl.utils.Template.createFromHTML(a)};a.CheatsheetService.prototype.initMarkupAbstract_=function(a,c){for(var d=$(c,this.cheatsheetEl_).get(0),e=0;e<a.length;e++){var f=this.getDomFromDescriptor_(a[e]);d.appendChild(f)}};a.CheatsheetService.prototype.initMarkupForTools_=function(){var a=pskl.app.toolController.tools.map(function(a){return this.toDescriptor_(a.shortcut,
a.instance.helpText,"tool-icon "+a.instance.toolId)}.bind(this));this.initMarkupAbstract_(a,".cheatsheet-tool-shortcuts")};a.CheatsheetService.prototype.initMarkupForMisc_=function(){var a=[this.toDescriptor_("X","Swap primary/secondary colors"),this.toDescriptor_("D","Reset default colors"),this.toDescriptor_("ctrl + Z","Undo"),this.toDescriptor_("ctrl + Y","Redo"),this.toDescriptor_("&#65514;","Select previous frame"),this.toDescriptor_("&#65516;","Select next frame"),this.toDescriptor_("N","Create new frame"),
this.toDescriptor_("shift + N","Duplicate selected frame"),this.toDescriptor_("shift + ?","Open/Close this popup"),this.toDescriptor_("alt + P","Open the Palette Manager")];this.initMarkupAbstract_(a,".cheatsheet-misc-shortcuts")};a.CheatsheetService.prototype.initMarkupForSelection_=function(){var a=[this.toDescriptor_("ctrl + X","Cut selection"),this.toDescriptor_("ctrl + C","Copy selection"),this.toDescriptor_("ctrl + V","Paste selection"),this.toDescriptor_("del","Delete selection")];this.initMarkupAbstract_(a,
".cheatsheet-selection-shortcuts")}})();(function(){var a={191:"?",27:"esc",38:"up",40:"down",46:"del"};$.namespace("pskl.service.keyboard").KeycodeTranslator={toChar:function(b){return 48<=b&&57>=b?b-48+"":65<=b&&90>=b?(b-65+10).toString(36):a[b]}}})();(function(){var a=$.namespace("pskl.service.keyboard");a.ShortcutService=function(){this.shortcuts_={}};a.ShortcutService.prototype.init=function(){$(document.body).keydown($.proxy(this.onKeyUp_,this))};a.ShortcutService.prototype.addShortcut=function(a,c){var d=this.parseKey_(a.toLowerCase()),e=d.key,d=d.meta;this.shortcuts_[e]=this.shortcuts_[e]||{};this.shortcuts_[e][d]?console.error("[ShortcutService] >>> Shortcut ["+(("normal"!==d?d+" + ":"")+e)+"] already registered"):this.shortcuts_[e][d]=
c};a.ShortcutService.prototype.removeShortcut=function(a){var c=this.parseKey_(a.toLowerCase());a=c.key;c=c.meta;this.shortcuts_[a]=this.shortcuts_[a]||{};this.shortcuts_[a][c]=null};a.ShortcutService.prototype.parseKey_=function(a){var c="normal";0===a.indexOf("ctrl+")?(c="ctrl",a=a.replace("ctrl+","")):0===a.indexOf("shift+")?(c="shift",a=a.replace("shift+","")):0===a.indexOf("alt+")&&(c="alt",a=a.replace("alt+",""));return{meta:c,key:a}};a.ShortcutService.prototype.onKeyUp_=function(a){if(!this.isInInput_(a)){var c=
a.which;a.target.nodeName.toUpperCase();var c=pskl.service.keyboard.KeycodeTranslator.toChar(c),d=this.shortcuts_[c];d&&(d=this.isCtrlKeyPressed_(a)?d.ctrl:this.isShiftKeyPressed_(a)?d.shift:this.isAltKeyPressed_(a)?d.alt:d.normal)&&(d(c),a.preventDefault())}};a.ShortcutService.prototype.isInInput_=function(a){a=a.target.nodeName.toUpperCase();return"INPUT"===a||"TEXTAREA"===a};a.ShortcutService.prototype.isCtrlKeyPressed_=function(a){return this.isMac_()?a.metaKey:a.ctrlKey};a.ShortcutService.prototype.isShiftKeyPressed_=
function(a){return a.shiftKey};a.ShortcutService.prototype.isAltKeyPressed_=function(a){return a.altKey};a.ShortcutService.prototype.isMac_=function(){return-1!=navigator.appVersion.indexOf("Mac")}})();(function(){$.namespace("pskl").CanvasUtils={createCanvas:function(a,b,c){var d=document.createElement("canvas");d.setAttribute("width",a);d.setAttribute("height",b);"string"==typeof c&&(c=[c]);if(Array.isArray(c))for(a=0;a<c.length;a++)d.classList.add(c[a]);return d},createFromImageData:function(a){var b=pskl.CanvasUtils.createCanvas(a.width,a.height);b.getContext("2d").putImageData(a,0,0);return b},disableImageSmoothing:function(a){a=a.getContext("2d");a.imageSmoothingEnabled=!1;a.mozImageSmoothingEnabled=
!1;a.oImageSmoothingEnabled=!1;a.webkitImageSmoothingEnabled=!1;a.msImageSmoothingEnabled=!1},clear:function(a){a&&a.getContext("2d").clearRect(0,0,a.width,a.height)},getImageDataFromCanvas:function(a){return a.getContext("2d").getImageData(0,0,a.width,a.height).data},getBase64FromCanvas:function(a,b){var c=a.toDataURL("image/"+(b||"png"));return c.substr(c.indexOf(",")+1)}}})();(function(){$.namespace("pskl.utils").Dom={isParent:function(a,b,c){if(a&&b)for(c&&(a=a.parentNode);a;){if(a===b)return!0;a=a.parentNode}return!1},getParentWithData:function(a,b){for(;a;){if(a.dataset&&"undefined"!==typeof a.dataset[b])return a;a=a.parentNode}return null}}})();(function(){$.namespace("pskl.utils").FileUtils={readFile:function(a,b){var c=new FileReader;c.onload=function(a){b(a.target.result)};c.readAsDataURL(a)},downloadAsFile:function(a,b){var c=window.saveAs||navigator.msSaveBlob&&navigator.msSaveBlob.bind(navigator);c?c(b,a):(c=document.createElement("a"),b=window.URL.createObjectURL(b),c.setAttribute("href",b),c.setAttribute("download",a),document.body.appendChild(c),c.click(),document.body.removeChild(c))}}})();(function(){var a={};$.namespace("pskl.utils").FrameUtils={merge:function(a){var c=null;if(a.length){c=a[0].clone();c.getWidth();c.getHeight();for(var d=1;d<a.length;d++)pskl.utils.FrameUtils.mergeFrames_(c,a[d])}return c},mergeFrames_:function(a,c){c.forEachPixel(function(c,e,f){c!=Constants.TRANSPARENT_COLOR&&a.setPixel(e,f,c)})},mergePixels:function(a,c,d){a=pskl.utils.FrameUtils.toRgba(a);c=pskl.utils.FrameUtils.toRgba(c);"number"==typeof d&&(a=JSON.parse(JSON.stringify(a)),a.a*=d);d=a.a+c.a*
(1-a.a);return"rgba("+((a.r*a.a+c.r*c.a*(1-a.a))/d|0)+","+((a.g*a.a+c.g*c.a*(1-a.a))/d|0)+","+((a.b*a.a+c.b*c.a*(1-a.a))/d|0)+","+d+")"},toRgba:function(b){if(a[b])return a[b];var c;"TRANSPARENT"===b?c={r:0,g:0,b:0,a:0}:-1!=b.indexOf("rgba(")?(c=/rgba\((\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(1|0\.\d+)\s*\)/.exec(b),c={r:parseInt(c[1],10),g:parseInt(c[2],10),b:parseInt(c[3],10),a:parseFloat(c[4])}):-1!=b.indexOf("rgb(")?(c=/rgb\((\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/.exec(b),c={r:parseInt(c[1],10),g:parseInt(c[2],
10),b:parseInt(c[3],10),a:1}):(c=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(b),c={r:parseInt(c[1],16),g:parseInt(c[2],16),b:parseInt(c[3],16),a:1});return a[b]=c},createFromImage:function(a){var c=a.width,d=a.height,e=pskl.CanvasUtils.createCanvas(c,d).getContext("2d");e.drawImage(a,0,0,c,d,0,0,c,d);a=e.getImageData(0,0,c,d).data;return pskl.utils.FrameUtils.createFromImageData(a,c,d)},createFromImageData:function(a,c,d){for(var e=[],f=0;f<c;f++){e[f]=[];for(var g=0;g<d;g++){var h=4*(g*c+f),
k=a[h],l=a[h+1],m=a[h+2];e[f][g]=125>a[h+3]?Constants.TRANSPARENT_COLOR:pskl.utils.FrameUtils.rgbToHex(k,l,m)}}return pskl.model.Frame.fromPixelGrid(e)},rgbToHex:function(a,c,d){return"#"+this.componentToHex(a)+this.componentToHex(c)+this.componentToHex(d)},componentToHex:function(a){a=a.toString(16);return 1==a.length?"0"+a:a}}})();(function(){$.namespace("pskl.utils").ImageResizer={resize:function(a,b,c,d){var e=pskl.CanvasUtils.createCanvas(b,c),f=e.getContext("2d");f.save();d||pskl.CanvasUtils.disableImageSmoothing(e);f.translate(e.width/2,e.height/2);f.scale(b/a.width,c/a.height);f.drawImage(a,-a.width/2,-a.height/2);f.restore();return e},resizeNearestNeighbour:function(a,b,c,d){c=c||0;for(var e=pskl.CanvasUtils.createCanvas(b*a.width,b*a.height),f=e.getContext("2d"),g=pskl.CanvasUtils.getImageDataFromCanvas(a),h={},k=0,
l=0,m,n,q=0;q<a.width;q++){m=Math.floor((q+1)*b)-k;for(var p=0;p<a.height;p++){h[p+""]||(h[p+""]=Math.floor((p+1)*b)-l);n=h[p+""];var r=4*(p*a.width+q);f.fillStyle="rgba("+g[r]+","+g[r+1]+","+g[r+2]+","+g[r+3]/255+")";f.fillRect(k,l,m-c,n-c);c&&d&&(f.fillStyle=d,f.fillRect(k+m-c,l,c,n),f.fillRect(k,l+n-c,m,c));l+=n}l=0;k+=m}return e}}})();(function(){$.namespace("pskl.utils").LayerUtils={createFromImage:function(a,b){var c=a.width,d=a.height,e=c/b,f=pskl.CanvasUtils.createCanvas(c,d).getContext("2d");f.drawImage(a,0,0,c,d,0,0,c,d);for(var c=[],g=0;g<b;g++){var h=f.getImageData(e*g,0,e,d).data,h=pskl.utils.FrameUtils.createFromImageData(h,e,d);c.push(h)}return c}}})();(function(){$.namespace("pskl.utils").Math={minmax:function(a,b,c){return Math.max(Math.min(a,c),b)}}})();(function(){$.namespace("pskl").PixelUtils={getRectanglePixels:function(a,b,c,d){a=this.getOrderedRectangleCoordinates(a,b,c,d);b=[];for(c=a.x0;c<=a.x1;c++)for(d=a.y0;d<=a.y1;d++)b.push({col:c,row:d});return b},getBoundRectanglePixels:function(a,b,c,d){a=this.getOrderedRectangleCoordinates(a,b,c,d);b=[];for(c=a.x0;c<=a.x1;c++)b.push({col:c,row:a.y0}),b.push({col:c,row:a.y1});for(c=a.y0;c<=a.y1;c++)b.push({col:a.x0,row:c}),b.push({col:a.x1,row:c});return b},getOrderedRectangleCoordinates:function(a,
b,c,d){return{x0:Math.min(a,c),y0:Math.min(b,d),x1:Math.max(a,c),y1:Math.max(b,d)}},getSimilarConnectedPixelsFromFrame:function(a,b,c){a=a.clone();return this.paintSimilarConnectedPixelsFromFrame(a,b,c,"sdfsdfsdf")},paintSimilarConnectedPixelsFromFrame:function(a,b,c,d){var e=[],f=[],g=[-1,0,1,0],h=[0,1,0,-1],k;try{k=a.getPixel(b,c)}catch(l){}if(k!=d){f.push({col:b,row:c});b=0;for(c=a.getWidth()*a.getHeight();0<f.length;){b++;var m=f.pop();a.setPixel(m.col,m.row,d);e.push({col:m.col,row:m.row});for(var n=
0;4>n;n++){var q=m.col+h[n],p=m.row+g[n];try{a.containsPixel(q,p)&&a.getPixel(q,p)==k&&f.push({col:q,row:p})}catch(r){}}if(b>10*c){console.log("loop breaker called");break}}return e}},calculateZoomForContainer:function(a,b,c){return this.calculateZoom(a.height(),a.width(),b,c)},calculateZoom:function(a,b,c,d){return Math.min(Math.floor(a/c),Math.floor(b/d))}}})();(function(){$.namespace("pskl.utils").Template={get:function(a){var b=document.getElementById(a);if(b)return b.innerHTML;console.error("Could not find template for id :",a)},createFromHTML:function(a){var b=document.createElement("div");b.innerHTML=a;return b.children[0]},replace:function(a,b){for(var c in b)if(b.hasOwnProperty(c)){var d=b[c];-1!==c.indexOf(":")&&(!0===d?d=c.split(":")[1]:!1===d&&(d=""));a=a.replace(RegExp("\\{\\{"+c+"\\}\\}","g"),d)}return a}}})();(function(){var a=$.namespace("pskl.utils"),b=navigator.userAgent;a.UserAgent={isIE:/MSIE/i.test(b),isChrome:/Chrome/i.test(b),isFirefox:/Firefox/i.test(b)};a.UserAgent.version=function(){if(pskl.utils.UserAgent.isIE)return parseInt(/MSIE\s?(\d+)/i.exec(b)[1],10);if(pskl.utils.UserAgent.isChrome)return parseInt(/Chrome\/(\d+)/i.exec(b)[1],10);if(pskl.utils.UserAgent.isFirefox)return parseInt(/Firefox\/(\d+)/i.exec(b)[1],10)}()})();(function(){$.namespace("pskl").UserSettings={GRID_WIDTH:"GRID_WIDTH",CANVAS_BACKGROUND:"CANVAS_BACKGROUND",SELECTED_PALETTE:"SELECTED_PALETTE",KEY_TO_DEFAULT_VALUE_MAP_:{GRID_WIDTH:0,CANVAS_BACKGROUND:"lowcont-dark-canvas-background",SELECTED_PALETTE:Constants.NO_PALETTE_ID},cache_:{},get:function(a){this.checkKeyValidity_(a);a in this.cache_||(this.cache_[a]=this.readFromLocalStorage_(a)||this.readFromDefaults_(a));return this.cache_[a]},set:function(a,b){this.checkKeyValidity_(a);this.cache_[a]=
b;this.writeToLocalStorage_(a,b);$.publish(Events.USER_SETTINGS_CHANGED,[a,b])},readFromLocalStorage_:function(a){a=window.localStorage[a];"undefined"!=typeof a&&(a=JSON.parse(a));return a},writeToLocalStorage_:function(a,b){window.localStorage[a]=JSON.stringify(b)},readFromDefaults_:function(a){return this.KEY_TO_DEFAULT_VALUE_MAP_[a]},checkKeyValidity_:function(a){a in this.KEY_TO_DEFAULT_VALUE_MAP_||console.log("UserSettings key <"+a+"> not find in supported keys.")}}})();jQuery.namespace=function(){var a=arguments,b=null,c,d,e;for(c=0;c<a.length;c+=1)for(e=a[c].split("."),b=window,d=0;d<e.length;d+=1)b[e[d]]=b[e[d]]||{},b=b[e[d]];return b};"function"!==typeof Function.prototype.bind&&(Function.prototype.bind=function(a){var b=this;return function(){return b.apply(a,arguments)}});
(function(){var a=$.namespace("pskl.utils");a.rgbToHex=function(a,c,d){if(255<a||255<c||255<d)throw"Invalid color component";return(a<<16|c<<8|d).toString(16)};a.inherit=function(a,c){a.prototype=Object.create(c.prototype);a.prototype.constructor=a;a.prototype.superclass=c.prototype};a.wrap=function(a,c){for(var d in c)"function"===typeof c[d]&&(a[d]=c[d].bind(c))}})();(function(){var a=$.namespace("pskl.utils.serialization");a.Deserializer=function(a,c){this.layersToLoad_=0;this.data_=a;this.callback_=c;this.piskel_=null};a.Deserializer.deserialize=function(b,c){(b.modelVersion==Constants.MODEL_VERSION?new a.Deserializer(b,c):1==b.modelVersion?new a.backward.Deserializer_v1(b,c):new a.backward.Deserializer_v0(b,c)).deserialize()};a.Deserializer.prototype.deserialize=function(a){var c=this.data_.piskel;a=new pskl.model.piskel.Descriptor(a||"Deserialized piskel",
"");this.piskel_=new pskl.model.Piskel(c.width,c.height,a);this.layersToLoad_=c.layers.length;c.layers.forEach(function(a){this.deserializeLayer(a)}.bind(this))};a.Deserializer.prototype.deserializeLayer=function(a){var c="string"===typeof a?JSON.parse(a):a,d=new pskl.model.Layer(c.name);if(c.base64PNG){a=c.base64PNG;var e=new Image;e.onload=function(){var a=pskl.utils.LayerUtils.createFromImage(e,c.frameCount);this.addFramesToLayer(a,d)}.bind(this);e.src=a}else a=c.grids.map(function(a){return pskl.model.Frame.fromPixelGrid(a)}),
this.addFramesToLayer(a,d);return d};a.Deserializer.prototype.addFramesToLayer=function(a,c){a.forEach(c.addFrame.bind(c));this.piskel_.addLayer(c);this.onLayerLoaded_()};a.Deserializer.prototype.onLayerLoaded_=function(){this.layersToLoad_-=1;0===this.layersToLoad_&&this.callback_(this.piskel_)}})();(function(){$.namespace("pskl.utils").Serializer={serializePiskel:function(a,b){var c=a.getLayers().map(function(a){return pskl.utils.Serializer.serializeLayer(a,b)});return JSON.stringify({modelVersion:Constants.MODEL_VERSION,piskel:{height:a.getHeight(),width:a.getWidth(),layers:c}})},serializeLayer:function(a,b){!1!==b&&(b=!0);var c=a.getFrames(),d=new pskl.rendering.FramesheetRenderer(c),e={name:a.getName(),frameCount:c.length};if(b)return e.base64PNG=d.renderAsCanvas().toDataURL(),JSON.stringify(e);
e.grids=c.map(function(a){return a.pixels});return e}}})();(function(){var a=$.namespace("pskl.utils.serialization.backward");a.Deserializer_v0=function(a,c){this.data_=a;this.callback_=c};a.Deserializer_v0.prototype.deserialize=function(){var a=this.data_.map(function(a){return pskl.model.Frame.fromPixelGrid(a)}),c=new pskl.model.piskel.Descriptor("Deserialized piskel",""),a=pskl.model.Layer.fromFrames("Layer 1",a);this.callback_(pskl.model.Piskel.fromLayers([a],c))}})();(function(){var a=$.namespace("pskl.utils.serialization.backward");a.Deserializer_v1=function(a,c){this.callback_=c;this.data_=a};a.Deserializer_v1.prototype.deserialize=function(){var a=this.data_.piskel,c=new pskl.model.piskel.Descriptor("Deserialized piskel",""),d=new pskl.model.Piskel(a.width,a.height,c);a.layers.forEach(function(a){a=this.deserializeLayer(a);d.addLayer(a)}.bind(this));this.callback_(d)};a.Deserializer_v1.prototype.deserializeLayer=function(a){a=JSON.parse(a);var c=new pskl.model.Layer(a.name);
a.frames.forEach(function(a){a=this.deserializeFrame(a);c.addFrame(a)}.bind(this));return c};a.Deserializer_v1.prototype.deserializeFrame=function(a){a=JSON.parse(a);return pskl.model.Frame.fromPixelGrid(a)}})();(function(){window.onPiskelReady=function(){var a=document.getElementById("loading-mask");a.style.opacity=0;window.setTimeout(function(){a.parentNode.removeChild(a)},600);pskl.app.init();delete window.pskl_exports;delete window.loadDebugScripts;delete window.done};var a=function(a,b){a=window.pskl&&window.pskl.appEngineToken_?"../"+a:a;var c=window.document.createElement("script");c.setAttribute("src",a);c.setAttribute("onload",b);window.document.body.appendChild(c)},b=function(a){a=window.pskl&&
window.pskl.appEngineToken_?"../"+a:a;var b=document.createElement("link");b.setAttribute("href",a);b.setAttribute("rel","stylesheet");b.setAttribute("type","text/css");document.head.appendChild(b)};if(-1!=window.location.href.indexOf("debug")){window.pskl_exports={};var c=0;window.loadNextScript=function(){if(c==window.pskl_exports.scripts.length)window.onPiskelReady();else a(window.pskl_exports.scripts[c],"loadNextScript()"),c++};a("piskel-script-list.js","loadNextScript()");window.loadStyles=function(){for(var a=
window.pskl_exports.styles,c=0;c<a.length;c++)b(a[c])};a("piskel-style-list.js","loadStyles()")}else{var d;d=-1!=window.location.href.indexOf("pack")?"build/piskel-packaged.js":"build/piskel-packaged-min.js";b("build/piskel-style-packaged.css");var e=window.setInterval(function(){0===document.querySelectorAll("[data-iframe-loader]").length?(window.clearInterval(e),a(d,"onPiskelReady()")):console.log("waiting for templates to load ....")},100)}})();("undefined"!=typeof exports?exports:pskl_exports).scripts="js/lib/jquery-1.8.0.js js/lib/jquery-ui-1.10.3.custom.js js/lib/pubsub.js js/lib/bootstrap/bootstrap.js js/lib/gif/gif.worker.js js/lib/gif/gif.js js/lib/gif/libgif.js js/lib/jszip/jszip.min.js js/lib/canvastoblob/canvasToBlob.js js/lib/spectrum/spectrum.js js/Constants.js js/Events.js js/utils/core.js js/utils/UserAgent.js js/utils/CanvasUtils.js js/utils/Dom.js js/utils/Math.js js/utils/FileUtils.js js/utils/FrameUtils.js js/utils/LayerUtils.js js/utils/ImageResizer.js js/utils/PixelUtils.js js/utils/Template.js js/utils/UserSettings.js js/utils/serialization/Serializer.js js/utils/serialization/Deserializer.js js/utils/serialization/backward/Deserializer_v0.js js/utils/serialization/backward/Deserializer_v1.js js/rendering/DrawingLoop.js js/model/Frame.js js/model/Layer.js js/model/piskel/Descriptor.js js/model/Piskel.js js/selection/SelectionManager.js js/selection/BaseSelection.js js/selection/RectangularSelection.js js/selection/ShapeSelection.js js/rendering/AbstractRenderer.js js/rendering/CompositeRenderer.js js/rendering/layer/LayersRenderer.js js/rendering/frame/FrameRenderer.js js/rendering/frame/CachedFrameRenderer.js js/rendering/CanvasRenderer.js js/rendering/FramesheetRenderer.js js/rendering/PiskelRenderer.js js/controller/piskel/PiskelController.js js/controller/piskel/PublicPiskelController.js js/controller/CursorCoordinatesController.js js/controller/DrawingController.js js/controller/PreviewFilmController.js js/controller/LayersListController.js js/controller/AnimatedPreviewController.js js/controller/MinimapController.js js/controller/ToolController.js js/controller/PaletteController.js js/controller/PalettesListController.js js/controller/NotificationController.js js/controller/settings/ApplicationSettingsController.js js/controller/settings/ResizeController.js js/controller/settings/GifExportController.js js/controller/settings/PngExportController.js js/controller/settings/LocalStorageController.js js/controller/settings/SaveController.js js/controller/settings/ImportController.js js/controller/settings/SettingsController.js js/controller/dialogs/PaletteManagerController.js js/controller/dialogs/DialogsController.js js/service/LocalStorageService.js js/service/GithubStorageService.js js/service/AppEngineStorageService.js js/service/HistoryService.js js/service/SavedStatusService.js js/service/keyboard/ShortcutService.js js/service/keyboard/KeycodeTranslator.js js/service/keyboard/CheatsheetService.js js/service/ImageUploadService.js js/drawingtools/BaseTool.js js/drawingtools/ShapeTool.js js/drawingtools/SimplePen.js js/drawingtools/VerticalMirrorPen.js js/drawingtools/Eraser.js js/drawingtools/Stroke.js js/drawingtools/PaintBucket.js js/drawingtools/Rectangle.js js/drawingtools/Circle.js js/drawingtools/Move.js js/drawingtools/selectiontools/BaseSelect.js js/drawingtools/selectiontools/RectangleSelect.js js/drawingtools/selectiontools/ShapeSelect.js js/drawingtools/ColorPicker.js js/app.js".split(" ");