6 if process.argv.length > 2
7 term_columns = parseInt process.argv[2]
8 if process.argv.length > 3
9 term_lines = parseInt process.argv[3]
12 handler = (req, res) ->
13 reply_err = (req, res, msg) ->
14 res.writeHead(200, 'Content-Type': 'text/plain')
15 return res.end("Error loading #{req.url} \"#{msg}\"")
17 when '/', '/index.html'
18 filename = __dirname + '/index.html'
21 filename = '/usr/share/javascript/jquery/jquery.min.js'
22 type = 'text/javascript'
24 filename = __dirname + '/terminal.coffee'
25 type = 'text/javascript'
27 filename = __dirname + '/htmlterm.coffee'
28 type = 'text/javascript'
30 filename = __dirname + '/client.coffee'
31 type = 'text/javascript'
33 return reply_err req, res
34 fs.readFile filename, 'utf8', (err, data) ->
35 return reply_err req, res, err if err
37 if filename.substr(filename.length - 7) is '.coffee'
39 data = coffee.compile data
41 return reply_err req, res, "server faild to compile #{filename}: #{JSON.stringify(e)}"
43 res.writeHead(200, 'Content-Type': type)
46 coffee = require 'coffee-script'
47 app = require('http').createServer(handler)
48 io = require('socket.io').listen(app)
50 terminal = require('./terminal.coffee')
53 term = terminal.new(term_columns, term_lines)
57 io.sockets.on 'connection', (socket) ->
59 socket.on 'disconnect', ->
60 for i in [i...sockets.length]
61 if sockets[i] is socket
66 enc_color = (prefix, c) ->
68 return "#{prefix}#{c}"
70 return "#{prefix + 6}#{c - 8}"
71 return "#{prefix}8;5;#{c}"
77 parts.push enc_color 3, (b & 0xff)
79 parts.push enc_color 4, ((b & 0xff00) >> 8)
80 for [bit, code] in [[0x010000, '1'], [0x200000, '3'], [0x020000, '4'], [0x040000, '5'], [0x080000, '7'], [0x100000, '8']]
87 return "\x1b[#{parts.join ';'}m"
90 encode_screen = (height, width, text, attributes) ->
94 while max >= 0 and text[y][max] is ' ' and (attributes[y][max] & 0x08ff00) is 0
98 if attributes[y][x] isnt a
99 state += attr_diff a, attributes[y][x]
108 if term.saved_normal_screen?
109 state += encode_screen term.height, term.width, term.saved_normal_screen.text, term.saved_normal_screen.attributes
110 state += "\x1b[#{term.saved_normal_screen.y + 1};#{term.saved_normal_screen.x + 1}H"
111 state += "\x1b[?1049h\x1b[H" # flip to alt screen and move cursor home
112 state += encode_screen term.height, term.width, term.text, term.attributes
113 state += attr_diff a, term.a
114 state += "\x1b[#{term.y + 1};#{term.x + 1}H"
115 unless term.cursor_visible
117 unless term.scroll_top is 0 and term.scroll_bottom is term.height - 1
118 state += "\x1b[#{term.scroll_top};#{term.scroll_bottom}r"
119 socket.emit 'init', width: term.width, height: term.height, text: state
121 process.stdin.resume()
122 process.stdin.setEncoding 'utf8'
124 process.stdin.on 'data', (data) ->
129 process.stdin.on 'end', -> process.exit()