Formatting fix

Formatting fix

# Abstract middleware stacks

    {EventEmitter} = require 'events'

    config = require 'config'
    pkgman = require 'pkgman'

    exports.Middleware = class Middleware extends EventEmitter

Implements a middleware stack. Middleware functions can be added to the stack
with `use`. Calling `dispatch` invokes the middleware functions serially.

Each middleware accepts an arbitrary parameters and finally a `next` function.
When a middleware finishes, it must call the `next` function. If there was an
error, it must be thrown or passed as the first argument to `next`. If no error
occurred, `next` must be invoked without arguments.

Error-handling middleware can also be defined. These middleware take an
additional parameter at the beginning of the function signature: `error`.
Error-handling middleware are only called if a previous middleware threw or
passed an error. Conversely, non-error-handling middleware are skipped if a
previous error occurred.

## *constructor*

*Create a middleware stack.*

      constructor: -> @_middleware = []

## Middlware#use

* (function) `fn` - A middleware function.

*Add a middleware function to the stack.*

      use: (fn) -> @_middleware.push fn

## Middleware#dispatch

* (mixed) `...` - One or more values to pass to the middleware.
* (function) `fn` - A function invoked when the middleware stack has
  finished. If an error occurred, it will be passed as the first
  argument.

*Invoke the middleware functions serially.*

      dispatch: (args..., fn) ->
        self = this

        index = 0

        invoke = (error) ->

          self.emit 'invoked', self._middleware[index - 1] if index > 0

Call `fn` with any error if we're done.

          return fn error if index is self._middleware.length

          current = self._middleware[index++]

Error-handling middleware.

          if current.length is args.length + 2

An error occurred previously.

            if error?

Try to invoke the middleware, if it throws, just catch the error and pass it
along.

              try
                localArgs = args.concat()
                localArgs.unshift error
                localArgs.push invoke
                self.emit 'invoking', current
                current localArgs...
              catch error
                invoke error

No previous error; skip this middleware.

            else

              invoke error

Non-error-handling middleware.

          else

An error occurred previously, skip this middleware.

            if error?

              invoke error

No previous error.

            else

Try to invoke the middleware, if it throws, just catch the error and pass it along.

              try
                localArgs = args.concat()
                localArgs.push invoke
                self.emit 'invoking', current
                current localArgs...
              catch error
                invoke error

Kick things off.

        invoke()

    debug = require('debug') 'shrub:middleware'
    debugSilly = require('debug') 'shrub-silly:middleware'

## middleware.fromHook

*Create a middleware stack from the results of a hook and path configuration.*

    exports.fromHook = (hook, paths, args...) ->

      middleware = new Middleware()

Invoke the hook and `use` the middleware in the paths configuration order.

      args.unshift hook
      hookResults = pkgman.invoke args...
      for path in paths ? []
        continue unless (spec = hookResults[path])?

        debugSilly "- - #{spec.label}"

        for fn in spec.middleware ? []
          fn.label = spec.label
          middleware.use fn, spec.label

      middleware.on 'invoking', (fn) -> debugSilly "Invoking #{fn.label}"
      middleware.on 'invoked', (fn) -> debugSilly "Invoked #{fn.label}"

      middleware

## middleware.fromShortName

*Create a middleware stack from a short name. e.g. "example thing hook".*

The short name is converted into log messages, a hook name, and configuration
key. In the case where we passed in "user before login", this would look
like:

```coffeescript
debug "Loading user before login middleware..."

middleware = exports.fromHook(
	"userBeforeLoginMiddleware"
	config.get "packageSettings:user:beforeLoginMiddleware"
)

debug "User before login middleware loaded."
```

###### TODO: This is bad and it should go away.

    exports.fromShortName = (shortName, packageName) ->

      i8n = require 'inflection'

      debugSilly "- Loading #{shortName} middleware..."

      [firstPart, keyParts...] = shortName.split ' '
      packageName ?= firstPart
      key = keyParts.join '_'

###### TODO: this really should be unified, making this unnecessary.

      configKey = if global? then 'packageSettings' else 'packageConfig'

      middleware = exports.fromHook(
        "#{firstPart}#{i8n.camelize key}Middleware"

        config.get "#{configKey}:#{packageName}:#{
          i8n.camelize key, true
        }Middleware"
      )

      debugSilly "- #{i8n.capitalize shortName} middleware loaded."

      middleware


Remove unused import

Remove unused import

    ObjectID    = require('mongodb').ObjectID
    stringify   = require('JSONStream').stringify

    Document    = require './model/Document'

    sentry      = require './db/sentry'
    mongo       = require './db/mongo'

## PARAM {collection}

    exports.param = (req, res, next, col) ->
      if col not in ['turer', 'steder', 'grupper', 'områder', 'bilder', 'arrangementer']
        return res.json 404, message: 'Objekttype ikke funnet'

      req.type = col
      req.db   = col: mongo[col]

      next()

## OPTIONS /{collection}

    exports.options = (req, res, next) ->
      res.setHeader 'Access-Control-Expose-Headers', [
        'ETag', 'Location', 'Last-Modified', 'Count-Return', 'Count-Total'
      ].join(', ')
      res.setHeader 'Access-Control-Max-Age', 86400
      res.setHeader 'Access-Control-Allow-Headers', 'Content-Type'
      res.setHeader 'Access-Control-Allow-Methods', 'HEAD, GET, POST'
      res.send 204

## HEAD /{collection}
## GET /{collection}

    exports.get = (req, res, next) ->
      query = {}

### ?tag=`String`

      if typeof req.query.tag is 'string' and req.query.tag isnt ''
        if req.query.tag.charAt(0) is '!' and req.query.tag.length > 1
          query['tags.0'] = $ne: req.query.tag.substr(1)
        else
          query['tags.0'] = req.query.tag

### ?grupper=`String`

      if typeof req.query.gruppe is 'string' and req.query.gruppe isnt ''
        query['grupper'] = req.query.gruppe

### ?after=`Mixed`

      if typeof req.query.after is 'string' and req.query.after isnt ''
        time = req.query.after

        if not isNaN time
          # Make unix timestamp into milliseconds
          time = time + '000' if (time + '').length is 10
          time = parseInt time

        time = new Date time

        if time.toString() isnt 'Invalid Date'
          query.endret = $gte: time.toISOString()

### ?bbox=`min_lng`,`min_lat`,`max_lng`,`max_lat`

      if typeof req.query.bbox is 'string' and req.query.bbox.split(',').length is 4
        bbox = req.query.bbox.split(',')
        bbox[i] = parseFloat(val) for val, i in bbox

        query.geojson =
          '$geoWithin':
            '$geometry':
              type: 'Polygon'
              coordinates: [[
                [bbox[0], bbox[1]]
                [bbox[2], bbox[1]]
                [bbox[2], bbox[3]]
                [bbox[0], bbox[3]]
                [bbox[0], bbox[1]]
              ]]

### ?privat.`String`=`String`

This allows the user to filter documents based on private document properties.
This will autumaticly limit returned documents to those owned by the current
user.

#### ToDo

 * Limit number of private fields?
 * Limit depth of private fields?

`NB` This section is looping through all of the url query parameters and hence
should take the queries from above sections into concideration so we don't need
to do double amount of work.

      for key, val of req.query when key.substr(0,7) is 'privat.'
        if /^[a-zæøåA-ZÆØÅ0-9_.]+$/.test key
          val = parseFloat(val) if not isNaN val # @TODO(starefossen) is this acceptable?
          query.tilbyder = req.usr
          query[key] = val

Limit queries to own documents or public documents i.e. where `doc.status` is
`Offentlig` if not `query.tilbyder` is set.

      query['$or'] = [{status: 'Offentlig'}, {tilbyder: req.usr}] if not query.tilbyder

Only project a few fields to since lists are mostly used intermediate before
fetching the entire document.

      fields = tilbyder: true, endret: true, status: true, navn: true, tags: true

Set up MongoDB options.

      options =
        limit: Math.min((parseInt(req.query.limit, 10) or 20), 50)
        skip: parseInt(req.query.skip, 10) or 0
        sort: 'endret'

Retrive matching documents from MongoDB.

      cursor = req.db.col.find(query, fields, options)
      cursor.count (err, total) ->
        return next err if err
        res.set 'Count-Return', Math.min(options.limit, total)
        res.set 'Count-Total', total
        return res.send 204 if req.method is 'HEAD'
        return res.json documents: [], count: 0, total: 0 if total is 0
        res.set 'Content-Type', 'application/json; charset=utf-8'

Calculate number of rows returned since we don't know that in advanced (due to
the nature of streaming).

        count = Math.min(options.limit, Math.max(total - options.skip, 0))

Stream documents user in order to prevent loading them into memory.

        op = '{"documents":['
        cl = '],"count":' + count + ',"total":' + total + '}'

        cursor.stream().pipe(stringify(op, ',', cl)).pipe(res)

## POST /{collection}

    exports.post = (req, res, next) ->
      return res.json 400, message: 'Body is missing' if Object.keys(req.body).length is 0
      return res.json 422, message: 'Body should be a JSON Hash' if req.body instanceof Array

      req.body.tilbyder = req.usr

      new Document(req.type, null).once('error', next).once 'ready', ->
        @insert req.body, (err, warn, data) ->
          if err
            return next(err) if err.name isnt 'ValidationError'

            sentry.captureDocumentError req, err

            return res.json 422,
              document: req.body
              message: 'Validation Failed'
              errors: err.details #TODO(starefossen) document this

          res.set 'ETag', "\"#{data.checksum}\""
          res.set 'Last-Modified', new Date(data.endret).toUTCString()
          # res.set 'Location', req.get 'host'

          return res.json 201,
            document: data
            message: 'Validation Warnings' if warn.length > 0
            warnings: warn if warn.length > 0

    ObjectID    = require('mongodb').ObjectID
    stringify   = require('JSONStream').stringify
    createHash  = require('crypto').createHash

    Document    = require './model/Document'

    sentry      = require './db/sentry'
    mongo       = require './db/mongo'

## PARAM {collection}

    exports.param = (req, res, next, col) ->
      if col not in ['turer', 'steder', 'grupper', 'områder', 'bilder', 'arrangementer']
        return res.json 404, message: 'Objekttype ikke funnet'

      req.type = col
      req.db   = col: mongo[col]

      next()

## OPTIONS /{collection}

    exports.options = (req, res, next) ->
      res.setHeader 'Access-Control-Expose-Headers', [
        'ETag', 'Location', 'Last-Modified', 'Count-Return', 'Count-Total'
      ].join(', ')
      res.setHeader 'Access-Control-Max-Age', 86400
      res.setHeader 'Access-Control-Allow-Headers', 'Content-Type'
      res.setHeader 'Access-Control-Allow-Methods', 'HEAD, GET, POST'
      res.send 204

## HEAD /{collection}
## GET /{collection}

    exports.get = (req, res, next) ->
      query = {}

### ?tag=`String`

      if typeof req.query.tag is 'string' and req.query.tag isnt ''
        if req.query.tag.charAt(0) is '!' and req.query.tag.length > 1
          query['tags.0'] = $ne: req.query.tag.substr(1)
        else
          query['tags.0'] = req.query.tag

### ?grupper=`String`

      if typeof req.query.gruppe is 'string' and req.query.gruppe isnt ''
        query['grupper'] = req.query.gruppe

### ?after=`Mixed`

      if typeof req.query.after is 'string' and req.query.after isnt ''
        time = req.query.after

        if not isNaN time
          # Make unix timestamp into milliseconds
          time = time + '000' if (time + '').length is 10
          time = parseInt time

        time = new Date time

        if time.toString() isnt 'Invalid Date'
          query.endret = $gte: time.toISOString()

### ?bbox=`min_lng`,`min_lat`,`max_lng`,`max_lat`

      if typeof req.query.bbox is 'string' and req.query.bbox.split(',').length is 4
        bbox = req.query.bbox.split(',')
        bbox[i] = parseFloat(val) for val, i in bbox

        query.geojson =
          '$geoWithin':
            '$geometry':
              type: 'Polygon'
              coordinates: [[
                [bbox[0], bbox[1]]
                [bbox[2], bbox[1]]
                [bbox[2], bbox[3]]
                [bbox[0], bbox[3]]
                [bbox[0], bbox[1]]
              ]]

### ?privat.`String`=`String`

This allows the user to filter documents based on private document properties.
This will autumaticly limit returned documents to those owned by the current
user.

#### ToDo

 * Limit number of private fields?
 * Limit depth of private fields?

`NB` This section is looping through all of the url query parameters and hence
should take the queries from above sections into concideration so we don't need
to do double amount of work.

      for key, val of req.query when key.substr(0,7) is 'privat.'
        if /^[a-zæøåA-ZÆØÅ0-9_.]+$/.test key
          val = parseFloat(val) if not isNaN val # @TODO(starefossen) is this acceptable?
          query.tilbyder = req.usr
          query[key] = val

Limit queries to own documents or public documents i.e. where `doc.status` is
`Offentlig` if not `query.tilbyder` is set.

      query['$or'] = [{status: 'Offentlig'}, {tilbyder: req.usr}] if not query.tilbyder

Only project a few fields to since lists are mostly used intermediate before
fetching the entire document.

      fields = tilbyder: true, endret: true, status: true, navn: true, tags: true

Set up MongoDB options.

      options =
        limit: Math.min((parseInt(req.query.limit, 10) or 20), 50)
        skip: parseInt(req.query.skip, 10) or 0
        sort: 'endret'

Retrive matching documents from MongoDB.

      cursor = req.db.col.find(query, fields, options)
      cursor.count (err, total) ->
        return next err if err
        res.set 'Count-Return', Math.min(options.limit, total)
        res.set 'Count-Total', total
        return res.send 204 if req.method is 'HEAD'
        return res.json documents: [], count: 0, total: 0 if total is 0
        res.set 'Content-Type', 'application/json; charset=utf-8'

Calculate number of rows returned since we don't know that in advanced (due to
the nature of streaming).

        count = Math.min(options.limit, Math.max(total - options.skip, 0))

Stream documents user in order to prevent loading them into memory.

        op = '{"documents":['
        cl = '],"count":' + count + ',"total":' + total + '}'

        cursor.stream().pipe(stringify(op, ',', cl)).pipe(res)

## POST /{collection}

    exports.post = (req, res, next) ->
      return res.json 400, message: 'Body is missing' if Object.keys(req.body).length is 0
      return res.json 422, message: 'Body should be a JSON Hash' if req.body instanceof Array

      req.body.tilbyder = req.usr

      new Document(req.type, null).once('error', next).once 'ready', ->
        @insert req.body, (err, warn, data) ->
          if err
            return next(err) if err.name isnt 'ValidationError'

            sentry.captureDocumentError req, err

            return res.json 422,
              document: req.body
              message: 'Validation Failed'
              errors: err.details #TODO(starefossen) document this

          res.set 'ETag', "\"#{data.checksum}\""
          res.set 'Last-Modified', new Date(data.endret).toUTCString()
          # res.set 'Location', req.get 'host'

          return res.json 201,
            document: data
            message: 'Validation Warnings' if warn.length > 0
            warnings: warn if warn.length > 0


support fenced code blocks with syntax highlight in markdown

# The build script

This is a very simple build script that puts together the YAML + JADE page files
and the pure JADE template files. It also builds the blog index.

Load modules

    fs = require 'fs'
    mkdirp = require('mkdirp').sync;
    jade = require 'jade'
    yaml = require 'js-yaml'
    config = require './config'

### Markdown

Add custom markdown parser
with custom code parsing function
that highlights with Pygments

**note**: We are overriding `renderer.code`
instead of `renderer.options.highlight`
because it wraps the highlihter result in unnecessary `<pre><code>`.

**note**: Since Jade doesn't support async filters,
we have to use `child_process.execSync`.
This requires Node >= 0.11.12

Further reading:
- [Marked overriding-renderer-methods](https://www.npmjs.com/package/marked#overriding-renderer-methods)
- [Node child_process.execSync](http://nodejs.org/docs/v0.12.0/api/child_process.html#child_process_child_process_execsync_command_options)
- [Jade How to define/install custom filter?](https://github.com/jadejs/jade/issues/1055)
- [Pygments lexers](http://pygments.org/docs/lexers/)

    execSync = (require 'child_process').execSync
    marked = require 'marked'

    renderer = new marked.Renderer
    renderer.code = (code, lexer = 'text') ->
        result = execSync "pygmentize -l #{lexer} -f html",
            input: code
        return result.toString()

    marked.setOptions
        renderer: renderer

    jade.filters.markdown = marked

### Template loader

Templates are different from pages in that they don't have a YAML front matter.
They are written in clean jade and can extend and include other templates.

    class Template
        constructor: (@name = 'page', @location = config.templatesPath) ->
        getHtml: (options) ->
            cwd = process.cwd()
            options.pretty = config.pretty
            options.filename = @name
            try
                process.chdir @location
                content = fs.readFileSync "#{@name}.jade", 'utf8'
                @html = jade.render content, options
            catch error
                console.log error
            finally
                process.chdir cwd
            return @html

## Page loader

    class Page

A nice /regexp?/ from the
[dworthen/js-yaml-front-matter](https://github.com/dworthen/js-yaml-front-matter/blob/master/lib/js-yaml-front.js)
repo to separate the YAML front matter from the JADE page content.

        re: /^(-{3}(?:\n|\r)([\w\W]+?)(?:\n|\r)-{3})?([\w\W]*)*/

Set the file name and location

        constructor: (@pageFile, @location = config.pagesPath) ->

Render the HTML

        render: ->

Make sure we have content

            if not @content?
                if not @pageFile?
                    throw new Error 'pageFile not set'
                location = "#{@location}/#{@pageFile}"
                @content = fs.readFileSync location, 'utf8'

Parse the content

            parts = @re.exec @content
            if ! @frontMatter?
                @frontMatter = if parts[2]? then yaml.safeLoad parts[2] else {}
            this[key] = value for key, value of @frontMatter
            if ! @containerContent?
                @containerContent = jade.render parts[3] or '',
                    filename: @pageFile
                    pretty: config.pretty

Parse the template

            template = new Template @template or null
            @html = template.getHtml this

Write the page into the output directory. I might move this to a separate
function (class) later on maybe?

        write: ->
            folder = "#{config.htmlPath}#{@url}"
            mkdirp folder unless fs.existsSync folder
            fs.writeFileSync "#{folder}/index.html", @html

#### Blog

It's the blog index page.

    class Blog extends Page
        posts: []
        content: ''
        template: 'blog'
        title: 'Blog'
        url: '/blog'

#### Pages

Iterate through a given directory and process the given pages.

Each page is pushed into a list of pages that will later be used for blog building
and sitemap.xml

    class Pages
        constructor: (@location) ->
            @pages = []
        render: ->
            for pageFile in (fs.readdirSync @location).reverse()
                page = new Page pageFile, @location
                page.render()
                page.write()
                @pages.push page

#### Blogs

Do the Pages thing and build a blog index on top.

    class Blogs extends Pages
        render: ->
            super()
            blog = new Blog
            blog.posts = @pages
            do blog.render
            do blog.write

# Render

    pages = new Pages config.pagesPath
    pages.render()
    blogs = new Blogs config.blogPath
    blogs.render()

# The build script

This is a very simple build script that puts together the YAML + JADE page files
and the pure JADE template files. It also builds the blog index.

Load modules

    fs = require 'fs'
    mkdirp = require('mkdirp').sync;
    jade = require 'jade'
    yaml = require 'js-yaml'
    config = require './config'
    execSync = (require 'child_process').execSync

Add custom Pygments filters to Jade

    jade.filters.bashcode = (text) ->
        result = execSync 'pygmentize -l bash -f html',
            input: text
        return result.toString()

### Template loader

Templates are different from pages in that they don't have a YAML front matter.
They are written in clean jade and can extend and include other templates.

    class Template
        constructor: (@name = 'page', @location = config.templatesPath) ->
        getHtml: (options) ->
            cwd = process.cwd()
            options.pretty = config.pretty
            options.filename = @name
            try
                process.chdir @location
                content = fs.readFileSync "#{@name}.jade", 'utf8'
                @html = jade.render content, options
            catch error
                console.log error
            finally
                process.chdir cwd
            return @html

## Page loader

    class Page

A nice /regexp?/ from the
[dworthen/js-yaml-front-matter](https://github.com/dworthen/js-yaml-front-matter/blob/master/lib/js-yaml-front.js)
repo to separate the YAML front matter from the JADE page content.

        re: /^(-{3}(?:\n|\r)([\w\W]+?)(?:\n|\r)-{3})?([\w\W]*)*/

Set the file name and location

        constructor: (@pageFile, @location = config.pagesPath) ->

Render the HTML

        render: ->

Make sure we have content

            if not @content?
                if not @pageFile?
                    throw new Error 'pageFile not set'
                location = "#{@location}/#{@pageFile}"
                @content = fs.readFileSync location, 'utf8'

Parse the content

            parts = @re.exec @content
            if ! @frontMatter?
                @frontMatter = if parts[2]? then yaml.safeLoad parts[2] else {}
            this[key] = value for key, value of @frontMatter
            if ! @containerContent?
                @containerContent = jade.render parts[3] or '',
                    filename: @pageFile
                    pretty: config.pretty

Parse the template

            template = new Template @template or null
            @html = template.getHtml this

Write the page into the output directory. I might move this to a separate
function (class) later on maybe?

        write: ->
            folder = "#{config.htmlPath}#{@url}"
            mkdirp folder unless fs.existsSync folder
            fs.writeFileSync "#{folder}/index.html", @html

#### Blog

It's the blog index page.

    class Blog extends Page
        posts: []
        content: ''
        template: 'blog'
        title: 'Blog'
        url: '/blog'

#### Pages

Iterate through a given directory and process the given pages.

Each page is pushed into a list of pages that will later be used for blog building
and sitemap.xml

    class Pages
        constructor: (@location) ->
            @pages = []
        render: ->
            for pageFile in (fs.readdirSync @location).reverse()
                page = new Page pageFile, @location
                page.render()
                page.write()
                @pages.push page

#### Blogs

Do the Pages thing and build a blog index on top.

    class Blogs extends Pages
        render: ->
            super()
            blog = new Blog
            blog.posts = @pages
            do blog.render
            do blog.write

# Render

    pages = new Pages config.pagesPath
    pages.render()
    blogs = new Blogs config.blogPath
    blogs.render()


Item::pointer::pressed and hover props are initialized when possible

# Pointer

```javascript
Rectangle {
    width: 100
    height: 100
    color: 'green'
    if (this.pointer.hover) {
        color: 'red'
    }
}
```

    'use strict'

    utils = require 'src/utils'
    signal = require 'src/signal'
    assert = require 'src/assert'

    NOP = ->

    module.exports = (Renderer, Impl, itemUtils, Item) -> (ctor) -> class Pointer extends itemUtils.DeepObject
        @__name__ = 'Pointer'

        itemUtils.defineProperty
            constructor: ctor
            name: 'pointer'
            valueConstructor: Pointer

Enables mouse and touch handling.

        constructor: (ref) ->
            super ref
            @_enabled = true
            @_draggable = false
            @_dragActive = false
            @_pressed = false
            @_hover = false
            @_pressedInitialized = false
            @_hoverInitialized = false

            Object.preventExtensions @

## *Boolean* Pointer::enabled = `true`

## *Signal* Pointer::onEnabledChange(*Boolean* oldValue)

        itemUtils.defineProperty
            constructor: Pointer
            name: 'enabled'
            defaultValue: true
            namespace: 'pointer'
            parentConstructor: ctor
            implementation: Impl.setItemPointerEnabled
            developmentSetter: (val) ->
                assert.isBoolean val

## Hidden *Boolean* Pointer::draggable = `false`

## Hidden *Signal* Pointer::onDraggableChange(*Boolean* oldValue)

        itemUtils.defineProperty
            constructor: Pointer
            name: 'draggable'
            defaultValue: false
            namespace: 'pointer'
            parentConstructor: ctor
            implementation: Impl.setItemPointerDraggable
            developmentSetter: (val) ->
                assert.isBoolean val

## Hidden *Boolean* Pointer::dragActive = `false`

## Hidden *Signal* Pointer::onDragActiveChange(*Boolean* oldValue)

        itemUtils.defineProperty
            constructor: Pointer
            name: 'dragActive'
            defaultValue: false
            namespace: 'pointer'
            parentConstructor: ctor
            implementation: Impl.setItemPointerDragActive
            developmentSetter: (val) ->
                assert.isBoolean val

## *Signal* Pointer::onClick(*Item.Pointer.Event* event)

## *Signal* Pointer::onPress(*Item.Pointer.Event* event)

## *Signal* Pointer::onRelease(*Item.Pointer.Event* event)

## *Signal* Pointer::onEnter(*Item.Pointer.Event* event)

## *Signal* Pointer::onExit(*Item.Pointer.Event* event)

## *Signal* Pointer::onWheel(*Item.Pointer.Event* event)

## *Signal* Pointer::onMove(*Item.Pointer.Event* event)

        PRESS_SIGNALS =
            onClick: true
            onPress: true
            onRelease: true

        MOVE_SIGNALS =
            onEnter: true
            onExit: true
            onMove: true

        onLazySignalInitialized = (pointer, name) ->
            # automatically initialize pressed and hover properties
            # if required events will be listened
            if PRESS_SIGNALS[name] or MOVE_SIGNALS[name]
                initializePressed pointer
                if MOVE_SIGNALS[name]
                    initializeHover pointer
            Impl.attachItemSignal.call pointer, 'pointer', name # TODO: send here an item
            return

        @SIGNALS = Object.keys(PRESS_SIGNALS).concat(Object.keys(MOVE_SIGNALS)).concat [
            'onWheel'
            # 'onDragStart', 'onDragEnd',
            # 'onDragEnter', 'onDragExit', 'onDrop'
        ]

        for signalName in @SIGNALS
            signal.Emitter.createSignal @, signalName, onLazySignalInitialized

## *Boolean* Pointer::pressed = `false`

Whether the pointer is currently pressed.

## *Signal* Pointer::onPressedChange(*Boolean* oldValue)

        initializePressed = do ->
            onPress = (event) ->
                event.stopPropagation = false
                @pressed = true
            onRelease = ->
                @pressed = false

            (pointer) ->
                unless pointer._pressedInitialized
                    pointer._pressedInitialized = true
                    pointer.onPress onPress
                    pointer.onRelease onRelease
                return

        itemUtils.defineProperty
            constructor: Pointer
            name: 'pressed'
            defaultValue: false
            namespace: 'pointer'
            parentConstructor: ctor
            signalInitializer: initializePressed
            getter: (_super) -> ->
                initializePressed @
                _super.call @

## *Boolean* Pointer::hover = `false`

Whether the pointer is currently under the item.

## *Signal* Pointer::onHoverChange(*Boolean* oldValue)

        initializeHover = do ->
            onEnter = ->
                @hover = true
            onExit = ->
                @hover = false

            (pointer) ->
                unless pointer._hoverInitialized
                    pointer._hoverInitialized = true
                    pointer.onEnter onEnter
                    pointer.onExit onExit
                return

        itemUtils.defineProperty
            constructor: Pointer
            name: 'hover'
            defaultValue: false
            namespace: 'pointer'
            parentConstructor: ctor
            signalInitializer: initializeHover
            getter: (_super) -> ->
                initializeHover @
                _super.call @

## **Class** Pointer.Event : *Device.PointerEvent*

Events order:
 1. Press
 2. Enter
 3. Move
 4. Move (not captured ensured items)
 5. Exit
 6. Release
 7. Click
 8. Release (not captured ensured items)

Stopped 'Enter' event will emit 'Move' event on this item.

Stopped 'Exit' event will emit 'Release' event on this item.

        @Event = class PointerEvent
            constructor: ->
                @_stopPropagation = true
                @_checkSiblings = false
                @_ensureRelease = true
                @_ensureMove = true
                Object.preventExtensions @

            @:: = Object.create Renderer.Device.pointer
            @::constructor = PointerEvent

### *Boolean* PointerEvent::stopPropagation = `false`

Enable this property to stop further event propagation.

            utils.defineProperty @::, 'stopPropagation', null, ->
                @_stopPropagation
            , (val) ->
                assert.isBoolean val
                @_stopPropagation = val

### *Boolean* PointerEvent::checkSiblings = `false`

By default first deepest captured item will propagate this event only by his parents.

Change this value to test previous siblings as well.

            utils.defineProperty @::, 'checkSiblings', null, ->
                @_checkSiblings
            , (val) ->
                assert.isBoolean val
                @_checkSiblings = val

### *Boolean* PointerEvent::ensureRelease = `true`

Define whether pressed item should get 'onRelease' signal even
if the pointer has been released outside of this item.

Can be changed only in the 'onPress' signal.

            utils.defineProperty @::, 'ensureRelease', null, ->
                @_ensureRelease
            , (val) ->
                assert.isBoolean val
                @_ensureRelease = val

### *Boolean* PointerEvent::ensureMove = `true`

Define whether the pressed item should get 'onMove' signals even
if the pointer is outside of this item.

Can be changed only in the 'onPress' signal.

            utils.defineProperty @::, 'ensureMove', null, ->
                @_ensureMove
            , (val) ->
                assert.isBoolean val
                @_ensureMove = val

## *Item.Pointer.Event* Pointer.event

        @event = new PointerEvent

# Pointer

```javascript
Rectangle {
    width: 100
    height: 100
    color: 'green'
    if (this.pointer.hover) {
        color: 'red'
    }
}
```

    'use strict'

    utils = require 'src/utils'
    signal = require 'src/signal'
    assert = require 'src/assert'

    NOP = ->

    module.exports = (Renderer, Impl, itemUtils, Item) -> (ctor) -> class Pointer extends itemUtils.DeepObject
        @__name__ = 'Pointer'

        itemUtils.defineProperty
            constructor: ctor
            name: 'pointer'
            valueConstructor: Pointer

Enables mouse and touch handling.

        constructor: (ref) ->
            super ref
            @_enabled = true
            @_draggable = false
            @_dragActive = false
            @_pressed = false
            @_hover = false
            @_pressedInitialized = false
            @_hoverInitialized = false

            Object.preventExtensions @

## *Boolean* Pointer::enabled = `true`

## *Signal* Pointer::onEnabledChange(*Boolean* oldValue)

        itemUtils.defineProperty
            constructor: Pointer
            name: 'enabled'
            defaultValue: true
            namespace: 'pointer'
            parentConstructor: ctor
            implementation: Impl.setItemPointerEnabled
            developmentSetter: (val) ->
                assert.isBoolean val

## Hidden *Boolean* Pointer::draggable = `false`

## Hidden *Signal* Pointer::onDraggableChange(*Boolean* oldValue)

        itemUtils.defineProperty
            constructor: Pointer
            name: 'draggable'
            defaultValue: false
            namespace: 'pointer'
            parentConstructor: ctor
            implementation: Impl.setItemPointerDraggable
            developmentSetter: (val) ->
                assert.isBoolean val

## Hidden *Boolean* Pointer::dragActive = `false`

## Hidden *Signal* Pointer::onDragActiveChange(*Boolean* oldValue)

        itemUtils.defineProperty
            constructor: Pointer
            name: 'dragActive'
            defaultValue: false
            namespace: 'pointer'
            parentConstructor: ctor
            implementation: Impl.setItemPointerDragActive
            developmentSetter: (val) ->
                assert.isBoolean val

## *Signal* Pointer::onClick(*Item.Pointer.Event* event)

## *Signal* Pointer::onPress(*Item.Pointer.Event* event)

## *Signal* Pointer::onRelease(*Item.Pointer.Event* event)

## *Signal* Pointer::onEnter(*Item.Pointer.Event* event)

## *Signal* Pointer::onExit(*Item.Pointer.Event* event)

## *Signal* Pointer::onWheel(*Item.Pointer.Event* event)

## *Signal* Pointer::onMove(*Item.Pointer.Event* event)

## Hidden *Signal* Pointer::onDragStart()

## Hidden *Signal* Pointer::onDragEnd()

## Hidden *Signal* Pointer::onDragEnter()

## Hidden *Signal* Pointer::onDragExit()

## Hidden *Signal* Pointer::onDrop()

        onLazySignalInitialized = (pointer, name) ->
            Impl.attachItemSignal.call pointer, 'pointer', name # TODO: send here an item
            return

        @SIGNALS = ['onClick', 'onPress', 'onRelease',
                    'onEnter', 'onExit', 'onWheel', 'onMove',
                    'onDragStart', 'onDragEnd',
                    'onDragEnter', 'onDragExit', 'onDrop']

        for signalName in @SIGNALS
            signal.Emitter.createSignal @, signalName, onLazySignalInitialized

## *Boolean* Pointer::pressed = `false`

Whether the pointer is currently pressed.

## *Signal* Pointer::onPressedChange(*Boolean* oldValue)

        intitializePressed = do ->
            onPress = (event) ->
                event.stopPropagation = false
                @pressed = true
            onRelease = ->
                @pressed = false

            (pointer) ->
                unless pointer._pressedInitialized
                    pointer._pressedInitialized = true
                    pointer.onPress onPress
                    pointer.onRelease onRelease
                return

        itemUtils.defineProperty
            constructor: Pointer
            name: 'pressed'
            defaultValue: false
            namespace: 'pointer'
            parentConstructor: ctor
            signalInitializer: intitializePressed
            getter: (_super) -> ->
                intitializePressed @
                _super.call @

## *Boolean* Pointer::hover = `false`

Whether the pointer is currently under the item.

## *Signal* Pointer::onHoverChange(*Boolean* oldValue)

        initializeHover = do ->
            onEnter = ->
                @hover = true
            onExit = ->
                @hover = false

            (pointer) ->
                unless pointer._hoverInitialized
                    pointer._hoverInitialized = true
                    pointer.onEnter onEnter
                    pointer.onExit onExit
                return

        itemUtils.defineProperty
            constructor: Pointer
            name: 'hover'
            defaultValue: false
            namespace: 'pointer'
            parentConstructor: ctor
            signalInitializer: initializeHover
            getter: (_super) -> ->
                initializeHover @
                _super.call @

## **Class** Pointer.Event : *Device.PointerEvent*

Events order:
 1. Press
 2. Enter
 3. Move
 4. Move (not captured ensured items)
 5. Exit
 6. Release
 7. Click
 8. Release (not captured ensured items)

Stopped 'Enter' event will emit 'Move' event on this item.

Stopped 'Exit' event will emit 'Release' event on this item.

        @Event = class PointerEvent
            constructor: ->
                @_stopPropagation = true
                @_checkSiblings = false
                @_ensureRelease = true
                @_ensureMove = true
                Object.preventExtensions @

            @:: = Object.create Renderer.Device.pointer
            @::constructor = PointerEvent

### *Boolean* PointerEvent::stopPropagation = `false`

Enable this property to stop further event propagation.

            utils.defineProperty @::, 'stopPropagation', null, ->
                @_stopPropagation
            , (val) ->
                assert.isBoolean val
                @_stopPropagation = val

### *Boolean* PointerEvent::checkSiblings = `false`

By default first deepest captured item will propagate this event only by his parents.

Change this value to test previous siblings as well.

            utils.defineProperty @::, 'checkSiblings', null, ->
                @_checkSiblings
            , (val) ->
                assert.isBoolean val
                @_checkSiblings = val

### *Boolean* PointerEvent::ensureRelease = `true`

Define whether pressed item should get 'onRelease' signal even
if the pointer has been released outside of this item.

Can be changed only in the 'onPress' signal.

            utils.defineProperty @::, 'ensureRelease', null, ->
                @_ensureRelease
            , (val) ->
                assert.isBoolean val
                @_ensureRelease = val

### *Boolean* PointerEvent::ensureMove = `true`

Define whether the pressed item should get 'onMove' signals even
if the pointer is outside of this item.

Can be changed only in the 'onPress' signal.

            utils.defineProperty @::, 'ensureMove', null, ->
                @_ensureMove
            , (val) ->
                assert.isBoolean val
                @_ensureMove = val

## *Item.Pointer.Event* Pointer.event

        @event = new PointerEvent


change port for heroku tests

change port for heroku tests

GapiSparql - Main class for GAPI SPARQL component

    restify = require('restify')
    self = null

    class GapiSparql

        constructor: (options) ->
            console.log('GapiSparql construct...')
            self = @
            @options = options or {}

            @options.name = 'gapi-sparql'
            @options.version = '0.0.1'
            @options.accept =
            #@options.formatters = {}
            #@options.formatters['application/sparql-query'] = @sparqlQuery
            @options.listenPort ?= 80
            # @options.accept

            server = restify.createServer(@options)
            #server.pre( (req, res, next) ->
            #    req.headers.accept = 'application/sparql-query'
            #    return next()
            #)
            server.listen(@options.listenPort, () ->
                console.log('%s listening at %s', server.name, server.url)
            )
            server.get('/.*/', (req, res, next) ->
                # console.log(res)
                d = "ahoj svete"
                res.writeHead(200, {
                    'Content-Length': Buffer.byteLength(d),
                    'Content-Type': 'text/plain'
                })
                res.write(d)
                res.end()
                next()
            )
            @server = server

        @run: (argv, exit) ->
            console.log('GapiSparql @run()')
            gapisparql = new GapiSparql()

        sparqlQuery: (req, res, body) ->
            console.log('GapiSparql @sparqlQuery()')
            body = "ahok"
            #console.log(body)
            #console.log('----- GapiSparql @sparqlQuery() -----');
            ###
            if body instanceof Error
                res.statusCode = body.statusCode || 500
                if body.body
                    #console.log('dada');
                    #body = body.body.message
                    body = "ttt"
                else
                    #body = message: body.message
                    body = "fifif"
                data = "err"
            else
                body = "body pyco"
                data = "aaa"
            console.log(body)
            #console.log(req)
            #console.log(res)
            #console.log(body)
            res.setHeader('Content-Length', Buffer.byteLength(body))
            return body
            ###
            return body

        use: (pluginName) ->

    module.exports = GapiSparql

GapiSparql - Main class for GAPI SPARQL component

    restify = require('restify')
    self = null

    class GapiSparql

        constructor: (options) ->
            console.log('GapiSparql construct...')
            self = @
            @options = options or {}

            @options.name = 'gapi-sparql'
            @options.version = '0.0.1'
            @options.accept =
            #@options.formatters = {}
            #@options.formatters['application/sparql-query'] = @sparqlQuery
            @options.listenPort ?= 8008
            # @options.accept

            server = restify.createServer(@options)
            #server.pre( (req, res, next) ->
            #    req.headers.accept = 'application/sparql-query'
            #    return next()
            #)
            server.listen(@options.listenPort, () ->
                console.log('%s listening at %s', server.name, server.url)
            )
            server.get('/.*/', (req, res, next) ->
                # console.log(res)
                d = "ahoj svete"
                res.writeHead(200, {
                    'Content-Length': Buffer.byteLength(d),
                    'Content-Type': 'text/plain'
                })
                res.write(d)
                res.end()
                next()
            )
            @server = server

        @run: (argv, exit) ->
            console.log('GapiSparql @run()')
            gapisparql = new GapiSparql()

        sparqlQuery: (req, res, body) ->
            console.log('GapiSparql @sparqlQuery()')
            body = "ahok"
            #console.log(body)
            #console.log('----- GapiSparql @sparqlQuery() -----');
            ###
            if body instanceof Error
                res.statusCode = body.statusCode || 500
                if body.body
                    #console.log('dada');
                    #body = body.body.message
                    body = "ttt"
                else
                    #body = message: body.message
                    body = "fifif"
                data = "err"
            else
                body = "body pyco"
                data = "aaa"
            console.log(body)
            #console.log(req)
            #console.log(res)
            #console.log(body)
            res.setHeader('Content-Length', Buffer.byteLength(body))
            return body
            ###
            return body

        use: (pluginName) ->

    module.exports = GapiSparql


typo fix

typo fix

    _self = this

    if console?.log?
     LOG = console.log.bind console
    else
     LOG = -> null

    if console?.error?
     ERROR_LOG = console.error.bind console
    else
     ERROR_LOG = -> null

    POLL_TYPE =
     progress: true

##Response class

    class Response
     constructor: (data, port, options) ->
      @id = data.id
      @port = port
      @options = options
      @queue = []
      @fresh = true

     progress: (progress, data, callback) ->
      @queue.push
       method: 'progress'
       data: data
       options: {progress: progress}
       callback: callback
      @_handleQueue()

     success: (data) ->
      @queue.push method: 'success', data: data, options: {}
      @_handleQueue()

     fail: (data) ->
      @queue.push method: 'fail', data: data, options: {}
      @_handleQueue()

     setOptions: (options) ->
      @options = options
      @fresh = true
      @_handleQueue()

     _multipleResponse: ->
      responseList = []
      callbacks = []
      for d in @queue
       responseList.push
        status: d.method
        data: d.data
        options: d.options
       if d.callback?
        callbacks.push d.callback

      done = ->
       for callback in callbacks
        callback()

      if @port.isStreaming
       @port.respondMultiple this, responseList, @options, done
      else if @fresh
       @port.respondMultiple this, responseList, @options, done
       @fresh = false

      @queue = []

     _handleQueue: ->
      return unless @queue.length > 0
      return if not @port.isStreaming and not @fresh

      if @queue.length > 1
       return @_multipleResponse()

      d = @queue[0]

      if @port.isStreaming
       @port.respond this, d.method, d.data, d.options, @options, d.callback
      else if @fresh
       @port.respond this, d.method, d.data, d.options, @options, d.callback
       @fresh = false

      @queue = []

##Call class

    class Call
     constructor: (@id, @method, @data, @callbacks, @options, @port) -> null

     handle: (data, options) ->
      if not @callbacks[options.status]?
       return if options.status is 'progress'
       #Handled by caller
       throw new Error "No callback registered #{@method} #{options.status}"
      self = this
      setTimeout ->
       try
        self.callbacks[options.status] data, options
       catch e
        if self.port.onerror?
         self.port.onerror e
        else
         throw e
      , 0

      if POLL_TYPE[options.status]?
       return false
      else
       return true

##Port base class

    class Port
     constructor: ->
      @handlers = {}
      @callsCache = {}
      @callsCounter = 0
      @id = parseInt Math.random() * 1000
      @responses = {}
      @wrappers =
       send: []
       respond: []
       handleCall: []
       handleResponse: []

     isStreaming: true

     onCallError: (msg, options) ->
      callsCache = @callsCache
      @callsCache = {}
      for id, call of callsCache
       if not call.callbacks.fail?
        ERROR_LOG 'fail callback not registered', call.method, call.data
       else
        call.callbacks.fail error: 'connectionError', msg: msg, options: options, {}

      @errorCallback msg, options

     onHandleError: (msg, data, options) ->
      @errorCallback msg, data
      response = new Response data, this, options
      response.fail msg

     errorCallback: (msg, options) ->
      ERROR_LOG msg, options

     wrap: (wrapper) ->
      for key, f of wrapper
       if @wrappers[key]?
        @wrappers[key].push f
       else
        this[key] = f

###Send RPC call

     send: (method, data, callbacks, options = {}) ->
      if (typeof callbacks) is 'function'
       callbacks =
        success: callbacks

      for f in @wrappers.send
       return unless f.apply this, [method, data, callbacks, options]

      params = @_createCall method, data, callbacks, options
      @_send params, callbacks

###Respond to a RPC call

     respond: (response, status, data, options = {}, portOptions = {}, callback = null) ->
      if not POLL_TYPE[status]?
       delete @responses[response.id]

      for f in @wrappers.respond
       return unless f.apply this, [response, status, data, options, portOptions]

      @_respond (@_createResponse response, status, data, options), portOptions, callback

     respondMultiple: (response, list, portOptions = {}, callback = null) ->
      for d in list
       if not POLL_TYPE[d.status]?
        delete @responses[response.id]
        break

      data = []
      for d in list
       cancel = false
       d.options ?= {}
       for f in @wrappers.respond
        r = f.apply this, [response, d.status, d.data, d.options, portOptions]
        if not r
         cancel = true
         break

        continue if cancel

       data.push @_createResponse response, d.status, d.data, d.options

      return if data.length is 0

      data =
       type: 'list'
       list: data

      @_respond data, portOptions, callback

###Create Call object
This is a private function

     _createCall: (method, data, callbacks, options) ->
      call = new Call "#{@id}-#{@callsCounter}",
                      method
                      data
                      callbacks
                      options
                      this
      @callsCounter++
      @callsCache[call.id] = call

      params =
       type: 'call'
       id: call.id
       method: call.method
       data: call.data

      params[k] = v for k, v of options
      return params

###Create Response object

     _createResponse: (response, status, data, options) ->
      params =
       type: 'response'
       id: response.id
       status: status
       data: data

      params[k] = v for k, v of options

      return params

###Add handler

     on: (method, callback) ->
      @handlers[method] = callback

###Handle incoming message

     _handleMessage: (data, options, last = true) ->
      switch data.type
       when 'list'
        for d, i in data.list
         @_handleMessage d, options, (last and i + 1 is data.list.length)
       when 'response'
        try
         @_handleResponse data, options, last
        catch e
         @onerror? e
       when 'call'
        try
         @_handleCall data, options, last
        catch e
         @onerror? e
       when 'poll'
        try
         @_handlePoll data, options, last
        catch e
         @onerror? e

     _handleCall: (data, options) ->
      for f in @wrappers.handleCall
       return unless f.apply this, arguments
      if not @handlers[data.method]?
       @onHandleError "Unknown method: #{data.method}", data, options
       return
      @responses[data.id] = new Response data, this, options
      @handlers[data.method] data.data, data, @responses[data.id]

     _handleResponse: (data, options) ->
      for f in @wrappers.handleResponse
       return unless f.apply this, arguments
      if not @callsCache[data.id]?
       #Cannot reply
       @errorCallback "Response without call: #{data.id}", data
       return
      try
       if @callsCache[data.id].handle data.data, data
        delete @callsCache[data.id]
      catch e
       @errorCallback e.message, data
       delete @callsCache[data.id]

     _handlePoll: (data, options) ->
      @onHandleError "Poll not implemented", data, options

##WorkerPort class
Used for browser and worker

    class WorkerPort extends Port
     constructor: (worker) ->
      super()
      @worker = worker
      @worker.onmessage = @_onMessage.bind this
      #@worker.onerror = @onCallError.bind this

     _send: (data) ->
      dd = data.data
      if dd? and dd._transferList?
       transferList = dd._transferList
       delete dd._transferList
      else
       transferList = []
      @worker.postMessage data, transferList

     _respond: (data, options, callback) ->
      dd = data.data
      if dd? and dd._transferList?
       transferList = dd._transferList
       delete dd._transferList
      else
       transferList = []
      @worker.postMessage data, transferList
      callback?()

     _onMessage: (e) ->
      data = e.data
      @_handleMessage data

##FramePort class
Used for browser and worker

    class FramePort extends Port
     constructor: (source, dest) ->
      super()
      @source = source
      @dest = dest
      @source.addEventListener 'message', @_onMessage.bind this

     _send: (data) ->
      @dest.postMessage data, '*'

     _respond: (data, options, callback) ->
      @dest.postMessage data, '*'
      callback?()

     _onMessage: (e) ->
      data = e.data
      @_handleMessage data

##SocketPort class

    class SocketPort extends Port
     constructor: (socket) ->
      super()
      @socket = socket
      @socket.on 'message', @_onMessage.bind this

     _send: (data) ->  @socket.emit 'message', data
     _respond: (data, options, callback) ->
      @worker.emit 'message', data
      callback?()

     _onMessage: (e) ->
      data = e.data
      @_handleMessage data

##ServerSocketPort class

    class ServerSocketPort extends Port
     constructor: (server) ->
      super()
      @server = server
      @server.on 'connection', @_onConnection.bind this

     _onConnection: (socket) ->
      new SocketPort handlers: @handlers, socket

##AJAX class

    class AjaxHttpPort extends Port
     constructor: (options) ->
      super()
      @protocol = options.protocol
      @host = options.host
      @port = options.port
      @path = options.path ? '/'
      @url = @path
      if @protocol?
       if @host? and not @port?
        @url = "#{@protocol}://#{@host}#{@path}"
       else if @host? and @port?
        @url = "#{@protocol}://#{@host}:#{@port}#{@path}"
      else
       if @host? and not @port?
        @url = "//#{@host}#{@path}"
       else if @host? and @port?
        @url = "//#{@host}:#{@port}#{@path}"

     isStreaming: false

     _onRequest: (xhr) ->
      return unless xhr.readyState is 4
      status = xhr.status
      if ((not status and xhr.responseText? and xhr.responseText != '') or
          (status >= 200 and status < 300) or
          (status is 304))
       try
        jsonData = JSON.parse xhr.responseText
       catch e
        @onCallError 'ParseError', e
        return

       @_handleMessage jsonData, xhr: xhr
      else
       @onCallError 'Cannot connect to server'

     _respond: (data, options, callback) ->
      @errorCallback 'AJAX cannot respond', data
      callback?()

     _send: (data) ->
      data = JSON.stringify data
      xhr = new XMLHttpRequest
      xhr.open 'POST', @url
      xhr.onreadystatechange = =>
       @_onRequest xhr
      xhr.setRequestHeader 'Accept', 'application/json'
      #xhr.setRequestHeader 'Content-Type', 'application/json'
      xhr.send data

     _handleResponse: (data, options, last = true) ->
      for f in @wrappers.handleResponse
       return unless f.apply this, arguments
      if not @callsCache[data.id]?
       @errorCallback "Response without call: #{data.id}", data
       return
      call = @callsCache[data.id]
      try
       if call.handle data.data, data
        delete @callsCache[data.id]
       else if last
        params =
         type: 'poll'
         id: call.id
        params[k] = v for k, v of call.options
        @_send params
      catch e
       @errorCallback e.message, data
       delete @callsCache[data.id]

##NodeHttpPort class

    class NodeHttpPort extends Port
     constructor: (options, http) ->
      super()
      @host = options.host ? 'localhost'
      @port = options.port ? 80
      @path = options.path ? '/'
      @http = http
      @_createHttpOptions()

     isStreaming: false

     _createHttpOptions: ->
      @httpOptions =
       hostname: @host
       port: @port
       path: @path
       method: 'POST'
       agent: false
       headers:
        accept: 'application/json'
       'content-type': 'application/json'

     _onRequest: (res) ->
      data = ''
      #LOG 'STATUS: ' + res.statusCode
      #LOG 'HEADERS: ' + JSON.stringify res.headers
      res.setEncoding 'utf8'
      res.on 'data', (chunk) ->
       data += chunk
      #LOG 'result', res
      res.on 'end', =>
       try
        jsonData = JSON.parse data
       catch e
        @onCallError 'ParseError', e
        return

       @_handleMessage jsonData, response: res

     _respond: (data, options, callback) ->
      data = JSON.stringify data
      res = options.response
      res.setHeader 'content-length', Buffer.byteLength data, 'utf8'
      if callback?
       res.once 'finish', ->
        callback()
       res.once 'close', ->
        callback()

      res.write data
      res.end()

     _send: (data, callbacks) ->
      data = JSON.stringify data
      options = @httpOptions
      options.headers['content-length'] = Buffer.byteLength data, 'utf8'

      req = @http.request options, @_onRequest.bind this
      delete options.headers['content-length']
      req.on 'error', (e) =>
       try
        callbacks.fail? e
       catch err
        @onerror? err

      req.write data
      req.end()

     _handleResponse: (data, options, last = true) ->
      for f in @wrappers.handleResponse
       return unless f.apply this, arguments
      if not @callsCache[data.id]?
       @errorCallback "Response without call: #{data.id}", data
       return
      call = @callsCache[data.id]
      if not call.handle data.data, data
       return if not last
       params =
        type: 'poll'
        id: call.id
       params[k] = v for k, v of call.options
       @_send params, call.callbacks

##NodeHttpServerPort class

    class NodeHttpServerPort extends Port
     constructor: (options, http, zlib = null) ->
      super()
      @port = options.port
      @http = http
      @zlib = zlib
      @allowOrigin = options.allowOrigin

     isStreaming: false

     _onRequest: (req, res) ->
      data = ''
      res.setHeader 'content-type', 'application/json'

      req.on 'data', (chunk) ->
       data += chunk
      req.on 'end', =>
       try
        jsonData = JSON.parse data
       catch e
        @errorCallback 'ParseError', e
        return

       @_handleMessage jsonData, response: res, request: req

     _respond: (data, options, callback) ->
      if @allowOrigin?
       options.response.setHeader 'Access-Control-Allow-Origin', @allowOrigin

      accept = options.request.headers['accept-encoding']
      accept ?= ''
      if not @zlib?
       accept = ''

      data = JSON.stringify data
      buffer = new Buffer data, 'utf8'
      if accept.match /\bgzip\b/
       options.response.setHeader 'content-encoding', 'gzip'
       @zlib.gzip buffer, (err, result) =>
        if err?
         return @errorCallback 'GZipeError', e
        @_sendBuffer result, options.response, callback
      else if accept.match /\bdeflate\b/
       options.response.setHeader 'content-encoding', 'deflate'
       @zlib.deflate buffer, (err, result) =>
        if err?
         return @errorCallback 'DeflateError', e
        @_sendBuffer result, options.response, callback
      else
       @_sendBuffer buffer, options.response, callback

     _sendBuffer: (buf, res, callback) ->
       res.setHeader 'content-length', buf.length
       if callback?
        res.once 'finish', ->
         callback()
        res.once 'close', ->
         callback()

       res.write buf
       res.end()

     listen: ->
      @server = @http.createServer @_onRequest.bind this
      @server.listen @port

     _handlePoll: (data, options) ->
      for f in @wrappers.handleCall
       return unless f.apply this, arguments
      if not @responses[data.id]?
       @onHandleError "Poll without response: #{data.id}", data, options
       return
      @responses[data.id].setOptions options

##NodeHttpsServerPort class

    class NodeHttpsServerPort extends NodeHttpServerPort
     constructor: (options, http) ->
      super options, http
      @_key = options.key
      @_cert = options.cert

     listen: ->
      options =
       key: @_key
       cert: @_cert

      @server = @http.createServer options, @_onRequest.bind this
      @server.listen @port

#IO Module

    IO =
     addPort: (name, port) ->
      IO[name] = port

     ports:
      WorkerPort: WorkerPort
      FramePort: FramePort
      SocketPort: SocketPort
      AjaxHttpPort: AjaxHttpPort
      NodeHttpPort: NodeHttpPort
      NodeHttpServerPort: NodeHttpServerPort
      NodeHttpsServerPort: NodeHttpsServerPort
      ServerSocketPort: ServerSocketPort

     Helpers:
      progress: (from, to, func) ->
       (progress, data) ->
        func? progress * (to - from) + from, data

     setup_____: (options) ->
      options.workers ?= []
      switch options.platform
       when 'ui'
        for worker in options.workers
         IO.addPort worker.name, new WorkerPort worker.js
        for socket in options.sockets
         IO.addPort socket.name, new SocketPort socket.url
       when 'node'
        for socket in options.listenSockets
         IO.addPort socket.name, new SocketListenPort socket.port
        for socket in options.sockets
         IO.addPort socket.name, new SocketPort socket.url
       when 'worker'
        IO.addPort 'UI', new WorkerListenPort _self

    if exports?
     module.exports = IO
    else
     _self.IO = IO

    _self = this

    if console?.log?
     LOG = console.log.bind console
    else
     LOG = -> null

    if console?.error?
     ERROR_LOG = console.error.bind console
    else
     ERROR_LOG = -> null

    POLL_TYPE =
     progress: true

##Response class

    class Response
     constructor: (data, port, options) ->
      @id = data.id
      @port = port
      @options = options
      @queue = []
      @fresh = true

     progress: (progress, data, callback) ->
      @queue.push
       method: 'progress'
       data: data
       options: {progress: progress}
       callback: callback
      @_handleQueue()

     success: (data) ->
      @queue.push method: 'success', data: data, options: {}
      @_handleQueue()

     fail: (data) ->
      @queue.push method: 'fail', data: data, options: {}
      @_handleQueue()

     setOptions: (options) ->
      @options = options
      @fresh = true
      @_handleQueue()

     _multipleResponse: ->
      responseList = []
      callbacks = []
      for d in @queue
       responseList.push
        status: d.method
        data: d.data
        options: d.options
       if d.callback?
        callbacks.push d.callback

      done = ->
       for callback in callbacks
        callback()

      if @port.isStreaming
       @port.respondMultiple this, responseList, @options, done
      else if @fresh
       @port.respondMultiple this, responseList, @options, done
       @fresh = false

      @queue = []

     _handleQueue: ->
      return unless @queue.length > 0
      return if not @queue.isStreaming and not @fresh

      if @queue.length > 1
       return @_multipleResponse()

      d = @queue[0]

      if @port.isStreaming
       @port.respond this, d.method, d.data, d.options, @options, d.callback
      else if @fresh
       @port.respond this, d.method, d.data, d.options, @options, d.callback
       @fresh = false

      @queue = []

##Call class

    class Call
     constructor: (@id, @method, @data, @callbacks, @options, @port) -> null

     handle: (data, options) ->
      if not @callbacks[options.status]?
       return if options.status is 'progress'
       #Handled by caller
       throw new Error "No callback registered #{@method} #{options.status}"
      self = this
      setTimeout ->
       try
        self.callbacks[options.status] data, options
       catch e
        if self.port.onerror?
         self.port.onerror e
        else
         throw e
      , 0

      if POLL_TYPE[options.status]?
       return false
      else
       return true

##Port base class

    class Port
     constructor: ->
      @handlers = {}
      @callsCache = {}
      @callsCounter = 0
      @id = parseInt Math.random() * 1000
      @responses = {}
      @wrappers =
       send: []
       respond: []
       handleCall: []
       handleResponse: []

     isStreaming: true

     onCallError: (msg, options) ->
      callsCache = @callsCache
      @callsCache = {}
      for id, call of callsCache
       if not call.callbacks.fail?
        ERROR_LOG 'fail callback not registered', call.method, call.data
       else
        call.callbacks.fail error: 'connectionError', msg: msg, options: options, {}

      @errorCallback msg, options

     onHandleError: (msg, data, options) ->
      @errorCallback msg, data
      response = new Response data, this, options
      response.fail msg

     errorCallback: (msg, options) ->
      ERROR_LOG msg, options

     wrap: (wrapper) ->
      for key, f of wrapper
       if @wrappers[key]?
        @wrappers[key].push f
       else
        this[key] = f

###Send RPC call

     send: (method, data, callbacks, options = {}) ->
      if (typeof callbacks) is 'function'
       callbacks =
        success: callbacks

      for f in @wrappers.send
       return unless f.apply this, [method, data, callbacks, options]

      params = @_createCall method, data, callbacks, options
      @_send params, callbacks

###Respond to a RPC call

     respond: (response, status, data, options = {}, portOptions = {}, callback = null) ->
      if not POLL_TYPE[status]?
       delete @responses[response.id]

      for f in @wrappers.respond
       return unless f.apply this, [response, status, data, options, portOptions]

      @_respond (@_createResponse response, status, data, options), portOptions, callback

     respondMultiple: (response, list, portOptions = {}, callback = null) ->
      for d in list
       if not POLL_TYPE[d.status]?
        delete @responses[response.id]
        break

      data = []
      for d in list
       cancel = false
       d.options ?= {}
       for f in @wrappers.respond
        r = f.apply this, [response, d.status, d.data, d.options, portOptions]
        if not r
         cancel = true
         break

        continue if cancel

       data.push @_createResponse response, d.status, d.data, d.options

      return if data.length is 0

      data =
       type: 'list'
       list: data

      @_respond data, portOptions, callback

###Create Call object
This is a private function

     _createCall: (method, data, callbacks, options) ->
      call = new Call "#{@id}-#{@callsCounter}",
                      method
                      data
                      callbacks
                      options
                      this
      @callsCounter++
      @callsCache[call.id] = call

      params =
       type: 'call'
       id: call.id
       method: call.method
       data: call.data

      params[k] = v for k, v of options
      return params

###Create Response object

     _createResponse: (response, status, data, options) ->
      params =
       type: 'response'
       id: response.id
       status: status
       data: data

      params[k] = v for k, v of options

      return params

###Add handler

     on: (method, callback) ->
      @handlers[method] = callback

###Handle incoming message

     _handleMessage: (data, options, last = true) ->
      switch data.type
       when 'list'
        for d, i in data.list
         @_handleMessage d, options, (last and i + 1 is data.list.length)
       when 'response'
        try
         @_handleResponse data, options, last
        catch e
         @onerror? e
       when 'call'
        try
         @_handleCall data, options, last
        catch e
         @onerror? e
       when 'poll'
        try
         @_handlePoll data, options, last
        catch e
         @onerror? e

     _handleCall: (data, options) ->
      for f in @wrappers.handleCall
       return unless f.apply this, arguments
      if not @handlers[data.method]?
       @onHandleError "Unknown method: #{data.method}", data, options
       return
      @responses[data.id] = new Response data, this, options
      @handlers[data.method] data.data, data, @responses[data.id]

     _handleResponse: (data, options) ->
      for f in @wrappers.handleResponse
       return unless f.apply this, arguments
      if not @callsCache[data.id]?
       #Cannot reply
       @errorCallback "Response without call: #{data.id}", data
       return
      try
       if @callsCache[data.id].handle data.data, data
        delete @callsCache[data.id]
      catch e
       @errorCallback e.message, data
       delete @callsCache[data.id]

     _handlePoll: (data, options) ->
      @onHandleError "Poll not implemented", data, options

##WorkerPort class
Used for browser and worker

    class WorkerPort extends Port
     constructor: (worker) ->
      super()
      @worker = worker
      @worker.onmessage = @_onMessage.bind this
      #@worker.onerror = @onCallError.bind this

     _send: (data) ->
      dd = data.data
      if dd? and dd._transferList?
       transferList = dd._transferList
       delete dd._transferList
      else
       transferList = []
      @worker.postMessage data, transferList

     _respond: (data, options, callback) ->
      dd = data.data
      if dd? and dd._transferList?
       transferList = dd._transferList
       delete dd._transferList
      else
       transferList = []
      @worker.postMessage data, transferList
      callback?()

     _onMessage: (e) ->
      data = e.data
      @_handleMessage data

##FramePort class
Used for browser and worker

    class FramePort extends Port
     constructor: (source, dest) ->
      super()
      @source = source
      @dest = dest
      @source.addEventListener 'message', @_onMessage.bind this

     _send: (data) ->
      @dest.postMessage data, '*'

     _respond: (data, options, callback) ->
      @dest.postMessage data, '*'
      callback?()

     _onMessage: (e) ->
      data = e.data
      @_handleMessage data

##SocketPort class

    class SocketPort extends Port
     constructor: (socket) ->
      super()
      @socket = socket
      @socket.on 'message', @_onMessage.bind this

     _send: (data) ->  @socket.emit 'message', data
     _respond: (data, options, callback) ->
      @worker.emit 'message', data
      callback?()

     _onMessage: (e) ->
      data = e.data
      @_handleMessage data

##ServerSocketPort class

    class ServerSocketPort extends Port
     constructor: (server) ->
      super()
      @server = server
      @server.on 'connection', @_onConnection.bind this

     _onConnection: (socket) ->
      new SocketPort handlers: @handlers, socket

##AJAX class

    class AjaxHttpPort extends Port
     constructor: (options) ->
      super()
      @protocol = options.protocol
      @host = options.host
      @port = options.port
      @path = options.path ? '/'
      @url = @path
      if @protocol?
       if @host? and not @port?
        @url = "#{@protocol}://#{@host}#{@path}"
       else if @host? and @port?
        @url = "#{@protocol}://#{@host}:#{@port}#{@path}"
      else
       if @host? and not @port?
        @url = "//#{@host}#{@path}"
       else if @host? and @port?
        @url = "//#{@host}:#{@port}#{@path}"

     isStreaming: false

     _onRequest: (xhr) ->
      return unless xhr.readyState is 4
      status = xhr.status
      if ((not status and xhr.responseText? and xhr.responseText != '') or
          (status >= 200 and status < 300) or
          (status is 304))
       try
        jsonData = JSON.parse xhr.responseText
       catch e
        @onCallError 'ParseError', e
        return

       @_handleMessage jsonData, xhr: xhr
      else
       @onCallError 'Cannot connect to server'

     _respond: (data, options, callback) ->
      @errorCallback 'AJAX cannot respond', data
      callback?()

     _send: (data) ->
      data = JSON.stringify data
      xhr = new XMLHttpRequest
      xhr.open 'POST', @url
      xhr.onreadystatechange = =>
       @_onRequest xhr
      xhr.setRequestHeader 'Accept', 'application/json'
      #xhr.setRequestHeader 'Content-Type', 'application/json'
      xhr.send data

     _handleResponse: (data, options, last = true) ->
      for f in @wrappers.handleResponse
       return unless f.apply this, arguments
      if not @callsCache[data.id]?
       @errorCallback "Response without call: #{data.id}", data
       return
      call = @callsCache[data.id]
      try
       if call.handle data.data, data
        delete @callsCache[data.id]
       else if last
        params =
         type: 'poll'
         id: call.id
        params[k] = v for k, v of call.options
        @_send params
      catch e
       @errorCallback e.message, data
       delete @callsCache[data.id]

##NodeHttpPort class

    class NodeHttpPort extends Port
     constructor: (options, http) ->
      super()
      @host = options.host ? 'localhost'
      @port = options.port ? 80
      @path = options.path ? '/'
      @http = http
      @_createHttpOptions()

     isStreaming: false

     _createHttpOptions: ->
      @httpOptions =
       hostname: @host
       port: @port
       path: @path
       method: 'POST'
       agent: false
       headers:
        accept: 'application/json'
       'content-type': 'application/json'

     _onRequest: (res) ->
      data = ''
      #LOG 'STATUS: ' + res.statusCode
      #LOG 'HEADERS: ' + JSON.stringify res.headers
      res.setEncoding 'utf8'
      res.on 'data', (chunk) ->
       data += chunk
      #LOG 'result', res
      res.on 'end', =>
       try
        jsonData = JSON.parse data
       catch e
        @onCallError 'ParseError', e
        return

       @_handleMessage jsonData, response: res

     _respond: (data, options, callback) ->
      data = JSON.stringify data
      res = options.response
      res.setHeader 'content-length', Buffer.byteLength data, 'utf8'
      if callback?
       res.once 'finish', ->
        callback()
       res.once 'close', ->
        callback()

      res.write data
      res.end()

     _send: (data, callbacks) ->
      data = JSON.stringify data
      options = @httpOptions
      options.headers['content-length'] = Buffer.byteLength data, 'utf8'

      req = @http.request options, @_onRequest.bind this
      delete options.headers['content-length']
      req.on 'error', (e) =>
       try
        callbacks.fail? e
       catch err
        @onerror? err

      req.write data
      req.end()

     _handleResponse: (data, options, last = true) ->
      for f in @wrappers.handleResponse
       return unless f.apply this, arguments
      if not @callsCache[data.id]?
       @errorCallback "Response without call: #{data.id}", data
       return
      call = @callsCache[data.id]
      if not call.handle data.data, data
       return if not last
       params =
        type: 'poll'
        id: call.id
       params[k] = v for k, v of call.options
       @_send params, call.callbacks

##NodeHttpServerPort class

    class NodeHttpServerPort extends Port
     constructor: (options, http, zlib = null) ->
      super()
      @port = options.port
      @http = http
      @zlib = zlib
      @allowOrigin = options.allowOrigin

     isStreaming: false

     _onRequest: (req, res) ->
      data = ''
      res.setHeader 'content-type', 'application/json'

      req.on 'data', (chunk) ->
       data += chunk
      req.on 'end', =>
       try
        jsonData = JSON.parse data
       catch e
        @errorCallback 'ParseError', e
        return

       @_handleMessage jsonData, response: res, request: req

     _respond: (data, options, callback) ->
      if @allowOrigin?
       options.response.setHeader 'Access-Control-Allow-Origin', @allowOrigin

      accept = options.request.headers['accept-encoding']
      accept ?= ''
      if not @zlib?
       accept = ''

      data = JSON.stringify data
      buffer = new Buffer data, 'utf8'
      if accept.match /\bgzip\b/
       options.response.setHeader 'content-encoding', 'gzip'
       @zlib.gzip buffer, (err, result) =>
        if err?
         return @errorCallback 'GZipeError', e
        @_sendBuffer result, options.response, callback
      else if accept.match /\bdeflate\b/
       options.response.setHeader 'content-encoding', 'deflate'
       @zlib.deflate buffer, (err, result) =>
        if err?
         return @errorCallback 'DeflateError', e
        @_sendBuffer result, options.response, callback
      else
       @_sendBuffer buffer, options.response, callback

     _sendBuffer: (buf, res, callback) ->
       res.setHeader 'content-length', buf.length
       if callback?
        res.once 'finish', ->
         callback()
        res.once 'close', ->
         callback()

       res.write buf
       res.end()

     listen: ->
      @server = @http.createServer @_onRequest.bind this
      @server.listen @port

     _handlePoll: (data, options) ->
      for f in @wrappers.handleCall
       return unless f.apply this, arguments
      if not @responses[data.id]?
       @onHandleError "Poll without response: #{data.id}", data, options
       return
      @responses[data.id].setOptions options

##NodeHttpsServerPort class

    class NodeHttpsServerPort extends NodeHttpServerPort
     constructor: (options, http) ->
      super options, http
      @_key = options.key
      @_cert = options.cert

     listen: ->
      options =
       key: @_key
       cert: @_cert

      @server = @http.createServer options, @_onRequest.bind this
      @server.listen @port

#IO Module

    IO =
     addPort: (name, port) ->
      IO[name] = port

     ports:
      WorkerPort: WorkerPort
      FramePort: FramePort
      SocketPort: SocketPort
      AjaxHttpPort: AjaxHttpPort
      NodeHttpPort: NodeHttpPort
      NodeHttpServerPort: NodeHttpServerPort
      NodeHttpsServerPort: NodeHttpsServerPort
      ServerSocketPort: ServerSocketPort

     Helpers:
      progress: (from, to, func) ->
       (progress, data) ->
        func? progress * (to - from) + from, data

     setup_____: (options) ->
      options.workers ?= []
      switch options.platform
       when 'ui'
        for worker in options.workers
         IO.addPort worker.name, new WorkerPort worker.js
        for socket in options.sockets
         IO.addPort socket.name, new SocketPort socket.url
       when 'node'
        for socket in options.listenSockets
         IO.addPort socket.name, new SocketListenPort socket.port
        for socket in options.sockets
         IO.addPort socket.name, new SocketPort socket.url
       when 'worker'
        IO.addPort 'UI', new WorkerListenPort _self

    if exports?
     module.exports = IO
    else
     _self.IO = IO