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 + '/htmlterm.coffee'
23 type = 'text/javascript'
25 filename = __dirname + '/client.coffee'
26 type = 'text/javascript'
28 return reply_err req, res
29 fs.readFile filename, 'utf8', (err, data) ->
30 return reply_err req, res, err if err
32 if filename.substr(filename.length - 7) is '.coffee'
34 data = coffee.compile data
36 return reply_err req, res, "server faild to compile #{filename}: #{JSON.stringify(e)}"
38 res.writeHead(200, 'Content-Type': type)
41 coffee = require 'coffee-script'
42 app = require('http').createServer(handler)
43 io = require('socket.io').listen(app)
45 terminal = require('./terminal.coffee')
48 term = terminal.new(term_columns, term_lines)
52 io.sockets.on 'connection', (socket) ->
54 socket.on 'disconnect', ->
55 for i in [i...sockets.length]
56 if sockets[i] is socket
61 enc_color = (prefix, c) ->
63 return "#{prefix}#{c}"
65 return "#{prefix + 6}#{c - 8}"
66 return "#{prefix}8;5;#{c}"
72 parts.push enc_color 3, (b & 0xff)
74 parts.push enc_color 4, ((b & 0xff00) >> 8)
75 for [bit, code] in [[0x010000, '1'], [0x200000, '3'], [0x020000, '4'], [0x040000, '5'], [0x080000, '7'], [0x100000, '8']]
82 return "\x1b[#{parts.join ';'}m"
85 encode_screen = (height, width, text, attributes) ->
89 while max >= 0 and text[y][max] is ' ' and (attributes[y][max] & 0x08ff00) is 0
93 if attributes[y][x] isnt a
94 state += attr_diff a, attributes[y][x]
103 if term.saved_normal_screen?
104 state += encode_screen term.height, term.width, term.saved_normal_screen.text, term.saved_normal_screen.attributes
105 state += "\x1b[#{term.saved_normal_screen.y + 1};#{term.saved_normal_screen.x + 1}H"
106 state += "\x1b[?1049h\x1b[H" # flip to alt screen and move cursor home
107 state += encode_screen term.height, term.width, term.text, term.attributes
108 state += attr_diff a, term.a
109 state += "\x1b[#{term.y + 1};#{term.x + 1}H"
110 unless term.cursor_visible
112 unless term.scroll_top is 0 and term.scroll_bottom is term.height - 1
113 state += "\x1b[#{term.scroll_top};#{term.scroll_bottom}r"
114 socket.emit 'init', width: term.width, height: term.height, text: state
116 process.stdin.resume()
117 process.stdin.setEncoding 'utf8'
119 process.stdin.on 'data', (data) ->
124 process.stdin.on 'end', -> process.exit()