7 handler = (req, res) ->
8 reply_err = (req, res, msg) ->
9 res.writeHead(200, 'Content-Type': 'text/plain')
10 return res.end("Error loading #{req.url} \"#{msg}\"")
12 when '/', '/index.html'
13 filename = __dirname + '/index.html'
16 filename = '/usr/share/javascript/jquery/jquery.min.js'
17 type = 'text/javascript'
19 filename = __dirname + '/terminal.coffee'
20 type = 'text/javascript'
22 filename = __dirname + '/client.coffee'
23 type = 'text/javascript'
25 return reply_err req, res
26 fs.readFile filename, 'utf8', (err, data) ->
27 return reply_err req, res, err if err
29 if filename.substr(filename.length - 7) is '.coffee'
31 data = coffee.compile data
33 return reply_err req, res, "server faild to compile #{filename}: #{JSON.stringify(e)}"
35 res.writeHead(200, 'Content-Type': type)
38 coffee = require 'coffee-script'
39 app = require('http').createServer(handler)
40 io = require('socket.io').listen(app)
42 terminal = require('./terminal.coffee')
45 term = terminal.new(term_columns, term_lines)
49 io.sockets.on 'connection', (socket) ->
51 socket.on 'disconnect', ->
52 for i in [i...sockets.length]
53 if sockets[i] is socket
58 enc_color = (prefix, c) ->
60 return "#{prefix}#{c}"
62 return "#{prefix + 6}#{c - 8}"
63 return "#{prefix}8;5;#{c}"
69 parts.push enc_color 3, (b & 0xff)
71 parts.push enc_color 4, ((b & 0xff00) >> 8)
72 for [bit, code] in [[0x010000, '1'], [0x200000, '3'], [0x020000, '4'], [0x040000, '5'], [0x080000, '7'], [0x100000, '8']]
79 return "\x1b[#{parts.join ';'}m"
82 encode_screen = (height, width, text, attributes) ->
86 while max >= 0 and text[y][max] is ' ' and (attributes[y][max] & 0x08ff00) is 0
90 if attributes[y][x] isnt a
91 state += attr_diff a, attributes[y][x]
100 if term.saved_normal_screen?
101 state += encode_screen term.height, term.width, term.saved_normal_screen.text, term.saved_normal_screen.attributes
102 state += "\x1b[#{term.saved_normal_screen.y + 1};#{term.saved_normal_screen.x + 1}H"
103 state += "\x1b[?1049h\x1b[H" # flip to alt screen and move cursor home
104 state += encode_screen term.height, term.width, term.text, term.attributes
105 state += attr_diff a, term.a
106 state += "\x1b[#{term.y + 1};#{term.x + 1}H"
107 unless term.cursor_visible
109 unless term.scroll_top is 0 and term.scroll_bottom is term.height - 1
110 state += "\x1b[#{term.scroll_top};#{term.scroll_bottom}r"
111 socket.emit 'init', width: term.width, height: term.height, text: state
113 process.stdin.resume()
114 process.stdin.setEncoding 'utf8'
116 process.stdin.on 'data', (data) ->
121 process.stdin.on 'end', -> process.exit()