1 handler = (req, res) ->
2 reply_err = (req, res, msg) ->
3 res.writeHead(200, 'Content-Type': 'text/plain')
4 return res.end("Error loading #{req.url} \"#{msg}\"")
6 when '/', '/index.html'
7 filename = __dirname + '/index.html'
10 filename = '/usr/share/javascript/jquery/jquery.min.js'
11 type = 'text/javascript'
13 filename = __dirname + '/terminal.coffee'
14 type = 'text/javascript'
16 filename = __dirname + '/client.coffee'
17 type = 'text/javascript'
19 return reply_err req, res
20 fs.readFile filename, 'utf8', (err, data) ->
21 return reply_err req, res, err if err
23 if filename.substr(filename.length - 7) is '.coffee'
25 data = coffee.compile data
27 return reply_err req, res, "server faild to compile #{filename}: #{JSON.stringify(e)}"
29 res.writeHead(200, 'Content-Type': type)
32 coffee = require 'coffee-script'
33 app = require('http').createServer(handler)
34 io = require('socket.io').listen(app)
36 terminal = require('./terminal.coffee')
40 term = terminal.new(104, 34)
44 io.sockets.on 'connection', (socket) ->
46 socket.on 'disconnect', ->
47 for i in [i...sockets.length]
48 if sockets[i] is socket
53 enc_color = (prefix, c) ->
55 return "#{prefix}#{c}"
57 return "#{prefix + 6}#{c - 8}"
58 return "#{prefix}8;5;#{c}"
64 parts.push enc_color 3, (b & 0xff)
66 parts.push enc_color 4, ((b & 0xff00) >> 8)
67 for [bit, code] in [[0x010000, '1'], [0x200000, '3'], [0x020000, '4'], [0x040000, '5'], [0x080000, '7'], [0x100000, '8']]
74 return "\x1b[#{parts.join ';'}m"
77 encode_screen = (height, width, text, attributes) ->
81 while max >= 0 and text[y][max] is ' ' and (attributes[y][max] & 0x08ff00) is 0
85 if attributes[y][x] isnt a
86 state += attr_diff a, attributes[y][x]
95 if term.saved_normal_screen?
96 state += encode_screen term.height, term.width, term.saved_normal_screen.text, term.saved_normal_screen.attributes
97 state += "\x1b[#{term.saved_normal_screen.y + 1};#{term.saved_normal_screen.x + 1}H"
98 state += "\x1b[?1049h\x1b[H" # flip to alt screen and move cursor home
99 state += encode_screen term.height, term.width, term.text, term.attributes
100 state += attr_diff a, term.a
101 state += "\x1b[#{term.y + 1};#{term.x + 1}H"
102 unless term.cursor_visible
104 unless term.scroll_top is 0 and term.scroll_bottom is term.height - 1
105 state += "\x1b[#{term.scroll_top};#{term.scroll_bottom}r"
106 socket.emit 'init', width: term.width, height: term.height, text: state
108 process.stdin.resume()
109 process.stdin.setEncoding 'utf8'
111 process.stdin.on 'data', (data) ->
116 process.stdin.on 'end', -> process.exit()