Merge branch 'master' into gh-pages

This commit is contained in:
juliandescottes 2012-09-14 01:13:22 +02:00
commit ef3e4a5f7a
22 changed files with 592 additions and 129 deletions

View File

@ -49,6 +49,10 @@
background-image: url(../img/tools/icons/hand.png); background-image: url(../img/tools/icons/hand.png);
} }
.tool-icon.tool-select {
background-image: url(../img/tools/icons/select.png);
}
/*.tool-icon.tool-palette { /*.tool-icon.tool-palette {
background-image: url(../img/tools/icons/color-palette.png); background-image: url(../img/tools/icons/color-palette.png);
}*/ }*/
@ -77,6 +81,10 @@
cursor: url(../img/tools/cursors/hand.png) 14 12, pointer; cursor: url(../img/tools/cursors/hand.png) 14 12, pointer;
} }
.tool-select .drawing-canvas-container:hover {
cursor: url(../img/tools/cursors/select.png) 14 12, pointer;
}
.tool-grid, .tool-grid,
.tool-grid label, .tool-grid label,
.tool-grid input { .tool-grid input {

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

BIN
img/tools/cursors/wand.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 570 B

BIN
img/tools/icons/select.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

BIN
img/tools/icons/wand.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 570 B

View File

@ -32,6 +32,7 @@
<li class="tool-icon tool-stroke" data-tool-id="tool-stroke" title="Stroke tool"></li> <li class="tool-icon tool-stroke" data-tool-id="tool-stroke" title="Stroke tool"></li>
<li class="tool-icon tool-rectangle" data-tool-id="tool-rectangle" title="Rectangle tool"></li> <li class="tool-icon tool-rectangle" data-tool-id="tool-rectangle" title="Rectangle tool"></li>
<li class="tool-icon tool-move" data-tool-id="tool-move" title="Move tool"></li> <li class="tool-icon tool-move" data-tool-id="tool-move" title="Move tool"></li>
<li class="tool-icon tool-select" data-tool-id="tool-select" title="Move tool"></li>
</ul> </ul>
<ul class="tools-group"> <ul class="tools-group">
@ -92,7 +93,8 @@
<script src="js/Events.js"></script> <script src="js/Events.js"></script>
<!-- Libraries --> <!-- Libraries -->
<script src="js/utils.js"></script> <script src="js/utils/core.js"></script>
<script src="js/utils/pixelUtils.js"></script>
<script src="js/lib/jsColor_1_4_0/jscolor.js"></script> <script src="js/lib/jsColor_1_4_0/jscolor.js"></script>
<!-- Application libraries--> <!-- Application libraries-->
@ -105,6 +107,10 @@
<script src="js/controller/AnimatedPreviewController.js"></script> <script src="js/controller/AnimatedPreviewController.js"></script>
<script src="js/LocalStorageService.js"></script> <script src="js/LocalStorageService.js"></script>
<script src="js/HistoryManager.js"></script> <script src="js/HistoryManager.js"></script>
<script src="js/KeyManager.js"></script>
<script src="js/selection/SelectionManager.js"></script>
<script src="js/selection/BaseSelection.js"></script>
<script src="js/selection/RectangularSelection.js"></script>
<script src="js/Palette.js"></script> <script src="js/Palette.js"></script>
<script src="js/Notification.js"></script> <script src="js/Notification.js"></script>
<script src="js/drawingtools/BaseTool.js"></script> <script src="js/drawingtools/BaseTool.js"></script>
@ -114,6 +120,7 @@
<script src="js/drawingtools/PaintBucket.js"></script> <script src="js/drawingtools/PaintBucket.js"></script>
<script src="js/drawingtools/Rectangle.js"></script> <script src="js/drawingtools/Rectangle.js"></script>
<script src="js/drawingtools/Move.js"></script> <script src="js/drawingtools/Move.js"></script>
<script src="js/drawingtools/RectangularSelect.js"></script>
<script src="js/ToolSelector.js"></script> <script src="js/ToolSelector.js"></script>
<!-- Application controller and initialization --> <!-- Application controller and initialization -->

View File

@ -34,7 +34,19 @@ Events = {
* Number of frames, content of frames, color used for the palette may have changed. * Number of frames, content of frames, color used for the palette may have changed.
*/ */
FRAMESHEET_RESET: "FRAMESHEET_RESET", FRAMESHEET_RESET: "FRAMESHEET_RESET",
CURRENT_FRAME_SET: "CURRENT_FRAME_SET",
SELECTION_CREATED: "SELECTION_CREATED",
SELECTION_MOVE_REQUEST: "SELECTION_MOVE_REQUEST",
SELECTION_DISMISSED: "SELECTION_DISMISSED",
SHOW_NOTIFICATION: "SHOW_NOTIFICATION", SHOW_NOTIFICATION: "SHOW_NOTIFICATION",
HIDE_NOTIFICATION: "HIDE_NOTIFICATION" HIDE_NOTIFICATION: "HIDE_NOTIFICATION",
UNDO: "UNDO",
REDO: "REDO",
CUT: "CUT",
COPY: "COPY",
PASTE: "PASTE"
}; };

View File

@ -5,36 +5,24 @@
}; };
ns.HistoryManager.prototype.init = function () { ns.HistoryManager.prototype.init = function () {
document.body.addEventListener('keyup', this.onKeyup.bind(this));
$.subscribe(Events.TOOL_RELEASED, this.saveState.bind(this)); $.subscribe(Events.TOOL_RELEASED, this.saveState.bind(this));
$.subscribe(Events.UNDO, this.undo.bind(this));
$.subscribe(Events.REDO, this.redo.bind(this));
}; };
ns.HistoryManager.prototype.saveState = function () { ns.HistoryManager.prototype.saveState = function () {
this.framesheet.getCurrentFrame().saveState(); this.framesheet.getCurrentFrame().saveState();
}; };
ns.HistoryManager.prototype.onKeyup = function (evt) {
if (evt.ctrlKey && evt.keyCode == 90) { // CTRL + Z
this.undo();
}
if (evt.ctrlKey && evt.keyCode == 89) { // CTRL+ Y
this.redo();
}
};
ns.HistoryManager.prototype.undo = function () { ns.HistoryManager.prototype.undo = function () {
this.framesheet.getCurrentFrame().loadPreviousState(); this.framesheet.getCurrentFrame().loadPreviousState();
this.redraw(); $.publish(Events.FRAMESHEET_RESET);
}; };
ns.HistoryManager.prototype.redo = function () { ns.HistoryManager.prototype.redo = function () {
this.framesheet.getCurrentFrame().loadNextState(); this.framesheet.getCurrentFrame().loadNextState();
this.redraw(); $.publish(Events.FRAMESHEET_RESET);
}; };
ns.HistoryManager.prototype.redraw = function () {
this.framesheet.drawingController.renderFrame();
this.framesheet.previewsController.createPreviews();
};
})(); })();

50
js/KeyManager.js Normal file
View File

@ -0,0 +1,50 @@
(function () {
var ns = $.namespace("pskl");
ns.KeyManager = function () {
$(document.body).keydown($.proxy(this.onKeyUp_, this));
};
// Kind of object that make you want to stop front-end _engineering_:
ns.KeyManager.prototype.CharCodeToKeyCodeMap = {
90 : "z",
89 : "y",
88 : "x",
67 : "c",
86 : "v"
};
ns.KeyManager.prototype.KeyboardActions = {
"ctrl" : {
"z" : Events.UNDO,
"y" : Events.REDO,
"x" : Events.CUT,
"c" : Events.COPY,
"v" : Events.PASTE
}
};
ns.KeyManager.prototype.onKeyUp_ = function(evt) {
var isMac = false;
if (navigator.appVersion.indexOf("Mac")!=-1) {
// Welcome in mac world where vowels are consons and meta used instead of ctrl:
isMac = true;
}
if (isMac ? evt.metaKey : evt.ctrlKey) {
// Get key pressed:
var letter = this.CharCodeToKeyCodeMap[evt.which];
if(letter) {
var eventToTrigger = this.KeyboardActions["ctrl"][letter];
if(eventToTrigger) {
$.publish(eventToTrigger);
}
};
}
};
})();

View File

@ -40,9 +40,12 @@ pskl.LocalStorageService = (function() {
/** /**
* @private * @private
* TODO(vince): Move that away from LocalStorageService
*/ */
var restoreFromLocalStorage_ = function() { var restoreFromLocalStorage_ = function() {
frameSheet_.deserialize(window.localStorage.snapShot); frameSheet_.deserialize(window.localStorage.snapShot);
frameSheet_.setCurrentFrameIndex(0);
}; };
/** /**

View File

@ -8,14 +8,15 @@
$.namespace("pskl"); $.namespace("pskl");
pskl.ToolSelector = (function() { pskl.ToolSelector = (function() {
var toolInstances = { var toolInstances = {
"simplePen" : new pskl.drawingtools.SimplePen(), "simplePen" : new pskl.drawingtools.SimplePen(),
"eraser" : new pskl.drawingtools.Eraser(), "eraser" : new pskl.drawingtools.Eraser(),
"paintBucket" : new pskl.drawingtools.PaintBucket(), "paintBucket" : new pskl.drawingtools.PaintBucket(),
"stroke" : new pskl.drawingtools.Stroke(), "stroke" : new pskl.drawingtools.Stroke(),
"rectangle" : new pskl.drawingtools.Rectangle(), "rectangle" : new pskl.drawingtools.Rectangle(),
"move" : new pskl.drawingtools.Move() "move" : new pskl.drawingtools.Move(),
"select" : new pskl.drawingtools.Select()
}; };
var currentSelectedTool = toolInstances.simplePen; var currentSelectedTool = toolInstances.simplePen;
var previousSelectedTool = toolInstances.simplePen; var previousSelectedTool = toolInstances.simplePen;

View File

@ -1,44 +1,44 @@
(function () { (function () {
var ns = $.namespace("pskl.controller"); var ns = $.namespace("pskl.controller");
ns.DrawingController = function (framesheet, container, dpi) { ns.DrawingController = function (framesheet, container, dpi) {
// TODO(vincz): Store user prefs in a localstorage string ? // TODO(vincz): Store user prefs in a localstorage string ?
var renderingOptions = { var renderingOptions = {
"dpi": dpi, "dpi": dpi,
"hasGrid" : true "hasGrid" : true
}; };
/** /**
* @public * @public
*/ */
this.framesheet = framesheet; this.framesheet = framesheet;
/** /**
* @public * @public
*/ */
this.overlayFrame = pskl.model.Frame.createEmptyFromFrame(framesheet.getCurrentFrame()); this.overlayFrame = pskl.model.Frame.createEmptyFromFrame(framesheet.getCurrentFrame());
/** /**
* @private * @private
*/ */
this.container = container; this.container = container;
this.renderer = new pskl.rendering.FrameRenderer(this.container, renderingOptions, "drawing-canvas"); this.renderer = new pskl.rendering.FrameRenderer(this.container, renderingOptions, "drawing-canvas");
this.overlayRenderer = new pskl.rendering.FrameRenderer(this.container, renderingOptions, "canvas-overlay"); this.overlayRenderer = new pskl.rendering.FrameRenderer(this.container, renderingOptions, "canvas-overlay");
this.renderer.init(framesheet.getCurrentFrame()); this.renderer.init(framesheet.getCurrentFrame());
this.overlayRenderer.init(this.overlayFrame); this.overlayRenderer.init(this.overlayFrame);
// State of drawing controller: // State of drawing controller:
this.isClicked = false; this.isClicked = false;
this.isRightClicked = false; this.isRightClicked = false;
this.previousMousemoveTime = 0; this.previousMousemoveTime = 0;
this.currentToolBehavior = null; this.currentToolBehavior = null;
this.primaryColor = Constants.DEFAULT_PEN_COLOR; this.primaryColor = Constants.DEFAULT_PEN_COLOR;
this.secondaryColor = Constants.TRANSPARENT_COLOR; this.secondaryColor = Constants.TRANSPARENT_COLOR;
this.initMouseBehavior(); this.initMouseBehavior();
$.subscribe(Events.TOOL_SELECTED, $.proxy(function(evt, toolBehavior) { $.subscribe(Events.TOOL_SELECTED, $.proxy(function(evt, toolBehavior) {
console.log("Tool selected: ", toolBehavior); console.log("Tool selected: ", toolBehavior);
this.currentToolBehavior = toolBehavior; this.currentToolBehavior = toolBehavior;
}, this)); }, this));
@ -51,22 +51,22 @@
this.secondaryColor = color; this.secondaryColor = color;
} }
}, this)); }, this));
}; };
ns.DrawingController.prototype.initMouseBehavior = function() { ns.DrawingController.prototype.initMouseBehavior = function() {
var body = $('body'); var body = $('body');
this.container.mousedown($.proxy(this.onMousedown_, this)); this.container.mousedown($.proxy(this.onMousedown_, this));
this.container.mousemove($.proxy(this.onMousemove_, this)); this.container.mousemove($.proxy(this.onMousemove_, this));
body.mouseup($.proxy(this.onMouseup_, this)); body.mouseup($.proxy(this.onMouseup_, this));
// Deactivate right click: // Deactivate right click:
this.container.contextmenu(this.onCanvasContextMenu_); this.container.contextmenu(this.onCanvasContextMenu_);
}; };
/** /**
* @private * @private
*/ */
ns.DrawingController.prototype.onMousedown_ = function (event) { ns.DrawingController.prototype.onMousedown_ = function (event) {
this.isClicked = true; this.isClicked = true;
if(event.button == 2) { // right click if(event.button == 2) { // right click
@ -87,8 +87,8 @@
}; };
/** /**
* @private * @private
*/ */
ns.DrawingController.prototype.onMousemove_ = function (event) { ns.DrawingController.prototype.onMousemove_ = function (event) {
var currentTime = new Date().getTime(); var currentTime = new Date().getTime();
// Throttling of the mousemove event: // Throttling of the mousemove event:
@ -102,19 +102,27 @@
this.framesheet.getCurrentFrame(), this.framesheet.getCurrentFrame(),
this.overlayFrame this.overlayFrame
); );
// TODO(vincz): Find a way to move that to the model instead of being at the interaction level. // TODO(vincz): Find a way to move that to the model instead of being at the interaction level.
// Eg when drawing, it may make sense to have it here. However for a non drawing tool, // Eg when drawing, it may make sense to have it here. However for a non drawing tool,
// you don't need to draw anything when mousemoving and you request useless localStorage. // you don't need to draw anything when mousemoving and you request useless localStorage.
$.publish(Events.LOCALSTORAGE_REQUEST); $.publish(Events.LOCALSTORAGE_REQUEST);
} else {
this.currentToolBehavior.moveUnactiveToolAt(
coords.col, coords.row,
this.getCurrentColor_(),
this.framesheet.getCurrentFrame(),
this.overlayFrame
);
} }
this.previousMousemoveTime = currentTime; this.previousMousemoveTime = currentTime;
} }
}; };
/** /**
* @private * @private
*/ */
ns.DrawingController.prototype.onMouseup_ = function (event) { ns.DrawingController.prototype.onMouseup_ = function (event) {
if(this.isClicked || this.isRightClicked) { if(this.isClicked || this.isRightClicked) {
// A mouse button was clicked on the drawing canvas before this mouseup event, // A mouse button was clicked on the drawing canvas before this mouseup event,
@ -139,8 +147,8 @@
}, },
/** /**
* @private * @private
*/ */
ns.DrawingController.prototype.getRelativeCoordinates = function (clientX, clientY) { ns.DrawingController.prototype.getRelativeCoordinates = function (clientX, clientY) {
var canvasPageOffset = this.container.offset(); var canvasPageOffset = this.container.offset();
return { return {
@ -150,16 +158,16 @@
}; };
/** /**
* @private * @private
*/ */
ns.DrawingController.prototype.getSpriteCoordinates = function(event) { ns.DrawingController.prototype.getSpriteCoordinates = function(event) {
var coords = this.getRelativeCoordinates(event.clientX, event.clientY); var coords = this.getRelativeCoordinates(event.clientX, event.clientY);
return this.renderer.convertPixelCoordinatesIntoSpriteCoordinate(coords); return this.renderer.convertPixelCoordinatesIntoSpriteCoordinate(coords);
}; };
/** /**
* @private * @private
*/ */
ns.DrawingController.prototype.getCurrentColor_ = function () { ns.DrawingController.prototype.getCurrentColor_ = function () {
if(this.isRightClicked) { if(this.isRightClicked) {
return this.secondaryColor; return this.secondaryColor;
@ -169,45 +177,44 @@
}; };
/** /**
* @private * @private
*/ */
ns.DrawingController.prototype.onCanvasContextMenu_ = function (event) { ns.DrawingController.prototype.onCanvasContextMenu_ = function (event) {
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
event.cancelBubble = true; event.cancelBubble = true;
return false; return false;
}; };
ns.DrawingController.prototype.updateDPI = function (newDPI) { ns.DrawingController.prototype.updateDPI = function (newDPI) {
this.renderer.updateDPI(newDPI); this.renderer.updateDPI(newDPI);
this.overlayRenderer.updateDPI(newDPI); this.overlayRenderer.updateDPI(newDPI);
this.forceRendering_();
this.render();
};
ns.DrawingController.prototype.render = function () {
try {
this.renderFrame();
this.renderOverlay();
} catch (e) {
// TODO : temporary t/c for integration
}
}; };
ns.DrawingController.prototype.renderFrame = function () { ns.DrawingController.prototype.render = function () {
this.renderFrame();
this.renderOverlay();
};
ns.DrawingController.prototype.renderFrame = function () {
var frame = this.framesheet.getCurrentFrame(); var frame = this.framesheet.getCurrentFrame();
var serializedFrame = frame.serialize(); var serializedFrame = frame.serialize();
if (this.serializedFrame != serializedFrame) { if (this.serializedFrame != serializedFrame) {
this.serializedFrame = serializedFrame this.serializedFrame = serializedFrame;
this.renderer.render(frame); this.renderer.render(frame);
} }
}; };
ns.DrawingController.prototype.renderOverlay = function () { ns.DrawingController.prototype.renderOverlay = function () {
var serializedOverlay = this.overlayFrame.serialize(); var serializedOverlay = this.overlayFrame.serialize();
if (this.serializedOverlay != serializedOverlay) { if (this.serializedOverlay != serializedOverlay) {
this.serializedOverlay = serializedOverlay this.serializedOverlay = serializedOverlay;
this.overlayRenderer.render(this.overlayFrame); this.overlayRenderer.render(this.overlayFrame);
} }
}; };
ns.DrawingController.prototype.forceRendering_ = function () {
this.serializedFrame = this.serializedOverlay = null;
}
})(); })();

View File

@ -12,6 +12,8 @@
ns.BaseTool.prototype.moveToolAt = function(col, row, color, frame, overlay) {}; ns.BaseTool.prototype.moveToolAt = function(col, row, color, frame, overlay) {};
ns.BaseTool.prototype.moveUnactiveToolAt = function(col, row, color, frame, overlay) {};
ns.BaseTool.prototype.releaseToolAt = function(col, row, color, frame, overlay) {}; ns.BaseTool.prototype.releaseToolAt = function(col, row, color, frame, overlay) {};
/** /**

View File

@ -32,14 +32,15 @@
// When the user moussemove (before releasing), we dynamically compute the // When the user moussemove (before releasing), we dynamically compute the
// pixel to draw the line and draw this line in the overlay : // pixel to draw the line and draw this line in the overlay :
var strokePoints = this.getRectanglePixels_(this.startCol, col, this.startRow, row); var strokePoints = pskl.PixelUtils.getBoundRectanglePixels(this.startCol, this.startRow, col, row);
if(color == Constants.TRANSPARENT_COLOR) {
color = Constants.SELECTION_TRANSPARENT_COLOR;
}
// Drawing current stroke: // Drawing current stroke:
for(var i = 0; i< strokePoints.length; i++) { for(var i = 0; i< strokePoints.length; i++) {
if(color == Constants.TRANSPARENT_COLOR) {
color = Constants.SELECTION_TRANSPARENT_COLOR;
}
overlay.setPixel(strokePoints[i].col, strokePoints[i].row, color); overlay.setPixel(strokePoints[i].col, strokePoints[i].row, color);
} }
}; };
@ -51,7 +52,7 @@
overlay.clear(); overlay.clear();
// If the stroke tool is released outside of the canvas, we cancel the stroke: // If the stroke tool is released outside of the canvas, we cancel the stroke:
if(frame.containsPixel(col, row)) { if(frame.containsPixel(col, row)) {
var strokePoints = this.getRectanglePixels_(this.startCol, col, this.startRow, row); var strokePoints = pskl.PixelUtils.getBoundRectanglePixels(this.startCol, this.startRow, col, row);
for(var i = 0; i< strokePoints.length; i++) { for(var i = 0; i< strokePoints.length; i++) {
// Change model: // Change model:
frame.setPixel(strokePoints[i].col, strokePoints[i].row, color); frame.setPixel(strokePoints[i].col, strokePoints[i].row, color);

View File

@ -0,0 +1,129 @@
/*
* @provide pskl.drawingtools.Select
*
* @require pskl.utils
*/
(function() {
var ns = $.namespace("pskl.drawingtools");
ns.Select = function() {
this.toolId = "tool-select";
this.secondaryToolId = "tool-move";
this.BodyRoot = $('body');
// Select's first point coordinates (set in applyToolAt)
this.startCol = null;
this.startRow = null;
};
pskl.utils.inherit(ns.Select, ns.BaseTool);
/**
* @override
*/
ns.Select.prototype.applyToolAt = function(col, row, color, frame, overlay) {
this.startCol = col;
this.startRow = row;
this.lastCol = col;
this.lastRow = row;
// TODO(vincz): Comment here nasty vince
if(overlay.getPixel(col, row) != Constants.SELECTION_TRANSPARENT_COLOR) {
this.mode = "select";
// Drawing the first point of the rectangle in the fake overlay canvas:
overlay.setPixel(col, row, color);
}
else {
this.mode = "moveSelection";
this.overlayFrameReference = overlay.clone();
}
};
ns.Select.prototype.moveToolAt = function(col, row, color, frame, overlay) {
if(this.mode == "select") {
// Clean overlay canvas:
overlay.clear();
// When the user moussemove (before releasing), we dynamically compute the
// pixel to draw the line and draw this line in the overlay :
var strokePoints = pskl.PixelUtils.getBoundRectanglePixels(this.startCol, this.startRow, col, row);
color = Constants.SELECTION_TRANSPARENT_COLOR;
// Drawing current stroke:
for(var i = 0; i< strokePoints.length; i++) {
overlay.setPixel(strokePoints[i].col, strokePoints[i].row, color);
}
}
else if(this.mode == "moveSelection") {
// TODO(vincz): Comment here nasty vince
var deltaCol = col - this.lastCol;
var deltaRow = row - this.lastRow;
console.log(deltaCol)
console.log(deltaRow)
var colDiff = col - this.startCol, rowDiff = row - this.startRow;
if (colDiff != 0 || rowDiff != 0) {
// Update selection on overlay frame:
this.shiftOverlayFrame_(colDiff, rowDiff, overlay, this.overlayFrameReference);
// Update selection model:
$.publish(Events.SELECTION_MOVE_REQUEST, [deltaCol, deltaRow]);
}
this.lastCol = col;
this.lastRow = row;
}
};
// TODO(vincz): Comment here nasty vince
ns.Select.prototype.moveUnactiveToolAt = function(col, row, color, frame, overlay) {
// If we mouseover the selection draw inside the overlay frame, show the 'move' cursor
// instead of the 'select' one. It indicates that we can move the selection by dragndroping it.
if(overlay.getPixel(col, row) != Constants.SELECTION_TRANSPARENT_COLOR) {
this.BodyRoot.addClass(this.toolId);
this.BodyRoot.removeClass(this.secondaryToolId);
} else {
this.BodyRoot.addClass(this.secondaryToolId);
this.BodyRoot.removeClass(this.toolId);
}
};
/**
* @override
*/
ns.Select.prototype.releaseToolAt = function(col, row, color, frame, overlay) {
if(this.mode == "select") {
overlay.clear();
if(this.startCol == col &&this.startRow == row) {
$.publish(Events.SELECTION_DISMISSED);
} else {
var selection = new pskl.selection.RectangularSelection(
this.startCol, this.startRow, col, row);
$.publish(Events.SELECTION_CREATED, [selection]);
}
} else if(this.mode == "moveSelection") {
this.moveToolAt(col, row, color, frame, overlay);
}
};
/**
* @private
*/
ns.Select.prototype.shiftOverlayFrame_ = function (colDiff, rowDiff, overlayFrame, reference) {
var color;
for (var col = 0 ; col < overlayFrame.getWidth() ; col++) {
for (var row = 0 ; row < overlayFrame.getHeight() ; row++) {
if (reference.containsPixel(col - colDiff, row - rowDiff)) {
color = reference.getPixel(col - colDiff, row - rowDiff);
} else {
color = Constants.TRANSPARENT_COLOR;
}
overlayFrame.setPixel(col, row, color)
}
}
};
})();

View File

@ -25,7 +25,8 @@
ns.FrameSheet.prototype.setCurrentFrameIndex = function (index) { ns.FrameSheet.prototype.setCurrentFrameIndex = function (index) {
this.currentFrameIndex = index; this.currentFrameIndex = index;
$.publish(Events.FRAMESHEET_RESET); $.publish(Events.CURRENT_FRAME_SET, [this.getCurrentFrame()]);
$.publish(Events.FRAMESHEET_RESET); // Is it no to overkill to have this here ?
}; };
ns.FrameSheet.prototype.getUsedColors = function() { ns.FrameSheet.prototype.getUsedColors = function() {

View File

@ -17,8 +17,7 @@ $.namespace("pskl");
framePixelHeight = 32, framePixelHeight = 32,
// Scaling factors for a given frameSheet rendering: // Scaling factors for a given frameSheet rendering:
// Main drawing area: // Main drawing area dpi is calculated dynamically
drawingCanvasDpi = 20,
// Canvas preview film canvases: // Canvas preview film canvases:
previewTileCanvasDpi = 4, previewTileCanvasDpi = 4,
// Animated canvas preview: // Animated canvas preview:
@ -30,15 +29,13 @@ $.namespace("pskl");
var piskel = { var piskel = {
init : function () { init : function () {
piskel.initDPIs_();
frameSheet = new pskl.model.FrameSheet(framePixelWidth, framePixelHeight); frameSheet = new pskl.model.FrameSheet(framePixelWidth, framePixelHeight);
frameSheet.addEmptyFrame(); frameSheet.addEmptyFrame();
this.drawingController = new pskl.controller.DrawingController( this.drawingController = new pskl.controller.DrawingController(
frameSheet, frameSheet,
$('#drawing-canvas-container'), $('#drawing-canvas-container'),
drawingCanvasDpi this.calculateDPIsForDrawingCanvas_()
); );
this.animationController = new pskl.controller.AnimatedPreviewController( this.animationController = new pskl.controller.AnimatedPreviewController(
@ -47,19 +44,33 @@ $.namespace("pskl");
previewAnimationCanvasDpi previewAnimationCanvasDpi
); );
this.previewsController = new pskl.controller.PreviewFilmController( this.previewsController = new pskl.controller.PreviewFilmController(
frameSheet, frameSheet,
$('#preview-list'), $('#preview-list'),
previewTileCanvasDpi previewTileCanvasDpi
); );
// To catch the current active frame, the selection manager have to be initialized before
// the 'frameSheet.setCurrentFrameIndex(0);'
// TODO(vincz): Slice each constructor to have:
// - an event(s) listening init
// - an event(s) triggering init
// All listerners will be hook in a first step, then all event triggering inits will be called
// in a second batch.
this.selectionManager =
new pskl.selection.SelectionManager(this.drawingController.overlayFrame);
// DO NOT MOVE THIS LINE (see comment above)
frameSheet.setCurrentFrameIndex(0);
this.animationController.init(); this.animationController.init();
this.previewsController.init(); this.previewsController.init();
this.historyManager = new pskl.HistoryManager(frameSheet); this.historyManager = new pskl.HistoryManager(frameSheet);
this.historyManager.init(); this.historyManager.init();
this.keyManager = new pskl.KeyManager();
pskl.NotificationService.init(); pskl.NotificationService.init();
pskl.LocalStorageService.init(frameSheet); pskl.LocalStorageService.init(frameSheet);
@ -73,13 +84,11 @@ $.namespace("pskl");
pskl.LocalStorageService.displayRestoreNotification(); pskl.LocalStorageService.displayRestoreNotification();
} }
$.subscribe('SET_ACTIVE_FRAME', function(evt, frameId) {
frameSheet.setCurrentFrameIndex(frameId);
});
var drawingLoop = new pskl.rendering.DrawingLoop(); var drawingLoop = new pskl.rendering.DrawingLoop();
drawingLoop.addCallback(this.render, this); drawingLoop.addCallback(this.render, this);
drawingLoop.start(); drawingLoop.start();
this.connectResizeToDpiUpdate_();
}, },
render : function (delta) { render : function (delta) {
@ -88,18 +97,18 @@ $.namespace("pskl");
this.previewsController.render(delta); this.previewsController.render(delta);
}, },
/** connectResizeToDpiUpdate_ : function () {
* Override default DPIs. $(window).resize($.proxy(this.startDPIUpdateTimer_, this));
* @private },
*/
initDPIs_ : function() { startDPIUpdateTimer_ : function () {
drawingCanvasDpi = piskel.calculateDPIsForDrawingCanvas_(); if (this.dpiUpdateTimer) window.clearInterval(this.dpiUpdateTimer);
// TODO(vincz): Add throttling on window.resize event. this.dpiUpdateTimer = window.setTimeout($.proxy(this.updateDPIForViewport, this), 200);
$(window).resize($.proxy(function() { },
drawingCanvasDpi = piskel.calculateDPIsForDrawingCanvas_();
this.drawingController.updateDPI(drawingCanvasDpi); updateDPIForViewport : function () {
}, this)); var dpi = piskel.calculateDPIsForDrawingCanvas_();
// TODO(vincz): Check for user settings eventually from localstorage. this.drawingController.updateDPI(dpi);
}, },
/** /**

View File

@ -0,0 +1,32 @@
(function () {
var ns = $.namespace("pskl.selection");
ns.BaseSelection = function () {
this.reset();
};
ns.BaseSelection.prototype.reset = function () {
this.pixels = [];
};
ns.BaseSelection.prototype.move = function (colDiff, rowDiff) {
var movedPixel, movedPixels = [];
for(var i=0, l=this.pixels.length; i<l; i++) {
movedPixel = this.pixels[i];
movedPixel.col += colDiff;
movedPixel.row += rowDiff;
movedPixels.push(movedPixel)
}
this.pixels = movedPixels;
};
ns.BaseSelection.prototype.fillSelectionFromFrame = function (targetFrame) {
var pixelWithCopiedColor;
for(var i=0, l=this.pixels.length; i<l; i++) {
pixelWithCopiedColor = this.pixels[i];
pixelWithCopiedColor.copiedColor =
targetFrame.getPixel(pixelWithCopiedColor.col, pixelWithCopiedColor.row);
}
};
})();

View File

@ -0,0 +1,9 @@
(function () {
var ns = $.namespace("pskl.selection");
ns.RectangularSelection = function (x0, y0, x1, y1) {
this.pixels = pskl.PixelUtils.getRectanglePixels(x0, y0, x1, y1);
};
pskl.utils.inherit(ns.RectangularSelection, ns.BaseSelection);
})();

View File

@ -0,0 +1,144 @@
(function () {
var ns = $.namespace("pskl.selection");
ns.SelectionManager = function (overlayFrame) {
this.overlayFrame = overlayFrame;
this.currentSelection = null;
this.currentFrame = null;
$.subscribe(Events.CURRENT_FRAME_SET, $.proxy(this.onCurrentFrameChanged_, this));
$.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));
$.subscribe(Events.PASTE, $.proxy(this.onPaste_, this));
$.subscribe(Events.COPY, $.proxy(this.onCopy_, this));
$.subscribe(Events.CUT, $.proxy(this.onCut_, this));
$.subscribe(Events.TOOL_SELECTED, $.proxy(this.onToolSelected_, this));
};
/**
* @private
*/
ns.SelectionManager.prototype.cleanSelection_ = function(selection) {
if(this.currentSelection) {
this.currentSelection.reset();
}
this.overlayFrame.clear();
};
/**
* @private
*/
ns.SelectionManager.prototype.onCurrentFrameChanged_ = function(evt, currentFrame) {
if(currentFrame) {
this.currentFrame = currentFrame;
}
else {
throw "Bad current frame set in SelectionManager";
}
};
/**
* @private
*/
ns.SelectionManager.prototype.onToolSelected_ = function(evt, tool) {
if(!(tool instanceof pskl.drawingtools.Select)) {
this.cleanSelection_();
}
};
/**
* @private
*/
ns.SelectionManager.prototype.onSelectionDismissed_ = function(evt) {
this.cleanSelection_();
};
/**
* @private
*/
ns.SelectionManager.prototype.onCut_ = function(evt) {
if(this.currentSelection && this.currentFrame) {
// Put cut target into the selection:
this.currentSelection.fillSelectionFromFrame(this.currentFrame);
var pixels = this.currentSelection.pixels;
for(var i=0, l=pixels.length; i<l; i++) {
try {
this.currentFrame.setPixel(pixels[i].col, pixels[i].row, Constants.TRANSPARENT_COLOR);
}
catch(e) {
// Catchng out of frame's bound pixels without testing
}
}
}
else {
throw "Bad state for CUT callback in SelectionManager";
}
};
ns.SelectionManager.prototype.onPaste_ = function(evt) {
if(this.currentSelection && this.currentFrame) {
var pixels = this.currentSelection.pixels;
for(var i=0, l=pixels.length; i<l; i++) {
try {
this.currentFrame.setPixel(
pixels[i].col, pixels[i].row,
pixels[i].copiedColor);
}
catch(e) {
// Catchng out of frame's bound pixels without testing
}
}
}
else {
throw "Bad state for PASTE callback in SelectionManager";
}
};
/**
* @private
*/
ns.SelectionManager.prototype.onCopy_ = function(evt) {
if(this.currentSelection && this.currentFrame) {
this.currentSelection.fillSelectionFromFrame(this.currentFrame);
}
else {
throw "Bad state for CUT callback in SelectionManager";
}
};
/**
* @private
*/
ns.SelectionManager.prototype.onSelectionCreated_ = function(evt, selection) {
if(selection) {
this.currentSelection = selection;
var pixels = selection.pixels;
for(var i=0, l=pixels.length; i<l; i++) {
this.overlayFrame.setPixel(pixels[i].col, pixels[i].row, Constants.SELECTION_TRANSPARENT_COLOR);
}
}
else {
throw "No selection set in SelectionManager";
}
};
/**
* @private
*/
ns.SelectionManager.prototype.onSelectionMoved_ = function(evt, colDiff, rowDiff) {
if(this.currentSelection) {
this.currentSelection.move(colDiff, rowDiff);
}
else {
throw "Bad state: No currentSelection set when trying to move it in SelectionManager";
}
};
})();

60
js/utils/pixelUtils.js Normal file
View File

@ -0,0 +1,60 @@
(function () {
var ns = $.namespace("pskl");
ns.PixelUtils = {
getRectanglePixels : function (x0, y0, x1, y1) {
var pixels = [];
var swap;
if(x0 > x1) {
swap = x0;
x0 = x1;
x1 = swap;
}
if(y0 > y1) {
swap = y0;
y0 = y1;
y1 = swap;
}
for(var x = x0; x <= x1; x++) {
for(var y = y0; y <= y1; y++) {
pixels.push({"col": x, "row": y});
}
}
return pixels;
},
getBoundRectanglePixels : function (x0, y0, x1, y1) {
var pixels = [];
var swap;
if(x0 > x1) {
swap = x0;
x0 = x1;
x1 = swap;
}
if(y0 > y1) {
swap = y0;
y0 = y1;
y1 = swap;
}
// Creating horizontal sides of the rectangle:
for(var x = x0; x <= x1; x++) {
pixels.push({"col": x, "row": y0});
pixels.push({"col": x, "row": y1});
}
// Creating vertical sides of the rectangle:
for(var y = y0; y <= y1; y++) {
pixels.push({"col": x0, "row": y});
pixels.push({"col": x1, "row": y});
}
return pixels;
}
};
})();