Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Comparing changes

Choose two branches to see what's changed or to start a new pull request. If you need to, you can also compare across forks.

Open a pull request

Create a new pull request by comparing changes across two branches. If you need to, you can also compare across forks.
base fork: trethaller/teztura
base: 9155580bd5
...
head fork: trethaller/teztura
compare: b6d8d6fe55
Checking mergeability… Don't worry, you can still create the pull request.
  • 8 commits
  • 10 files changed
  • 0 commit comments
  • 1 contributor
View
4 index.html
@@ -9,7 +9,7 @@
<script src="js/vendor/jquery-1.10.1.min.js"></script>
<script src="js/vendor/jquery-ui-1.10.3.custom.js"></script>
<script src="js/vendor/underscore-min.js"></script>
-<script src="js/vendor/backbone-min.js"></script>
+<script src="js/vendor/backbone.js"></script>
<script src="js/core.js"></script>
<script src="js/tools.js"></script>
<script src="js/app.js"></script>
@@ -30,6 +30,8 @@
<div class="properties"></div>
</div>
</div>
+ <pre id="status-bar">
+ </pre>
</div>
<!--[if IE]>
View
287 js/app.coffee
@@ -2,26 +2,50 @@
class Document
constructor: (@width,@height)->
@layer = new Layer(@width,@height)
+ @backup = new Layer(@width,@height)
+ @history = []
+ @histIndex = -1
-Editor = Backbone.Model.extend({
- toolObject: null
- getToolObject: ()->
- if @get('toolObject') is null
- console.log "Creating brush of type " + @get("tool").description.name
- o = @get('tool').createTool(this)
- @set('toolObject', o)
- return @get('toolObject')
- setToolDirty: ()->
- @set('toolObject', null)
-})
+ afterEdit: (rect)->
+ if @histIndex > 0
+ @history.splice 0, @histIndex
+
+ @history.splice 0, 0, {
+ data: @backup.getCopy(rect)
+ rect: rect
+ }
+ @backup.getBuffer().set(@layer.getBuffer())
+ histSize = 10
+ if @history.length > histSize
+ @history.splice(histSize)
+
+ @histIndex = -1
+ console.log "History len: #{this.history.length}"
+
+ undo: ->
+ if @histIndex >= @history.length - 1
+ return
+
+ if @histIndex is -1
+ @afterEdit(@history[0].rect)
+ @histIndex = 1
+ else
+ @histIndex++
+
+ console.log "History idx: #{this.histIndex}"
+ @restore( @history[ @histIndex ] )
+
+ redo: ->
+ if @histIndex <= 0
+ return
+ @histIndex--
+ console.log "History idx: #{this.histIndex}"
+ @restore( @history[ @histIndex ] )
+
+
+ restore: (histItem)->
+ @layer.setData(histItem.data, histItem.rect)
-editor = new Editor {
- doc: null
- tool: null
- renderer: null
- tiling: true
- targetValue: 1.0
-}
Renderers = [GammaRenderer, NormalRenderer, GradientRenderer]
Tools = [RoundBrush, Picker]
@@ -114,54 +138,53 @@ class DocumentView
@context.mozImageSmoothingEnabled = false
- self = this
- getCoords = (e)->
+ getCoords = (e)=>
x = e.pageX-$backCanvas.position().left
y = e.pageY-$backCanvas.position().top
return new Vec2(x,y)
- getCanvasCoords = (e)->
+ getCanvasCoords = (e)=>
v = getCoords(e)
- return self.screenToCanvas(v)
+ return @screenToCanvas(v)
local = {}
- $backCanvas.mousedown (e)->
+ $backCanvas.mousedown (e)=>
e.preventDefault()
if e.which is 1
- self.drawing = true
+ @drawing = true
+ @actionDirtyRect = null
coords = getCanvasCoords(e)
editor.getToolObject().beginDraw(coords)
- self.onDraw(coords)
+ @onDraw(coords)
if e.which is 2
- self.panning = true
+ @panning = true
local.panningStart = getCoords(e)
- local.offsetStart = self.offset.clone()
+ local.offsetStart = @offset.clone()
- $container.mouseup (e)->
+ $container.mouseup (e)=>
e.preventDefault()
if e.which is 1
editor.getToolObject().endDraw(getCanvasCoords(e))
- self.drawing = false
+ @drawing = false
+ if @actionDirtyRect?
+ doc.afterEdit(@actionDirtyRect)
if e.which is 2
- self.panning = false
+ @panning = false
- $container.mousemove (e)->
+ $container.mousemove (e)=>
e.preventDefault()
- if self.drawing
- self.onDraw(getCanvasCoords(e))
+ if @drawing
+ @onDraw(getCanvasCoords(e))
- if self.panning
+ if @panning
curPos = getCoords(e)
o = local.offsetStart.add(curPos.sub(local.panningStart))
- limW = self.doc.width / 3.0
- limH = self.doc.height / 3.0
- self.offset.x = Math.min(Math.max(o.x, -limW), limW)
- self.offset.y = Math.min(Math.max(o.y, -limH), limH)
- self.rePaint()
+ @offset = o
+ @rePaint()
screenToCanvas: (pt)->
return pt.sub(@offset).scale(1.0/@scale)
@@ -184,8 +207,6 @@ class DocumentView
ctx.drawImage(@canvas, 0, 0)
onDraw: (pos)->
- self = this
-
pressure = getPenPressure()
dirtyRects = []
@@ -201,39 +222,84 @@ class DocumentView
for yoff in [-1,0,1]
dirtyRects.push(r.offset(new Vec2(xoff * layerRect.width, yoff * layerRect.height)))
else
- dirtyRects.push(r)
+ dirtyRects.push(r.intersect(layerRect))
dirtyRects = dirtyRects
.map((r)->r.intersect(layerRect))
.filter((r)->not r.isEmpty())
+ dirtyRects.forEach (r)=>
+ if not @actionDirtyRect?
+ @actionDirtyRect = r.clone()
+ else
+ @actionDirtyRect.extend(r)
+
+ if false # Log dirty rects
+ totalArea = dirtyRects
+ .map((r)-> r.width * r.height)
+ .reduce((a,b)-> a+b)
+ console.log "#{dirtyRects.length} rects, #{Math.round(Math.sqrt(totalArea))} px²"
+
if true
#setTimeout (()->
- editor.get('renderer').renderLayer(layer, self, dirtyRects)
- self.rePaint()
+ editor.get('renderer').renderLayer(layer, @, dirtyRects)
+ @rePaint()
#), 0
# ---
-getPenPressure = () ->
- plugin = document.getElementById('wtPlugin')
- penAPI = plugin.penAPI
- if penAPI and penAPI.pointerType > 0
- return penAPI.pressure
- return 1.0
-
-# ---
-
-
-status = (txt)->
- $('#status-bar').text(txt)
-
-view = null
+class Editor extends Backbone.Model
+ defaults: ->
+ doc: null
+ tool: null
+ preset: null
+ renderer: null
+ tiling: true
+ targetValue: 1.0
+ altkeyDown: false
+
+ initialize: ->
+ @toolObject = null
+ @on 'change:tool', ()->
+ @setToolDirty()
+ tool = @get('tool')
+ toolsProperties.setTool(tool)
+
+ @on 'change:preset', ->
+ p = @get('preset')
+ @set('tool', p.tools[0])
+
+ @on 'change:altkeyDown', ->
+ idx = if @get('altkeyDown') then 1 else 0
+ p = @get('preset')
+ @set('tool', p.tools[idx])
+
+ @on 'change:renderer', ()->
+ @get('view').reRender()
+ @get('view').rePaint()
+
+ createDoc: (w,h)->
+ doc = new Document(512, 512)
+ fillLayer doc.layer, (x,y)->
+ return -1
+
+ @set('doc', doc)
+ @set('view', new DocumentView($('.document-view'), doc))
+
+ getToolObject: ->
+ if @get('toolObject') is null
+ console.log "Creating brush of type " + @get("tool").description.name
+ o = @get('tool').createTool(this)
+ @set('toolObject', o)
+ return @get('toolObject')
+ setToolDirty: ->
+ @set('toolObject', null)
-refresh = ()->
- view.reRender()
- view.rePaint()
+ refresh: ->
+ v = @get('view')
+ v.reRender()
+ v.rePaint()
PropertyView = Backbone.View.extend
className: "property"
@@ -247,63 +313,79 @@ PropertyView = Backbone.View.extend
# Slider
if prop.range?
- step = if prop.type is 'int' then 1 else (prop.range[1]-prop.range[0]) / 100
+ power = prop.power or 1.0
+ conv = (v)-> Math.pow(v, power)
+ invconv = (v)-> Math.pow(v, 1.0 / power)
+
+ rmin = invconv(prop.range[0])
+ rmax = invconv(prop.range[1])
+ step = if prop.type is 'int' then 1 else (rmax-rmin) / 100
+
$slider = $('<div/>').slider({
- min: prop.range[0]
- max: prop.range[1]
- value: tool.get(prop.id)
+ min: rmin
+ max: rmax
+ value: invconv(tool.get(prop.id))
step: step
change: (evt, ui)->
- tool.set(prop.id, ui.value)
+ tool.set(prop.id, conv(ui.value))
editor.setToolDirty()
}).width(200).appendTo(@$el)
- $val = $('<input/>')
+ $input = $('<input/>')
.val(tool.get(prop.id))
.appendTo(@$el)
.change (evt)->
if prop.type is 'int'
- tool.set(prop.id, parseInt($val.val()))
+ tool.set(prop.id, parseInt($input.val()))
else
- tool.set(prop.id, parseFloat($val.val()))
+ tool.set(prop.id, parseFloat($input.val()))
@listenTo @model.tool, "change:#{prop.id}", ()->
v = tool.get(prop.id)
- $val.val(v)
- $slider.slider("value", v)
+ $input.val(v)
+ $slider.slider("value", invconv(v))
# --
class PropertyPanel
- views: []
- constructor: (@selector)-> ;
+ constructor: (@selector)->
+ @views = []
+
setTool: (tool)->
- self = this
@removeViews()
- tool.properties.forEach (prop)->
+ tool.properties.forEach (prop)=>
v = new PropertyView
model: {prop, tool}
- $(self.selector).append(v.$el)
- self.views.push(v)
+ $(@selector).append(v.$el)
+ @views.push(v)
removeViews: ()->
@views.forEach (v)->
v.remove()
@views = []
+# ---
-toolsProperties = new PropertyPanel '#tools > .properties'
+getPenPressure = () ->
+ plugin = document.getElementById('wtPlugin')
+ penAPI = plugin.penAPI
+ if penAPI and penAPI.pointerType > 0
+ return penAPI.pressure
+ return 1.0
+
+
+status = (txt)->
+ $('#status-bar').text(txt)
-editor.on 'change:tool', ()->
- editor.setToolDirty()
- tool = editor.get('tool')
- toolsProperties.setTool(tool)
-editor.on 'change:renderer', ()->
- view.reRender()
- view.rePaint()
+
+refresh = ()->
+ editor.refresh()
+editor = null
+toolsProperties = null
+
createToolsButtons = ($container)->
$container.empty()
@@ -336,7 +418,7 @@ createPalette = ($container)->
$slider = $('<div/>').slider({
min: -1.0
max: 1.0
- value: 0
+ value: editor.get('targetValue')
step: 0.005
change: (evt, ui)->
editor.set('targetValue', ui.value)
@@ -361,22 +443,39 @@ loadGradient = (name, url)->
imageObj.src = url
# --
-
loadGradient('g1', 'img/gradient-1.png')
+
+$(window).keydown (e)->
+ if e.key is 'Control'
+ editor.set('altkeyDown', true)
+
+$(window).keyup (e)->
+ if e.key is 'Control'
+ editor.set('altkeyDown', false)
+
+ if e.ctrlKey
+ switch e.keyCode
+ when 90
+ editor.get('doc').undo()
+ editor.refresh()
+ when 89
+ editor.get('doc').redo()
+ editor.refresh()
+
$(document).ready ()->
- doc = new Document(512, 512)
- fillLayer doc.layer, (x,y)->
- return -1
- view = new DocumentView($('.document-view'), doc)
+ toolsProperties = new PropertyPanel '#tools > .properties'
+ editor = new Editor()
+ editor.createDoc(512, 512)
+
createToolsButtons($('#tools > .buttons'))
createRenderersButtons($('#renderers > .buttons'))
createPalette($('#palette'))
createCommandsButtons($('#commands'))
- editor.set('doc', doc)
- editor.set('tool', RoundBrush)
+ editor.set('preset', {
+ tools: [RoundBrush, Picker]
+ })
editor.set('renderer', GammaRenderer)
- editor.set('targetValue', 0.0)
View
339 js/app.js
@@ -1,40 +1,66 @@
// Generated by CoffeeScript 1.6.3
-var Commands, Document, DocumentView, Editor, PropertyPanel, PropertyView, Renderers, Tools, createCommandsButtons, createPalette, createRenderersButtons, createToolsButtons, editor, getPenPressure, loadGradient, refresh, status, toolsProperties, view;
+var Commands, Document, DocumentView, Editor, PropertyPanel, PropertyView, Renderers, Tools, createCommandsButtons, createPalette, createRenderersButtons, createToolsButtons, editor, getPenPressure, loadGradient, refresh, status, toolsProperties, _ref,
+ __hasProp = {}.hasOwnProperty,
+ __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Document = (function() {
function Document(width, height) {
this.width = width;
this.height = height;
this.layer = new Layer(this.width, this.height);
+ this.backup = new Layer(this.width, this.height);
+ this.history = [];
+ this.histIndex = -1;
}
- return Document;
+ Document.prototype.afterEdit = function(rect) {
+ var histSize;
+ if (this.histIndex > 0) {
+ this.history.splice(0, this.histIndex);
+ }
+ this.history.splice(0, 0, {
+ data: this.backup.getCopy(rect),
+ rect: rect
+ });
+ this.backup.getBuffer().set(this.layer.getBuffer());
+ histSize = 10;
+ if (this.history.length > histSize) {
+ this.history.splice(histSize);
+ }
+ this.histIndex = -1;
+ return console.log("History len: " + this.history.length);
+ };
-})();
+ Document.prototype.undo = function() {
+ if (this.histIndex >= this.history.length - 1) {
+ return;
+ }
+ if (this.histIndex === -1) {
+ this.afterEdit(this.history[0].rect);
+ this.histIndex = 1;
+ } else {
+ this.histIndex++;
+ }
+ console.log("History idx: " + this.histIndex);
+ return this.restore(this.history[this.histIndex]);
+ };
-Editor = Backbone.Model.extend({
- toolObject: null,
- getToolObject: function() {
- var o;
- if (this.get('toolObject') === null) {
- console.log("Creating brush of type " + this.get("tool").description.name);
- o = this.get('tool').createTool(this);
- this.set('toolObject', o);
+ Document.prototype.redo = function() {
+ if (this.histIndex <= 0) {
+ return;
}
- return this.get('toolObject');
- },
- setToolDirty: function() {
- return this.set('toolObject', null);
- }
-});
+ this.histIndex--;
+ console.log("History idx: " + this.histIndex);
+ return this.restore(this.history[this.histIndex]);
+ };
-editor = new Editor({
- doc: null,
- tool: null,
- renderer: null,
- tiling: true,
- targetValue: 1.0
-});
+ Document.prototype.restore = function(histItem) {
+ return this.layer.setData(histItem.data, histItem.rect);
+ };
+
+ return Document;
+
+})();
Renderers = [GammaRenderer, NormalRenderer, GradientRenderer];
@@ -129,7 +155,8 @@ DocumentView = (function() {
DocumentView.prototype.scale = 1.0;
function DocumentView($container, doc) {
- var $backCanvas, $canvas, getCanvasCoords, getCoords, local, self;
+ var $backCanvas, $canvas, getCanvasCoords, getCoords, local,
+ _this = this;
this.doc = doc;
$container.empty();
$canvas = $('<canvas/>', {
@@ -150,7 +177,6 @@ DocumentView = (function() {
this.context = $canvas[0].getContext('2d');
this.imageData = this.context.getImageData(0, 0, doc.width, doc.height);
this.context.mozImageSmoothingEnabled = false;
- self = this;
getCoords = function(e) {
var x, y;
x = e.pageX - $backCanvas.position().left;
@@ -160,48 +186,49 @@ DocumentView = (function() {
getCanvasCoords = function(e) {
var v;
v = getCoords(e);
- return self.screenToCanvas(v);
+ return _this.screenToCanvas(v);
};
local = {};
$backCanvas.mousedown(function(e) {
var coords;
e.preventDefault();
if (e.which === 1) {
- self.drawing = true;
+ _this.drawing = true;
+ _this.actionDirtyRect = null;
coords = getCanvasCoords(e);
editor.getToolObject().beginDraw(coords);
- self.onDraw(coords);
+ _this.onDraw(coords);
}
if (e.which === 2) {
- self.panning = true;
+ _this.panning = true;
local.panningStart = getCoords(e);
- return local.offsetStart = self.offset.clone();
+ return local.offsetStart = _this.offset.clone();
}
});
$container.mouseup(function(e) {
e.preventDefault();
if (e.which === 1) {
editor.getToolObject().endDraw(getCanvasCoords(e));
- self.drawing = false;
+ _this.drawing = false;
+ if (_this.actionDirtyRect != null) {
+ doc.afterEdit(_this.actionDirtyRect);
+ }
}
if (e.which === 2) {
- return self.panning = false;
+ return _this.panning = false;
}
});
$container.mousemove(function(e) {
- var curPos, limH, limW, o;
+ var curPos, o;
e.preventDefault();
- if (self.drawing) {
- self.onDraw(getCanvasCoords(e));
+ if (_this.drawing) {
+ _this.onDraw(getCanvasCoords(e));
}
- if (self.panning) {
+ if (_this.panning) {
curPos = getCoords(e);
o = local.offsetStart.add(curPos.sub(local.panningStart));
- limW = self.doc.width / 3.0;
- limH = self.doc.height / 3.0;
- self.offset.x = Math.min(Math.max(o.x, -limW), limW);
- self.offset.y = Math.min(Math.max(o.y, -limH), limH);
- return self.rePaint();
+ _this.offset = o;
+ return _this.rePaint();
}
});
}
@@ -232,8 +259,8 @@ DocumentView = (function() {
};
DocumentView.prototype.onDraw = function(pos) {
- var dirtyRects, layer, layerRect, pressure, r, self, tool, xoff, yoff, _i, _j, _len, _len1, _ref, _ref1;
- self = this;
+ var dirtyRects, layer, layerRect, pressure, r, tool, totalArea, xoff, yoff, _i, _j, _len, _len1, _ref, _ref1,
+ _this = this;
pressure = getPenPressure();
dirtyRects = [];
layer = this.doc.layer;
@@ -251,16 +278,31 @@ DocumentView = (function() {
}
}
} else {
- dirtyRects.push(r);
+ dirtyRects.push(r.intersect(layerRect));
}
dirtyRects = dirtyRects.map(function(r) {
return r.intersect(layerRect);
}).filter(function(r) {
return !r.isEmpty();
});
+ dirtyRects.forEach(function(r) {
+ if (_this.actionDirtyRect == null) {
+ return _this.actionDirtyRect = r.clone();
+ } else {
+ return _this.actionDirtyRect.extend(r);
+ }
+ });
+ if (false) {
+ totalArea = dirtyRects.map(function(r) {
+ return r.width * r.height;
+ }).reduce(function(a, b) {
+ return a + b;
+ });
+ console.log("" + dirtyRects.length + " rects, " + (Math.round(Math.sqrt(totalArea))) + " px²");
+ }
if (true) {
- editor.get('renderer').renderLayer(layer, self, dirtyRects);
- return self.rePaint();
+ editor.get('renderer').renderLayer(layer, this, dirtyRects);
+ return this.rePaint();
}
};
@@ -268,73 +310,139 @@ DocumentView = (function() {
})();
-getPenPressure = function() {
- var penAPI, plugin;
- plugin = document.getElementById('wtPlugin');
- penAPI = plugin.penAPI;
- if (penAPI && penAPI.pointerType > 0) {
- return penAPI.pressure;
+Editor = (function(_super) {
+ __extends(Editor, _super);
+
+ function Editor() {
+ _ref = Editor.__super__.constructor.apply(this, arguments);
+ return _ref;
}
- return 1.0;
-};
-status = function(txt) {
- return $('#status-bar').text(txt);
-};
+ Editor.prototype.defaults = function() {
+ return {
+ doc: null,
+ tool: null,
+ preset: null,
+ renderer: null,
+ tiling: true,
+ targetValue: 1.0,
+ altkeyDown: false
+ };
+ };
-view = null;
+ Editor.prototype.initialize = function() {
+ this.toolObject = null;
+ this.on('change:tool', function() {
+ var tool;
+ this.setToolDirty();
+ tool = this.get('tool');
+ return toolsProperties.setTool(tool);
+ });
+ this.on('change:preset', function() {
+ var p;
+ p = this.get('preset');
+ return this.set('tool', p.tools[0]);
+ });
+ this.on('change:altkeyDown', function() {
+ var idx, p;
+ idx = this.get('altkeyDown') ? 1 : 0;
+ p = this.get('preset');
+ return this.set('tool', p.tools[idx]);
+ });
+ return this.on('change:renderer', function() {
+ this.get('view').reRender();
+ return this.get('view').rePaint();
+ });
+ };
-refresh = function() {
- view.reRender();
- return view.rePaint();
-};
+ Editor.prototype.createDoc = function(w, h) {
+ var doc;
+ doc = new Document(512, 512);
+ fillLayer(doc.layer, function(x, y) {
+ return -1;
+ });
+ this.set('doc', doc);
+ return this.set('view', new DocumentView($('.document-view'), doc));
+ };
+
+ Editor.prototype.getToolObject = function() {
+ var o;
+ if (this.get('toolObject') === null) {
+ console.log("Creating brush of type " + this.get("tool").description.name);
+ o = this.get('tool').createTool(this);
+ this.set('toolObject', o);
+ }
+ return this.get('toolObject');
+ };
+
+ Editor.prototype.setToolDirty = function() {
+ return this.set('toolObject', null);
+ };
+
+ Editor.prototype.refresh = function() {
+ var v;
+ v = this.get('view');
+ v.reRender();
+ return v.rePaint();
+ };
+
+ return Editor;
+
+})(Backbone.Model);
PropertyView = Backbone.View.extend({
className: "property",
initialize: function() {
- var $slider, $val, prop, step, tool;
+ var $input, $slider, conv, invconv, power, prop, rmax, rmin, step, tool;
tool = this.model.tool;
prop = this.model.prop;
$('<span/>').text(prop.name).appendTo(this.$el);
if (prop.range != null) {
- step = prop.type === 'int' ? 1 : (prop.range[1] - prop.range[0]) / 100;
+ power = prop.power || 1.0;
+ conv = function(v) {
+ return Math.pow(v, power);
+ };
+ invconv = function(v) {
+ return Math.pow(v, 1.0 / power);
+ };
+ rmin = invconv(prop.range[0]);
+ rmax = invconv(prop.range[1]);
+ step = prop.type === 'int' ? 1 : (rmax - rmin) / 100;
$slider = $('<div/>').slider({
- min: prop.range[0],
- max: prop.range[1],
- value: tool.get(prop.id),
+ min: rmin,
+ max: rmax,
+ value: invconv(tool.get(prop.id)),
step: step,
change: function(evt, ui) {
- tool.set(prop.id, ui.value);
+ tool.set(prop.id, conv(ui.value));
return editor.setToolDirty();
}
}).width(200).appendTo(this.$el);
- $val = $('<input/>').val(tool.get(prop.id)).appendTo(this.$el).change(function(evt) {
+ $input = $('<input/>').val(tool.get(prop.id)).appendTo(this.$el).change(function(evt) {
if (prop.type === 'int') {
- return tool.set(prop.id, parseInt($val.val()));
+ return tool.set(prop.id, parseInt($input.val()));
} else {
- return tool.set(prop.id, parseFloat($val.val()));
+ return tool.set(prop.id, parseFloat($input.val()));
}
});
return this.listenTo(this.model.tool, "change:" + prop.id, function() {
var v;
v = tool.get(prop.id);
- $val.val(v);
- return $slider.slider("value", v);
+ $input.val(v);
+ return $slider.slider("value", invconv(v));
});
}
}
});
PropertyPanel = (function() {
- PropertyPanel.prototype.views = [];
-
function PropertyPanel(selector) {
this.selector = selector;
+ this.views = [];
}
PropertyPanel.prototype.setTool = function(tool) {
- var self;
- self = this;
+ var _this = this;
this.removeViews();
return tool.properties.forEach(function(prop) {
var v;
@@ -344,8 +452,8 @@ PropertyPanel = (function() {
tool: tool
}
});
- $(self.selector).append(v.$el);
- return self.views.push(v);
+ $(_this.selector).append(v.$el);
+ return _this.views.push(v);
});
};
@@ -360,19 +468,27 @@ PropertyPanel = (function() {
})();
-toolsProperties = new PropertyPanel('#tools > .properties');
+getPenPressure = function() {
+ var penAPI, plugin;
+ plugin = document.getElementById('wtPlugin');
+ penAPI = plugin.penAPI;
+ if (penAPI && penAPI.pointerType > 0) {
+ return penAPI.pressure;
+ }
+ return 1.0;
+};
-editor.on('change:tool', function() {
- var tool;
- editor.setToolDirty();
- tool = editor.get('tool');
- return toolsProperties.setTool(tool);
-});
+status = function(txt) {
+ return $('#status-bar').text(txt);
+};
-editor.on('change:renderer', function() {
- view.reRender();
- return view.rePaint();
-});
+refresh = function() {
+ return editor.refresh();
+};
+
+editor = null;
+
+toolsProperties = null;
createToolsButtons = function($container) {
$container.empty();
@@ -421,7 +537,7 @@ createPalette = function($container) {
$slider = $('<div/>').slider({
min: -1.0,
max: 1.0,
- value: 0,
+ value: editor.get('targetValue'),
step: 0.005,
change: function(evt, ui) {
return editor.set('targetValue', ui.value);
@@ -456,19 +572,38 @@ loadGradient = function(name, url) {
loadGradient('g1', 'img/gradient-1.png');
+$(window).keydown(function(e) {
+ if (e.key === 'Control') {
+ return editor.set('altkeyDown', true);
+ }
+});
+
+$(window).keyup(function(e) {
+ if (e.key === 'Control') {
+ editor.set('altkeyDown', false);
+ }
+ if (e.ctrlKey) {
+ switch (e.keyCode) {
+ case 90:
+ editor.get('doc').undo();
+ return editor.refresh();
+ case 89:
+ editor.get('doc').redo();
+ return editor.refresh();
+ }
+ }
+});
+
$(document).ready(function() {
- var doc;
- doc = new Document(512, 512);
- fillLayer(doc.layer, function(x, y) {
- return -1;
- });
- view = new DocumentView($('.document-view'), doc);
+ toolsProperties = new PropertyPanel('#tools > .properties');
+ editor = new Editor();
+ editor.createDoc(512, 512);
createToolsButtons($('#tools > .buttons'));
createRenderersButtons($('#renderers > .buttons'));
createPalette($('#palette'));
createCommandsButtons($('#commands'));
- editor.set('doc', doc);
- editor.set('tool', RoundBrush);
- editor.set('renderer', GammaRenderer);
- return editor.set('targetValue', 0.0);
+ editor.set('preset', {
+ tools: [RoundBrush, Picker]
+ });
+ return editor.set('renderer', GammaRenderer);
});
View
90 js/core.coffee
@@ -23,7 +23,10 @@ class Vec2
return @x*@x+@y*@y
normalized: () ->
return @scale(1.0 / @length())
-
+ wrap: (w,h)->
+ return new Vec2(
+ (@x % w + w) % w,
+ (@y % h + h) % h)
class Vec3
constructor: (@x, @y, @z) ->;
@@ -61,6 +64,9 @@ class Rect
ret.extend(rect.bottomRight())
return ret
+ clone: ->
+ return new Rect(@x, @y, @width, @height)
+
offset: (vec)->
return new Rect(@x+vec.x, @y+vec.y, @width, @height)
@@ -107,20 +113,42 @@ class Layer
constructor: (@width, @height) ->
@data = new FloatBuffer(@width, @height)
- getRect: () ->
+ getRect: ->
return new Rect(0,0,@width,@height)
- getBuffer: () ->
+ getBuffer: ->
return @data.fbuffer
getAt: (pos)->
- ipos = pos.round()
+ ipos = pos.wrap(@width, @height).round()
return @data.fbuffer[ ipos.y * @width + ipos.x ]
getNormalAt: (pos)->
p = pos.round()
fb = @data.fbuffer
+ getCopy: (rect)->
+ srcData = @data.buffer
+ dstData = new ArrayBuffer(rect.width * rect.height * 4)
+ `
+ for(var iy=0; iy<rect.height; ++iy) {
+ var src = new Uint32Array(srcData, 4 * ((iy + rect.y) * this.width + rect.x), rect.width);
+ var dst = new Uint32Array(dstData, 4 * iy * rect.width, rect.width);
+ dst.set(src);
+ }`
+ return dstData
+
+ setData: (buffer, rect)->
+ dstData = @data.buffer
+ `
+ for(var iy=0; iy<rect.height; ++iy) {
+ var src = new Uint32Array(buffer, 4 * iy * rect.width, rect.width);
+ var dstOff = 4 * ((iy + rect.y) * this.width + rect.x);
+ var dst = new Uint32Array(dstData, dstOff, rect.width);
+ dst.set(src);
+ }`
+ return
+
Bezier =
quadratic: (pts, t)->
lerp = (a, b, t) ->
@@ -160,6 +188,7 @@ GammaRenderer = (()->
var offset = iy * width;
for(var ix=minX; ix<=maxX; ++ix) {
var fval = fb[offset + ix];
+ fval = fval > 1.0 ? 1.0 : (fval < -1.0 ? -1.0 : fval)
var val = Math.round(Math.pow((fval + 1.0) * 0.5, gamma) * 255.0);
destBuffer[offset + ix] =
(val) | (val << 8) | (val << 16) | 0xff000000;
@@ -307,30 +336,31 @@ genBlendFunc = (args, expression)->
}
}
})"
- #console.log("Generating blend function", str)
return eval(str)
-genBrushFunc = (args, brushExp, blendExp)->
- blendExp = blendExp
+genBrushFunc = (opts)->
+ blendExp = opts.blendExp
.replace(/{dst}/g, "dstData[dsti]")
.replace(/{src}/g, "_tmp")
- brushExp = brushExp
+ brushExp = opts.brushExp
.replace(/{out}/g, "_tmp")
- str = "
- (function (rect, dstFb, #{args}) {
- var sw = Math.round(rect.width);
- var sh = Math.round(rect.height);
- var invw = 2.0 / (rect.width - 1);
- var invh = 2.0 / (rect.height - 1);
- var offx = -(rect.x % 1.0) * invw - 1.0;
- var offy = -(rect.y % 1.0) * invh - 1.0;
- var fbw = dstFb.width;
- var fbh = dstFb.height;
+ str = "(function (rect, dstFb, #{opts.args}) {
+ var invw = 2.0 / (rect.width - 1);
+ var invh = 2.0 / (rect.height - 1);
+ var offx = -(rect.x % 1.0) * invw - 1.0;
+ var offy = -(rect.y % 1.0) * invh - 1.0;
+ var fbw = dstFb.width;
+ var fbh = dstFb.height;
+ var dstData = dstFb.getBuffer();"
+
+ str += if opts.tiling then "
var minx = Math.floor(rect.x) + fbw;
var miny = Math.floor(rect.y) + fbh;
- var dstData = dstFb.getBuffer();
+ var sw = Math.round(rect.width);
+ var sh = Math.round(rect.height);
+
for(var sy=0; sy<sh; ++sy) {
var y = sy * invh + offy;
for(var sx=0; sx<sw; ++sx) {
@@ -340,10 +370,26 @@ genBrushFunc = (args, brushExp, blendExp)->
#{brushExp};
#{blendExp};
}
- }
- })"
- return eval(str)
+ }"
+ else "
+ var minx = Math.floor(Math.max(0, -rect.x));
+ var miny = Math.floor(Math.max(0, -rect.y));
+ var sw = Math.round(Math.min(rect.width, fbw - rect.x));
+ var sh = Math.round(Math.min(rect.height, fbh - rect.y));
+ for(var sy=miny; sy<sh; ++sy) {
+ var dsti = (Math.floor(rect.y) + sy) * dstFb.width + Math.floor(rect.x) + minx;
+ var y = sy * invh + offy;
+ for(var sx=minx; sx<sw; ++sx) {
+ var x = sx * invw + offx;
+ var _tmp = 0.0;
+ #{brushExp};
+ #{blendExp};
+ ++dsti;
+ }
+ }"
+ str += "});"
+ return eval(str)
getRoundBrushFunc = (hardness) ->
hardnessPlus1 = hardness + 1.0
View
48 js/core.js
@@ -50,6 +50,10 @@ Vec2 = (function() {
return this.scale(1.0 / this.length());
};
+ Vec2.prototype.wrap = function(w, h) {
+ return new Vec2((this.x % w + w) % w, (this.y % h + h) % h);
+ };
+
return Vec2;
})();
@@ -122,6 +126,10 @@ Rect = (function() {
return ret;
};
+ Rect.prototype.clone = function() {
+ return new Rect(this.x, this.y, this.width, this.height);
+ };
+
Rect.prototype.offset = function(vec) {
return new Rect(this.x + vec.x, this.y + vec.y, this.width, this.height);
};
@@ -197,7 +205,7 @@ Layer = (function() {
Layer.prototype.getAt = function(pos) {
var ipos;
- ipos = pos.round();
+ ipos = pos.wrap(this.width, this.height).round();
return this.data.fbuffer[ipos.y * this.width + ipos.x];
};
@@ -207,6 +215,31 @@ Layer = (function() {
return fb = this.data.fbuffer;
};
+ Layer.prototype.getCopy = function(rect) {
+ var dstData, srcData;
+ srcData = this.data.buffer;
+ dstData = new ArrayBuffer(rect.width * rect.height * 4);
+
+ for(var iy=0; iy<rect.height; ++iy) {
+ var src = new Uint32Array(srcData, 4 * ((iy + rect.y) * this.width + rect.x), rect.width);
+ var dst = new Uint32Array(dstData, 4 * iy * rect.width, rect.width);
+ dst.set(src);
+ };
+ return dstData;
+ };
+
+ Layer.prototype.setData = function(buffer, rect) {
+ var dstData;
+ dstData = this.data.buffer;
+
+ for(var iy=0; iy<rect.height; ++iy) {
+ var src = new Uint32Array(buffer, 4 * iy * rect.width, rect.width);
+ var dstOff = 4 * ((iy + rect.y) * this.width + rect.x);
+ var dst = new Uint32Array(dstData, dstOff, rect.width);
+ dst.set(src);
+ };
+ };
+
return Layer;
})();
@@ -257,6 +290,7 @@ GammaRenderer = (function() {
var offset = iy * width;
for(var ix=minX; ix<=maxX; ++ix) {
var fval = fb[offset + ix];
+ fval = fval > 1.0 ? 1.0 : (fval < -1.0 ? -1.0 : fval)
var val = Math.round(Math.pow((fval + 1.0) * 0.5, gamma) * 255.0);
destBuffer[offset + ix] =
(val) | (val << 8) | (val << 16) | 0xff000000;
@@ -367,11 +401,13 @@ genBlendFunc = function(args, expression) {
return eval(str);
};
-genBrushFunc = function(args, brushExp, blendExp) {
- var str;
- blendExp = blendExp.replace(/{dst}/g, "dstData[dsti]").replace(/{src}/g, "_tmp");
- brushExp = brushExp.replace(/{out}/g, "_tmp");
- str = " (function (rect, dstFb, " + args + ") { var sw = Math.round(rect.width); var sh = Math.round(rect.height); var invw = 2.0 / (rect.width - 1); var invh = 2.0 / (rect.height - 1); var offx = -(rect.x % 1.0) * invw - 1.0; var offy = -(rect.y % 1.0) * invh - 1.0; var fbw = dstFb.width; var fbh = dstFb.height; var minx = Math.floor(rect.x) + fbw; var miny = Math.floor(rect.y) + fbh; var dstData = dstFb.getBuffer(); for(var sy=0; sy<sh; ++sy) { var y = sy * invh + offy; for(var sx=0; sx<sw; ++sx) { var x = sx * invw + offx; var dsti = ((sy + miny) % fbh) * fbw + ((sx + minx) % fbw); var _tmp = 0.0; " + brushExp + "; " + blendExp + "; } } })";
+genBrushFunc = function(opts) {
+ var blendExp, brushExp, str;
+ blendExp = opts.blendExp.replace(/{dst}/g, "dstData[dsti]").replace(/{src}/g, "_tmp");
+ brushExp = opts.brushExp.replace(/{out}/g, "_tmp");
+ str = "(function (rect, dstFb, " + opts.args + ") { var invw = 2.0 / (rect.width - 1); var invh = 2.0 / (rect.height - 1); var offx = -(rect.x % 1.0) * invw - 1.0; var offy = -(rect.y % 1.0) * invh - 1.0; var fbw = dstFb.width; var fbh = dstFb.height; var dstData = dstFb.getBuffer();";
+ str += opts.tiling ? " var minx = Math.floor(rect.x) + fbw; var miny = Math.floor(rect.y) + fbh; var sw = Math.round(rect.width); var sh = Math.round(rect.height); for(var sy=0; sy<sh; ++sy) { var y = sy * invh + offy; for(var sx=0; sx<sw; ++sx) { var x = sx * invw + offx; var dsti = ((sy + miny) % fbh) * fbw + ((sx + minx) % fbw); var _tmp = 0.0; " + brushExp + "; " + blendExp + "; } }" : " var minx = Math.floor(Math.max(0, -rect.x)); var miny = Math.floor(Math.max(0, -rect.y)); var sw = Math.round(Math.min(rect.width, fbw - rect.x)); var sh = Math.round(Math.min(rect.height, fbh - rect.y)); for(var sy=miny; sy<sh; ++sy) { var dsti = (Math.floor(rect.y) + sy) * dstFb.width + Math.floor(rect.x) + minx; var y = sy * invh + offy; for(var sx=minx; sx<sw; ++sx) { var x = sx * invw + offx; var _tmp = 0.0; " + brushExp + "; " + blendExp + "; ++dsti; } }";
+ str += "});";
return eval(str);
};
View
27 js/tools.coffee
@@ -5,15 +5,19 @@ class StepBrush
accumulator: 0.0
stepSize: 4.0
nsteps: 0
+ tiling: false
drawStep: (layer, pos, intensity, rect)->
fb = layer.getBuffer()
fb[ Math.floor(pos.x) + Math.floor(pos.y) * layer.width ] = intensity
rect.extend(pos)
+ mod = (val, size)-> (val % size + size) % size
+
move: (pos, pressure) ->;
draw: (layer, pos, pressure) ->
- rect = new Rect(pos.x, pos.y, 1, 1)
+ wpos = if @tiling then pos.wrap(layer.width, layer.height) else pos
+ rect = new Rect(wpos.x, wpos.y, 1, 1)
intensity = pressure
if @lastpos?
delt = pos.sub(@lastpos)
@@ -21,12 +25,15 @@ class StepBrush
dir = delt.scale(1.0 / length)
while(@accumulator + @stepSize <= length)
@accumulator += @stepSize
- pt = @lastpos.add(dir.scale(@accumulator))
+ pt = @lastpos
+ .add(dir.scale(@accumulator))
+ if @tiling
+ pt = pt.wrap(layer.width, layer.height)
@drawStep(layer, pt, intensity, rect)
++@nsteps
@accumulator -= length
else
- @drawStep(layer, pos, intensity, rect)
+ @drawStep(layer, wpos, intensity, rect)
++@nsteps
@lastpos = pos
@@ -114,6 +121,7 @@ RoundBrush = (()->
name: "Intensity"
defaultValue: 1.0
range: [0.0, 1.0]
+ power: 2.0
}
]
@@ -122,21 +130,24 @@ RoundBrush = (()->
createTool = (env)->
sb = new StepBrush()
sb.stepSize = self.get('stepSize')
+ sb.tiling = env.get('tiling')
size = self.get('size')
hardness = Math.pow(self.get('hardness'), 2.0) * 8.0;
hardnessPlus1 = hardness + 1.0
- func = genBrushFunc("intensity, target, h, hp1",
- "var d = Math.min(1.0, Math.max(0.0, (Math.sqrt(x*x + y*y) * hp1 - h)));
- {out} = Math.cos(d * Math.PI) * 0.5 + 0.5;",
- BlendModes[self.get('blendMode')])
+ func = genBrushFunc {
+ args: "intensity, target, h, hp1"
+ tiling: env.get('tiling')
+ blendExp: BlendModes[self.get('blendMode')]
+ brushExp: "var d = Math.min(1.0, Math.max(0.0, (Math.sqrt(x*x + y*y) * hp1 - h)));
+ {out} = Math.cos(d * Math.PI) * 0.5 + 0.5;"
+ }
sb.drawStep = (layer, pos, intensity, rect)->
r = new Rect(
pos.x - size * 0.5,
pos.y - size * 0.5,
size, size)
-
func(r, layer, intensity * self.get('intensity'), env.get('targetValue'), hardness, hardnessPlus1)
rect.extend(r.round())
return sb
View
29 js/tools.js
@@ -2,6 +2,8 @@
var BlendModes, Flatten, Picker, RoundBrush, StepBrush;
StepBrush = (function() {
+ var mod;
+
function StepBrush() {}
StepBrush.prototype.drawing = false;
@@ -14,6 +16,8 @@ StepBrush = (function() {
StepBrush.prototype.nsteps = 0;
+ StepBrush.prototype.tiling = false;
+
StepBrush.prototype.drawStep = function(layer, pos, intensity, rect) {
var fb;
fb = layer.getBuffer();
@@ -21,11 +25,16 @@ StepBrush = (function() {
return rect.extend(pos);
};
+ mod = function(val, size) {
+ return (val % size + size) % size;
+ };
+
StepBrush.prototype.move = function(pos, pressure) {};
StepBrush.prototype.draw = function(layer, pos, pressure) {
- var delt, dir, intensity, length, pt, rect;
- rect = new Rect(pos.x, pos.y, 1, 1);
+ var delt, dir, intensity, length, pt, rect, wpos;
+ wpos = this.tiling ? pos.wrap(layer.width, layer.height) : pos;
+ rect = new Rect(wpos.x, wpos.y, 1, 1);
intensity = pressure;
if (this.lastpos != null) {
delt = pos.sub(this.lastpos);
@@ -34,12 +43,15 @@ StepBrush = (function() {
while (this.accumulator + this.stepSize <= length) {
this.accumulator += this.stepSize;
pt = this.lastpos.add(dir.scale(this.accumulator));
+ if (this.tiling) {
+ pt = pt.wrap(layer.width, layer.height);
+ }
this.drawStep(layer, pt, intensity, rect);
++this.nsteps;
}
this.accumulator -= length;
} else {
- this.drawStep(layer, pos, intensity, rect);
+ this.drawStep(layer, wpos, intensity, rect);
++this.nsteps;
}
this.lastpos = pos;
@@ -140,7 +152,8 @@ RoundBrush = (function() {
id: 'intensity',
name: "Intensity",
defaultValue: 1.0,
- range: [0.0, 1.0]
+ range: [0.0, 1.0],
+ power: 2.0
}
];
self = new Backbone.Model;
@@ -148,10 +161,16 @@ RoundBrush = (function() {
var func, hardness, hardnessPlus1, sb, size;
sb = new StepBrush();
sb.stepSize = self.get('stepSize');
+ sb.tiling = env.get('tiling');
size = self.get('size');
hardness = Math.pow(self.get('hardness'), 2.0) * 8.0;
hardnessPlus1 = hardness + 1.0;
- func = genBrushFunc("intensity, target, h, hp1", "var d = Math.min(1.0, Math.max(0.0, (Math.sqrt(x*x + y*y) * hp1 - h))); {out} = Math.cos(d * Math.PI) * 0.5 + 0.5;", BlendModes[self.get('blendMode')]);
+ func = genBrushFunc({
+ args: "intensity, target, h, hp1",
+ tiling: env.get('tiling'),
+ blendExp: BlendModes[self.get('blendMode')],
+ brushExp: "var d = Math.min(1.0, Math.max(0.0, (Math.sqrt(x*x + y*y) * hp1 - h))); {out} = Math.cos(d * Math.PI) * 0.5 + 0.5;"
+ });
sb.drawStep = function(layer, pos, intensity, rect) {
var r;
r = new Rect(pos.x - size * 0.5, pos.y - size * 0.5, size, size);
View
1,571 js/vendor/backbone.js
@@ -0,0 +1,1571 @@
+// Backbone.js 1.0.0
+
+// (c) 2010-2013 Jeremy Ashkenas, DocumentCloud Inc.
+// Backbone may be freely distributed under the MIT license.
+// For all details and documentation:
+// http://backbonejs.org
+
+(function(){
+
+ // Initial Setup
+ // -------------
+
+ // Save a reference to the global object (`window` in the browser, `exports`
+ // on the server).
+ var root = this;
+
+ // Save the previous value of the `Backbone` variable, so that it can be
+ // restored later on, if `noConflict` is used.
+ var previousBackbone = root.Backbone;
+
+ // Create local references to array methods we'll want to use later.
+ var array = [];
+ var push = array.push;
+ var slice = array.slice;
+ var splice = array.splice;
+
+ // The top-level namespace. All public Backbone classes and modules will
+ // be attached to this. Exported for both the browser and the server.
+ var Backbone;
+ if (typeof exports !== 'undefined') {
+ Backbone = exports;
+ } else {
+ Backbone = root.Backbone = {};
+ }
+
+ // Current version of the library. Keep in sync with `package.json`.
+ Backbone.VERSION = '1.0.0';
+
+ // Require Underscore, if we're on the server, and it's not already present.
+ var _ = root._;
+ if (!_ && (typeof require !== 'undefined')) _ = require('underscore');
+
+ // For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns
+ // the `$` variable.
+ Backbone.$ = root.jQuery || root.Zepto || root.ender || root.$;
+
+ // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable
+ // to its previous owner. Returns a reference to this Backbone object.
+ Backbone.noConflict = function() {
+ root.Backbone = previousBackbone;
+ return this;
+ };
+
+ // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option
+ // will fake `"PUT"` and `"DELETE"` requests via the `_method` parameter and
+ // set a `X-Http-Method-Override` header.
+ Backbone.emulateHTTP = false;
+
+ // Turn on `emulateJSON` to support legacy servers that can't deal with direct
+ // `application/json` requests ... will encode the body as
+ // `application/x-www-form-urlencoded` instead and will send the model in a
+ // form param named `model`.
+ Backbone.emulateJSON = false;
+
+ // Backbone.Events
+ // ---------------
+
+ // A module that can be mixed in to *any object* in order to provide it with
+ // custom events. You may bind with `on` or remove with `off` callback
+ // functions to an event; `trigger`-ing an event fires all callbacks in
+ // succession.
+ //
+ // var object = {};
+ // _.extend(object, Backbone.Events);
+ // object.on('expand', function(){ alert('expanded'); });
+ // object.trigger('expand');
+ //
+ var Events = Backbone.Events = {
+
+ // Bind an event to a `callback` function. Passing `"all"` will bind
+ // the callback to all events fired.
+ on: function(name, callback, context) {
+ if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this;
+ this._events || (this._events = {});
+ var events = this._events[name] || (this._events[name] = []);
+ events.push({callback: callback, context: context, ctx: context || this});
+ return this;
+ },
+
+ // Bind an event to only be triggered a single time. After the first time
+ // the callback is invoked, it will be removed.
+ once: function(name, callback, context) {
+ if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this;
+ var self = this;
+ var once = _.once(function() {
+ self.off(name, once);
+ callback.apply(this, arguments);
+ });
+ once._callback = callback;
+ return this.on(name, once, context);
+ },
+
+ // Remove one or many callbacks. If `context` is null, removes all
+ // callbacks with that function. If `callback` is null, removes all
+ // callbacks for the event. If `name` is null, removes all bound
+ // callbacks for all events.
+ off: function(name, callback, context) {
+ var retain, ev, events, names, i, l, j, k;
+ if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this;
+ if (!name && !callback && !context) {
+ this._events = {};
+ return this;
+ }
+
+ names = name ? [name] : _.keys(this._events);
+ for (i = 0, l = names.length; i < l; i++) {
+ name = names[i];
+ if (events = this._events[name]) {
+ this._events[name] = retain = [];
+ if (callback || context) {
+ for (j = 0, k = events.length; j < k; j++) {
+ ev = events[j];
+ if ((callback && callback !== ev.callback && callback !== ev.callback._callback) ||
+ (context && context !== ev.context)) {
+ retain.push(ev);
+ }
+ }
+ }
+ if (!retain.length) delete this._events[name];
+ }
+ }
+
+ return this;
+ },
+
+ // Trigger one or many events, firing all bound callbacks. Callbacks are
+ // passed the same arguments as `trigger` is, apart from the event name
+ // (unless you're listening on `"all"`, which will cause your callback to
+ // receive the true name of the event as the first argument).
+ trigger: function(name) {
+ if (!this._events) return this;
+ var args = slice.call(arguments, 1);
+ if (!eventsApi(this, 'trigger', name, args)) return this;
+ var events = this._events[name];
+ var allEvents = this._events.all;
+ if (events) triggerEvents(events, args);
+ if (allEvents) triggerEvents(allEvents, arguments);
+ return this;
+ },
+
+ // Tell this object to stop listening to either specific events ... or
+ // to every object it's currently listening to.
+ stopListening: function(obj, name, callback) {
+ var listeners = this._listeners;
+ if (!listeners) return this;
+ var deleteListener = !name && !callback;
+ if (typeof name === 'object') callback = this;
+ if (obj) (listeners = {})[obj._listenerId] = obj;
+ for (var id in listeners) {
+ listeners[id].off(name, callback, this);
+ if (deleteListener) delete this._listeners[id];
+ }
+ return this;
+ }
+
+ };
+
+ // Regular expression used to split event strings.
+ var eventSplitter = /\s+/;
+
+ // Implement fancy features of the Events API such as multiple event
+ // names `"change blur"` and jQuery-style event maps `{change: action}`
+ // in terms of the existing API.
+ var eventsApi = function(obj, action, name, rest) {
+ if (!name) return true;
+
+ // Handle event maps.
+ if (typeof name === 'object') {
+ for (var key in name) {
+ obj[action].apply(obj, [key, name[key]].concat(rest));
+ }
+ return false;
+ }
+
+ // Handle space separated event names.
+ if (eventSplitter.test(name)) {
+ var names = name.split(eventSplitter);
+ for (var i = 0, l = names.length; i < l; i++) {
+ obj[action].apply(obj, [names[i]].concat(rest));
+ }
+ return false;
+ }
+
+ return true;
+ };
+
+ // A difficult-to-believe, but optimized internal dispatch function for
+ // triggering events. Tries to keep the usual cases speedy (most internal
+ // Backbone events have 3 arguments).
+ var triggerEvents = function(events, args) {
+ var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2];
+ switch (args.length) {
+ case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return;
+ case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return;
+ case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return;
+ case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return;
+ default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args);
+ }
+ };
+
+ var listenMethods = {listenTo: 'on', listenToOnce: 'once'};
+
+ // Inversion-of-control versions of `on` and `once`. Tell *this* object to
+ // listen to an event in another object ... keeping track of what it's
+ // listening to.
+ _.each(listenMethods, function(implementation, method) {
+ Events[method] = function(obj, name, callback) {
+ var listeners = this._listeners || (this._listeners = {});
+ var id = obj._listenerId || (obj._listenerId = _.uniqueId('l'));
+ listeners[id] = obj;
+ if (typeof name === 'object') callback = this;
+ obj[implementation](name, callback, this);
+ return this;
+ };
+ });
+
+ // Aliases for backwards compatibility.
+ Events.bind = Events.on;
+ Events.unbind = Events.off;
+
+ // Allow the `Backbone` object to serve as a global event bus, for folks who
+ // want global "pubsub" in a convenient place.
+ _.extend(Backbone, Events);
+
+ // Backbone.Model
+ // --------------
+
+ // Backbone **Models** are the basic data object in the framework --
+ // frequently representing a row in a table in a database on your server.
+ // A discrete chunk of data and a bunch of useful, related methods for
+ // performing computations and transformations on that data.
+
+ // Create a new model with the specified attributes. A client id (`cid`)
+ // is automatically generated and assigned for you.
+ var Model = Backbone.Model = function(attributes, options) {
+ var defaults;
+ var attrs = attributes || {};
+ options || (options = {});
+ this.cid = _.uniqueId('c');
+ this.attributes = {};
+ _.extend(this, _.pick(options, modelOptions));
+ if (options.parse) attrs = this.parse(attrs, options) || {};
+ if (defaults = _.result(this, 'defaults')) {
+ attrs = _.defaults({}, attrs, defaults);
+ }
+ this.set(attrs, options);
+ this.changed = {};
+ this.initialize.apply(this, arguments);
+ };
+
+ // A list of options to be attached directly to the model, if provided.
+ var modelOptions = ['url', 'urlRoot', 'collection'];
+
+ // Attach all inheritable methods to the Model prototype.
+ _.extend(Model.prototype, Events, {
+
+ // A hash of attributes whose current and previous value differ.
+ changed: null,
+
+ // The value returned during the last failed validation.
+ validationError: null,
+
+ // The default name for the JSON `id` attribute is `"id"`. MongoDB and
+ // CouchDB users may want to set this to `"_id"`.
+ idAttribute: 'id',
+
+ // Initialize is an empty function by default. Override it with your own
+ // initialization logic.
+ initialize: function(){},
+
+ // Return a copy of the model's `attributes` object.
+ toJSON: function(options) {
+ return _.clone(this.attributes);
+ },
+
+ // Proxy `Backbone.sync` by default -- but override this if you need
+ // custom syncing semantics for *this* particular model.
+ sync: function() {
+ return Backbone.sync.apply(this, arguments);
+ },
+
+ // Get the value of an attribute.
+ get: function(attr) {
+ return this.attributes[attr];
+ },
+
+ // Get the HTML-escaped value of an attribute.
+ escape: function(attr) {
+ return _.escape(this.get(attr));
+ },
+
+ // Returns `true` if the attribute contains a value that is not null
+ // or undefined.
+ has: function(attr) {
+ return this.get(attr) != null;
+ },
+
+ // Set a hash of model attributes on the object, firing `"change"`. This is
+ // the core primitive operation of a model, updating the data and notifying
+ // anyone who needs to know about the change in state. The heart of the beast.
+ set: function(key, val, options) {
+ var attr, attrs, unset, changes, silent, changing, prev, current;
+ if (key == null) return this;
+
+ // Handle both `"key", value` and `{key: value}` -style arguments.
+ if (typeof key === 'object') {
+ attrs = key;
+ options = val;
+ } else {
+ (attrs = {})[key] = val;
+ }
+
+ options || (options = {});
+
+ // Run validation.
+ if (!this._validate(attrs, options)) return false;
+
+ // Extract attributes and options.
+ unset = options.unset;
+ silent = options.silent;
+ changes = [];
+ changing = this._changing;
+ this._changing = true;
+
+ if (!changing) {
+ this._previousAttributes = _.clone(this.attributes);
+ this.changed = {};
+ }
+ current = this.attributes, prev = this._previousAttributes;
+
+ // Check for changes of `id`.
+ if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];
+
+ // For each `set` attribute, update or delete the current value.
+ for (attr in attrs) {
+ val = attrs[attr];
+ if (!_.isEqual(current[attr], val)) changes.push(attr);
+ if (!_.isEqual(prev[attr], val)) {
+ this.changed[attr] = val;
+ } else {
+ delete this.changed[attr];
+ }
+ unset ? delete current[attr] : current[attr] = val;
+ }
+
+ // Trigger all relevant attribute changes.
+ if (!silent) {
+ if (changes.length) this._pending = true;
+ for (var i = 0, l = changes.length; i < l; i++) {
+ this.trigger('change:' + changes[i], this, current[changes[i]], options);
+ }
+ }
+
+ // You might be wondering why there's a `while` loop here. Changes can
+ // be recursively nested within `"change"` events.
+ if (changing) return this;
+ if (!silent) {
+ while (this._pending) {
+ this._pending = false;
+ this.trigger('change', this, options);
+ }
+ }
+ this._pending = false;
+ this._changing = false;
+ return this;
+ },
+
+ // Remove an attribute from the model, firing `"change"`. `unset` is a noop
+ // if the attribute doesn't exist.
+ unset: function(attr, options) {
+ return this.set(attr, void 0, _.extend({}, options, {unset: true}));
+ },
+
+ // Clear all attributes on the model, firing `"change"`.
+ clear: function(options) {
+ var attrs = {};
+ for (var key in this.attributes) attrs[key] = void 0;
+ return this.set(attrs, _.extend({}, options, {unset: true}));
+ },
+
+ // Determine if the model has changed since the last `"change"` event.
+ // If you specify an attribute name, determine if that attribute has changed.
+ hasChanged: function(attr) {
+ if (attr == null) return !_.isEmpty(this.changed);
+ return _.has(this.changed, attr);
+ },
+
+ // Return an object containing all the attributes that have changed, or
+ // false if there are no changed attributes. Useful for determining what
+ // parts of a view need to be updated and/or what attributes need to be
+ // persisted to the server. Unset attributes will be set to undefined.
+ // You can also pass an attributes object to diff against the model,
+ // determining if there *would be* a change.
+ changedAttributes: function(diff) {
+ if (!diff) return this.hasChanged() ? _.clone(this.changed) : false;
+ var val, changed = false;
+ var old = this._changing ? this._previousAttributes : this.attributes;
+ for (var attr in diff) {
+ if (_.isEqual(old[attr], (val = diff[attr]))) continue;
+ (changed || (changed = {}))[attr] = val;
+ }
+ return changed;
+ },
+
+ // Get the previous value of an attribute, recorded at the time the last
+ // `"change"` event was fired.
+ previous: function(attr) {
+ if (attr == null || !this._previousAttributes) return null;
+ return this._previousAttributes[attr];
+ },
+
+ // Get all of the attributes of the model at the time of the previous
+ // `"change"` event.
+ previousAttributes: function() {
+ return _.clone(this._previousAttributes);
+ },
+
+ // Fetch the model from the server. If the server's representation of the
+ // model differs from its current attributes, they will be overridden,
+ // triggering a `"change"` event.
+ fetch: function(options) {
+ options = options ? _.clone(options) : {};
+ if (options.parse === void 0) options.parse = true;
+ var model = this;
+ var success = options.success;
+ options.success = function(resp) {
+ if (!model.set(model.parse(resp, options), options)) return false;
+ if (success) success(model, resp, options);
+ model.trigger('sync', model, resp, options);
+ };
+ wrapError(this, options);
+ return this.sync('read', this, options);
+ },
+
+ // Set a hash of model attributes, and sync the model to the server.
+ // If the server returns an attributes hash that differs, the model's
+ // state will be `set` again.
+ save: function(key, val, options) {
+ var attrs, method, xhr, attributes = this.attributes;
+
+ // Handle both `"key", value` and `{key: value}` -style arguments.
+ if (key == null || typeof key === 'object') {
+ attrs = key;
+ options = val;
+ } else {
+ (attrs = {})[key] = val;
+ }
+
+ // If we're not waiting and attributes exist, save acts as `set(attr).save(null, opts)`.
+ if (attrs && (!options || !options.wait) && !this.set(attrs, options)) return false;
+
+ options = _.extend({validate: true}, options);
+
+ // Do not persist invalid models.
+ if (!this._validate(attrs, options)) return false;
+
+ // Set temporary attributes if `{wait: true}`.
+ if (attrs && options.wait) {
+ this.attributes = _.extend({}, attributes, attrs);
+ }
+
+ // After a successful server-side save, the client is (optionally)
+ // updated with the server-side state.
+ if (options.parse === void 0) options.parse = true;
+ var model = this;
+ var success = options.success;
+ options.success = function(resp) {
+ // Ensure attributes are restored during synchronous saves.
+ model.attributes = attributes;
+ var serverAttrs = model.parse(resp, options);
+ if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs);
+ if (_.isObject(serverAttrs) && !model.set(serverAttrs, options)) {
+ return false;
+ }
+ if (success) success(model, resp, options);
+ model.trigger('sync', model, resp, options);
+ };
+ wrapError(this, options);
+
+ method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update');
+ if (method === 'patch') options.attrs = attrs;
+ xhr = this.sync(method, this, options);
+
+ // Restore attributes.
+ if (attrs && options.wait) this.attributes = attributes;
+
+ return xhr;
+ },
+
+ // Destroy this model on the server if it was already persisted.
+ // Optimistically removes the model from its collection, if it has one.
+ // If `wait: true` is passed, waits for the server to respond before removal.
+ destroy: function(options) {
+ options = options ? _.clone(options) : {};
+ var model = this;
+ var success = options.success;
+
+ var destroy = function() {
+ model.trigger('destroy', model, model.collection, options);
+ };
+
+ options.success = function(resp) {
+ if (options.wait || model.isNew()) destroy();
+ if (success) success(model, resp, options);
+ if (!model.isNew()) model.trigger('sync', model, resp, options);
+ };
+
+ if (this.isNew()) {
+ options.success();
+ return false;
+ }
+ wrapError(this, options);
+
+ var xhr = this.sync('delete', this, options);
+ if (!options.wait) destroy();
+ return xhr;
+ },
+
+ // Default URL for the model's representation on the server -- if you're
+ // using Backbone's restful methods, override this to change the endpoint
+ // that will be called.
+ url: function() {
+ var base = _.result(this, 'urlRoot') || _.result(this.collection, 'url') || urlError();
+ if (this.isNew()) return base;
+ return base + (base.charAt(base.length - 1) === '/' ? '' : '/') + encodeURIComponent(this.id);
+ },
+
+ // **parse** converts a response into the hash of attributes to be `set` on
+ // the model. The default implementation is just to pass the response along.
+ parse: function(resp, options) {
+ return resp;
+ },
+
+ // Create a new model with identical attributes to this one.
+ clone: function() {
+ return new this.constructor(this.attributes);
+ },
+
+ // A model is new if it has never been saved to the server, and lacks an id.
+ isNew: function() {
+ return this.id == null;
+ },
+
+ // Check if the model is currently in a valid state.
+ isValid: function(options) {
+ return this._validate({}, _.extend(options || {}, { validate: true }));
+ },
+
+ // Run validation against the next complete set of model attributes,
+ // returning `true` if all is well. Otherwise, fire an `"invalid"` event.
+ _validate: function(attrs, options) {
+ if (!options.validate || !this.validate) return true;
+ attrs = _.extend({}, this.attributes, attrs);
+ var error = this.validationError = this.validate(attrs, options) || null;
+ if (!error) return true;
+ this.trigger('invalid', this, error, _.extend(options || {}, {validationError: error}));
+ return false;
+ }
+
+ });
+
+ // Underscore methods that we want to implement on the Model.
+ var modelMethods = ['keys', 'values', 'pairs', 'invert', 'pick', 'omit'];
+
+ // Mix in each Underscore method as a proxy to `Model#attributes`.
+ _.each(modelMethods, function(method) {
+ Model.prototype[method] = function() {
+ var args = slice.call(arguments);
+ args.unshift(this.attributes);
+ return _[method].apply(_, args);
+ };
+ });
+
+ // Backbone.Collection
+ // -------------------
+
+ // If models tend to represent a single row of data, a Backbone Collection is
+ // more analagous to a table full of data ... or a small slice or page of that
+ // table, or a collection of rows that belong together for a particular reason
+ // -- all of the messages in this particular folder, all of the documents
+ // belonging to this particular author, and so on. Collections maintain
+ // indexes of their models, both in order, and for lookup by `id`.
+
+ // Create a new **Collection**, perhaps to contain a specific type of `model`.
+ // If a `comparator` is specified, the Collection will maintain
+ // its models in sort order, as they're added and removed.
+ var Collection = Backbone.Collection = function(models, options) {
+ options || (options = {});
+ if (options.url) this.url = options.url;
+ if (options.model) this.model = options.model;
+ if (options.comparator !== void 0) this.comparator = options.comparator;
+ this._reset();
+ this.initialize.apply(this, arguments);
+ if (models) this.reset(models, _.extend({silent: true}, options));
+ };
+
+ // Default options for `Collection#set`.
+ var setOptions = {add: true, remove: true, merge: true};
+ var addOptions = {add: true, merge: false, remove: false};
+
+ // Define the Collection's inheritable methods.
+ _.extend(Collection.prototype, Events, {
+
+ // The default model for a collection is just a **Backbone.Model**.
+ // This should be overridden in most cases.
+ model: Model,
+
+ // Initialize is an empty function by default. Override it with your own
+ // initialization logic.
+ initialize: function(){},
+
+ // The JSON representation of a Collection is an array of the
+ // models' attributes.
+ toJSON: function(options) {
+ return this.map(function(model){ return model.toJSON(options); });
+ },
+
+ // Proxy `Backbone.sync` by default.
+ sync: function() {
+ return Backbone.sync.apply(this, arguments);
+ },
+
+ // Add a model, or list of models to the set.
+ add: function(models, options) {
+ return this.set(models, _.defaults(options || {}, addOptions));
+ },
+
+ // Remove a model, or a list of models from the set.
+ remove: function(models, options) {
+ models = _.isArray(models) ? models.slice() : [models];
+ options || (options = {});
+ var i, l, index, model;
+ for (i = 0, l = models.length; i < l; i++) {
+ model = this.get(models[i]);
+ if (!model) continue;
+ delete this._byId[model.id];
+ delete this._byId[model.cid];
+ index = this.indexOf(model);
+ this.models.splice(index, 1);
+ this.length--;
+ if (!options.silent) {
+ options.index = index;
+ model.trigger('remove', model, this, options);
+ }
+ this._removeReference(model);
+ }
+ return this;
+ },
+
+ // Update a collection by `set`-ing a new list of models, adding new ones,
+ // removing models that are no longer present, and merging models that
+ // already exist in the collection, as necessary. Similar to **Model#set**,
+ // the core operation for updating the data contained by the collection.
+ set: function(models, options) {
+ options = _.defaults(options || {}, setOptions);
+ if (options.parse) models = this.parse(models, options);
+ if (!_.isArray(models)) models = models ? [models] : [];
+ var i, l, model, attrs, existing, sort;
+ var at = options.at;
+ var sortable = this.comparator && (at == null) && options.sort !== false;
+ var sortAttr = _.isString(this.comparator) ? this.comparator : null;
+ var toAdd = [], toRemove = [], modelMap = {};
+
+ // Turn bare objects into model references, and prevent invalid models
+ // from being added.
+ for (i = 0, l = models.length; i < l; i++) {
+ if (!(model = this._prepareModel(models[i], options))) continue;
+
+ // If a duplicate is found, prevent it from being added and
+ // optionally merge it into the existing model.
+ if (existing = this.get(model)) {
+ if (options.remove) modelMap[existing.cid] = true;
+ if (options.merge) {
+ existing.set(model.attributes, options);
+ if (sortable && !sort && existing.hasChanged(sortAttr)) sort = true;
+ }
+
+ // This is a new model, push it to the `toAdd` list.
+ } else if (options.add) {
+ toAdd.push(model);
+
+ // Listen to added models' events, and index models for lookup by
+ // `id` and by `cid`.
+ model.on('all', this._onModelEvent, this);
+ this._byId[model.cid] = model;
+ if (model.id != null) this._byId[model.id] = model;
+ }
+ }
+
+ // Remove nonexistent models if appropriate.
+ if (options.remove) {
+ for (i = 0, l = this.length; i < l; ++i) {
+ if (!modelMap[(model = this.models[i]).cid]) toRemove.push(model);
+ }
+ if (toRemove.length) this.remove(toRemove, options);
+ }
+
+ // See if sorting is needed, update `length` and splice in new models.
+ if (toAdd.length) {
+ if (sortable) sort = true;
+ this.length += toAdd.length;
+ if (at != null) {
+ splice.apply(this.models, [at, 0].concat(toAdd));
+ } else {
+ push.apply(this.models, toAdd);
+ }
+ }
+
+ // Silently sort the collection if appropriate.
+ if (sort) this.sort({silent: true});
+
+ if (options.silent) return this;
+
+ // Trigger `add` events.
+ for (i = 0, l = toAdd.length; i < l; i++) {
+ (model = toAdd[i]).trigger('add', model, this, options);
+ }
+
+ // Trigger `sort` if the collection was sorted.
+ if (sort) this.trigger('sort', this, options);
+ return this;
+ },
+
+ // When you have more items than you want to add or remove individually,
+ // you can reset the entire set with a new list of models, without firing
+ // any granular `add` or `remove` events. Fires `reset` when finished.
+ // Useful for bulk operations and optimizations.
+ reset: function(models, options) {
+ options || (options = {});
+ for (var i = 0, l = this.models.length; i < l; i++) {
+ this._removeReference(this.models[i]);
+ }
+ options.previousModels = this.models;
+ this._reset();
+ this.add(models, _.extend({silent: true}, options));
+ if (!options.silent) this.trigger('reset', this, options);
+ return this;
+ },
+
+ // Add a model to the end of the collection.
+ push: function(model, options) {
+ model = this._prepareModel(model, options);
+ this.add(model, _.extend({at: this.length}, options));
+ return model;
+ },
+
+ // Remove a model from the end of the collection.
+ pop: function(options) {
+ var model = this.at(this.length - 1);
+ this.remove(model, options);
+ return model;
+ },
+
+ // Add a model to the beginning of the collection.
+ unshift: function(model, options) {
+ model = this._prepareModel(model, options);
+ this.add(model, _.extend({at: 0}, options));
+ return model;
+ },
+
+ // Remove a model from the beginning of the collection.
+ shift: function(options) {
+ var model = this.at(0);
+ this.remove(model, options);
+ return model;
+ },
+
+ // Slice out a sub-array of models from the collection.
+ slice: function(begin, end) {
+ return this.models.slice(begin, end);
+ },
+
+ // Get a model from the set by id.
+ get: function(obj) {
+ if (obj == null) return void 0;
+ return this._byId[obj.id != null ? obj.id : obj.cid || obj];
+ },
+
+ // Get the model at the given index.
+ at: function(index) {
+ return this.models[index];
+ },
+
+ // Return models with matching attributes. Useful for simple cases of
+ // `filter`.
+ where: function(attrs, first) {
+ if (_.isEmpty(attrs)) return first ? void 0 : [];
+ return this[first ? 'find' : 'filter'](function(model) {
+ for (var key in attrs) {
+ if (attrs[key] !== model.get(key)) return false;
+ }
+ return true;
+ });
+ },
+
+ // Return the first model with matching attributes. Useful for simple cases
+ // of `find`.
+ findWhere: function(attrs) {
+ return this.where(attrs, true);
+ },
+
+ // Force the collection to re-sort itself. You don't need to call this under