JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
run.sh: complain if not passed width/height
[watch-my-terminal.git] / terminal.coffee
1 # this file is used by the client and server.
2
3 # work around lack of module system in the browser:
4 if exports?
5         my_exports = exports
6 else
7         window.terminal = {}
8         my_exports = window.terminal
9
10 if console?.log?
11         log = -> console.log arguments...
12 else
13         log = -> null
14
15 alternate_charset_table = {
16         A: "↑"
17         B: "↓"
18         C: "→"
19         D: "←"
20         E: "█"
21         F: "▚"
22         G: "☃"
23         '_': " "
24         '`': "◆"
25         a: "▒"
26         b: "␉"
27         c: "␌"
28         d: "␍"
29         e: "␊"
30         f: "°"
31         g: "±"
32         h: "␤"
33         i: "␋"
34         j: "┘"
35         k: "┐"
36         l: "┌"
37         m: "└"
38         n: "┼"
39         o: "⎺"
40         p: "⎻"
41         q: "─"
42         r: "⎼"
43         s: "⎽"
44         t: "├"
45         u: "┤"
46         v: "┴"
47         w: "┬"
48         x: "│"
49         y: "≤"
50         z: "≥"
51         '{': "π"
52         '|': "≠"
53         '}': "£"
54         '~': "·"
55 }
56
57 class Terminal
58         # public:
59         constructor: (width, height) ->
60                 @width = 1
61                 @height = 1
62                 @text = []
63                 @attributes = []
64                 @x = 0
65                 @y = 0
66                 @a = 0x000007 # cursor attributes
67                 @partial = ''
68                 @saved_normal_screen = null
69                 @cursor_visible = true
70                 @scroll_top = 0
71                 @scroll_bottom = height - 1
72                 @resize width, height
73
74         resize: (width, height) ->
75                 # FIXME: write a version that retains some of the data
76                 # FIXME: clamp variables (eg x, y, saved.*, scrolling region) if getting smaller
77                 @width = width
78                 @height = height
79                 @text = []
80                 @attributes = []
81                 for y in [0...height]
82                         @text[y] = []
83                         @attributes[y] = []
84                         for x in [0...width]
85                                 @text[y].push ' '
86                                 @attributes[y].push 0x07
87
88         # pass data from stdout
89         update: (data) ->
90                 return unless data?.length > 0
91                 if @partial.length > 0
92                         data = @partial + data
93                         @partial = ''
94                 parts = data.split(/\x1b/)
95                 if parts.length > 1
96                         if -1 is @escape_sequence_length parts[parts.length - 1]
97                                 @partial = parts.pop()
98                 for i in [0...parts.length]
99                         if i is 0
100                                 @update_text parts[i]
101                         else
102                                 @update_sequence_then_text parts[i]
103                 return
104
105         add_new_line: ->
106                 # clear the line at the top of the scrolling region
107                 for i in [0...@width]
108                         @text[@scroll_top][i] = ' '
109                         @attributes[@scroll_top][i] = 0x07
110
111                 rearrange = (a) =>
112                         return [
113                                 a[0...@scroll_top]..., # up to but not including scroll top
114                                 a[@scroll_top + 1 .. @scroll_bottom]..., # scroll region except top line of it
115                                 a[@scroll_top], # top line of scroll region (already cleared)
116                                 a[@scroll_bottom + 1 ... @height]... # rest of screen
117                         ]
118                 @text = rearrange @text
119                 @attributes = rearrange @attributes
120
121                 # slide cursor up with rest of text
122                 @y -= 1
123
124         wrap_to_next_line: ->
125                 if @y is @scroll_bottom
126                         @add_new_line()
127                 @y += 1
128                 @x = 0
129
130         # str has no escape sequences
131         update_text: (str) ->
132                 return unless str.length > 0
133                 for c in str
134                         switch c
135                                 when '\t' # tab
136                                         @update_text "        ".substr(@x % 8)
137                                 when '\x07' # bell
138                                         false
139                                 when '\x0d' # cr
140                                         @x = 0
141                                 when '\x08' # backspace
142                                         if @x is 0
143                                                 @x = @width - 1
144                                                 if @y > 0
145                                                         @y -= 1
146                                         else
147                                                 @x -= 1
148                                 when '\x0a', '\x0b' # lf, vertical tab (same thing)
149                                         @wrap_to_next_line()
150                                 when '\x0f'
151                                         @alternate_charset = true
152                                 when '\x0e'
153                                         @alternate_charset = false
154                                 else
155                                         if @x >= @width
156                                                 @wrap_to_next_line()
157                                         if @alternate_charset
158                                                 if alternate_charset_table[c]?
159                                                         c = alternate_charset_table[c]
160                                         @text[@y][@x] = c
161                                         @attributes[@y][@x] = @a
162                                         @x += 1
163                 return
164
165         set_attribute_bits: (mask, value) ->
166                 @a = ((@a & ~mask) | value)
167
168         # we're supposed to ignore leeding zeros, and while we're at it, lets swap
169         # in the default for blank or missing values
170         fix_esc_arg: (value, deef_alt) ->
171                 if value? and value != ''
172                         while value[0] is '0' and value.length > 1
173                                 value = value.substr 1
174                         return value
175                 else
176                         return deef_alt
177
178         # csi_@: rxvt does nothing I can detect
179
180         # "The auxiliary keypad keys will send ASCII codes corresponding to the
181         # characters engraved on their keys." (numlock?)
182         "esc_>": ->
183
184         # move cursor up
185         csi_A: (lines) ->
186                 lines = parseInt @fix_esc_arg lines, '1'
187                 @y -= lines
188                 if @y < 0
189                         @y = 0
190                 return
191
192         # move cursor down
193         csi_B: (lines) ->
194                 lines = parseInt @fix_esc_arg lines, '1'
195                 @y += lines
196                 if @y >= @height
197                         @y = @height - 1
198                 return
199
200         # move cursor right
201         csi_C: (cols) ->
202                 cols = parseInt @fix_esc_arg cols, '1'
203                 @x += cols
204                 if @x >= @width
205                         @x = @width - 1
206                 return
207
208         # move cursor left
209         csi_D: (cols) ->
210                 cols = parseInt @fix_esc_arg cols, '1'
211                 @x -= cols
212                 if @x < 0
213                         @x = 0
214                 return
215
216         # cursor set_row (y)
217         csi_d: (row) ->
218                 row = -1 + parseInt @fix_esc_arg row, '1'
219                 @set_row_clamped row
220                 return
221
222         # cursor column (x)
223         csi_G: (col) ->
224                 col = -1 + parseInt @fix_esc_arg col, '1'
225                 @set_column_clamped col
226                 return
227
228         # set cursor row (zero based)
229         set_row_clamped: (row) ->
230                 if row < 0
231                         row = 0
232                 if row >= @height
233                         row = @height - 1
234                 @y = row
235                 return
236         # set cursor column (zero based)
237         set_column_clamped: (column) ->
238                 if column < 0
239                         column = 0
240                 if column >= @width
241                         column = @width - 1
242                 @x = column
243                 return
244         # set cursor position (one based)
245         csi_H: (row, column) ->
246                 # handle blank/missing args and convert to 0 base
247                 row = -1 + parseInt @fix_esc_arg row, '1'
248                 column = -1 + parseInt @fix_esc_arg column, '1'
249                 @set_row_clamped row
250                 @set_column_clamped column
251                 return
252
253         # clear to screen edge(es)
254         csi_J: (direction) ->
255                 switch @fix_esc_arg direction, '0'
256                         when '0' # erase down
257                                 # rest of current line
258                                 @csi_K direction
259                                 # rest of lines
260                                 for row in [@y...@height]
261                                         for i in [0...@width]
262                                                 @text[row][i] = ' '
263                                                 @attributes[row][i] = @a
264                         when '1' # erase up
265                                 # beginning of current line
266                                 @csi_K direction
267                                 # all previous lines
268                                 for row in [0..@y]
269                                         for i in [0...@width]
270                                                 @text[row][i] = ' '
271                                                 @attributes[row][i] = @a
272                         when '2' # erase everything
273                                 for row in [0...@height]
274                                         for i in [0...@width]
275                                                 @text[row][i] = ' '
276                                                 @attributes[row][i] = @a
277                         else
278                                 log "confusing arg for csi_J: #{direction}"
279                 return
280
281         # clear (some or all of) current line
282         csi_K: (direction) ->
283                 switch @fix_esc_arg direction, '0'
284                         when '0' # erase to right
285                                 for i in [@x...@width]
286                                         @text[@y][i] = ' '
287                                         @attributes[@y][i] = @a
288                         when '1' # erase to left
289                                 # @x can equal @width (after printing to right-most column)
290                                 if @x < @width
291                                         max = @x
292                                 else
293                                         max = @width - 1
294                                 for i in [0..max]
295                                         @text[@y][i] = ' '
296                                         @attributes[@y][i] = @a
297                         when '2' # erase whole line
298                                 for i in [0...@width]
299                                         @text[@y][i] = ' '
300                                         @attributes[@y][i] = @a
301                         else
302                                 log "confusing arg for csi_K: #{direction}"
303                 return
304
305         # move lines downwards (arg is how far)
306         csi_L: (lines) ->
307                 lines = parseInt @fix_esc_arg lines, '1'
308
309                 rearrange = (a) =>
310                         return [
311                                 a[0...@y]..., # keep everything above cursor
312                                 a[@scroll_bottom - lines + 1 .. @scroll_bottom]..., # we'll clear these shortly
313                                 a[@y..@scroll_bottom - lines]..., # lines that are moving down
314                                 a[@scroll_bottom + 1 ... @height]... # rest of screen
315                         ]
316                 @text = rearrange @text
317                 @attributes = rearrange @attributes
318
319                 # clear the lines we scrolled off (and put back in as "new")
320                 for y in [@y...@y+lines]
321                         for x in [0...@width]
322                                 @text[y][x] = ' '
323                                 @attributes[y][x] = 0x07
324
325         # move lines upwards (arg is how far)
326         # this obliterates the line under the cursor and arg-1 following it
327         csi_M: (lines) ->
328                 lines = parseInt @fix_esc_arg lines, '1'
329
330                 rearrange = (a) =>
331                         return [
332                                 a[0 ... @y]..., # keep everything above cursor
333                                 a[@y + lines .. @scroll_bottom]..., # lines we're moving up
334                                 a[@y ... @y + lines]..., # recycle these
335                                 a[@scroll_bottom + 1 ... @height]... # keep the rest
336                         ]
337                 @text = rearrange @text
338                 @attributes = rearrange @attributes
339
340                 # clear the lines we're recycling
341                 for y in [@scroll_bottom - lines + 1 .. @scroll_bottom]
342                         for x in [0...@width]
343                                 @text[y][x] = ' '
344                                 @attributes[y][x] = 0x07
345
346         # delete chars (without moving the cursor)
347         csi_X: (chars) ->
348                 chars = parseInt @fix_esc_arg chars, '1'
349                 x = @x
350                 for c in [0...chars]
351                         if x >= @width
352                                 return
353                         @text[@y][x] = ' '
354                         @attributes[@y][x] = @a
355                         x += 1
356                 return
357         "csi_@": (chars) ->
358                 chars = parseInt @fix_esc_arg chars, '1'
359                 if chars < 1
360                         return
361                 if chars > @width - @x
362                         chars = @width - @x
363                 else
364                         dest = @width - 1
365                         if dest >= @width
366                                 dest = @width - 1
367                         while dest - chars >= @x
368                                 @text[@y][dest] = @text[@y][dest - chars]
369                                 @attributes[@y][dest] = @attributes[@y][dest - chars]
370                                 dest -= 1
371                 @csi_X chars # clear
372         csi_P: (chars) ->
373                 chars = parseInt @fix_esc_arg chars, '1'
374                 if chars < 1
375                         return
376                 if chars > @width - @x
377                         chars = @width - @x
378                 else
379                         dest = @x
380                         while dest < @width - chars
381                                 @text[@y][dest] = @text[@y][dest + chars]
382                                 @attributes[@y][dest] = @attributes[@y][dest + chars]
383                                 dest += 1
384                 # clear the space moved out of
385                 x = @width - chars
386                 while x < @width
387                         @text[@y][x] = ' '
388                         @attributes[@y][x] = @a
389                         x += 1
390
391         # set modes not starting with "?"
392         csi_h: (args...) ->
393                 for i in args
394                         arg = @fix_esc_arg i, ''
395                         switch arg
396                                 when '0' # error (ignored
397                                         return
398                                 when '2' # KAM -- keyboard action
399                                         return
400                                 when '4' # put cursor in "INSERT" mode
401                                         return
402                                 when '12' # turn local echo off (or on?)
403                                         return
404                                 # TODO when '20' LNM linefeed/newline
405                                 else
406                                         log "Unimplemented arg for csi_h: #{arg}"
407         # set modes starting with "?"
408         csiq_h: (args...) ->
409                 for i in args
410                         arg = @fix_esc_arg i, ''
411                         switch arg
412                                 when '1' # mode ?1
413                                         # numlock on
414                                         return
415                                 when '25'
416                                         @cursor_visible = true
417                                 when '1000'
418                                         # x11 normal mouse tracking
419                                         return
420                                 when '1049'
421                                         if @saved_normal_screen?
422                                                 log "ignoring request to switch to the alt screen because we're already on the alt screen"
423                                                 return
424                                         @saved_normal_screen = x: @x, y: @y, text: @text, attributes: @attributes
425                                         @text = []
426                                         @attributes = []
427                                         for y in [0...@height]
428                                                 @text[y] = []
429                                                 @attributes[y] = []
430                                                 for x in [0...@width]
431                                                         @text[y].push ' '
432                                                         @attributes[y].push 0x07
433                                 else
434                                         log "Unimplemented arg for csiq_h: #{arg}"
435                 return
436
437         # reset (turn off) modes
438         # note that modes starting with ? call csiq_l, not this
439         csi_l: ->
440                 for i in arguments
441                         arg = @fix_esc_arg i, ''
442                         switch arg
443                                 when '0' # error (ignored
444                                         return
445                                 when '2' # KAM -- keyboard action
446                                         return
447                                 when '4' # put cursor in "REPLACE" mode
448                                         return
449                                 when '12' # turn local echo on (or off?)
450                                         return
451                                 # TODO when '20' LNM linefeed/newline
452
453         # reset (turn off) modes starting with ?
454         # in st source, these are priv=true
455         csiq_l: ->
456                 args = []
457                 for i in arguments
458                         arg = @fix_esc_arg i, ''
459                         switch arg
460                                 when '1' # mode ?1 reset
461                                         # numlock off
462                                         return
463                                 when '12' # mode ?12
464                                         # stop blinking the cursor (ignored)
465                                         return
466                                 when '25' # mode ?25 reset
467                                         @cursor_visible = false
468                                 when '0', '2', '3', '4', '8', '18', '19', '42', '12'
469                                         # st ignores all of these
470                                         return
471                                 when '9', '1000', '1002', '1003', '1004', '1006'
472                                         # mouse reporting and such (ignored)
473                                         return
474                                 when '1049'
475                                         if not @saved_normal_screen?
476                                                 log "ignoring request to switch to the normal screen because we're already on the normal screen"
477                                                 return
478                                         @x = @saved_normal_screen.x
479                                         @y = @saved_normal_screen.y
480                                         @text = @saved_normal_screen.text
481                                         @attributes = @saved_normal_screen.attributes
482                                         @saved_normal_screen = null
483                                 else
484                                         log "Unimplemented arg for csiq_l: #{arg}"
485                 return
486
487         # set color, bold, underline, etc
488         csi_m: ->
489                 args = []
490                 for i in arguments
491                         args.push @fix_esc_arg i, '0'
492
493                 while args.length > 0
494                         arg = args.shift()
495                         switch arg
496                                 # remove all style/color
497                                 when '0'
498                                         @a = 0x07
499
500                                 # style attributes
501                                 when '1' # bold
502                                         @set_attribute_bits 0x010000, 0x010000
503                                 when '3' # italic (rare)
504                                         @set_attribute_bits 0x200000, 0x200000
505                                 when '4' # underline
506                                         @set_attribute_bits 0x020000, 0x020000
507                                 when '5' # blink
508                                         @set_attribute_bits 0x040000, 0x040000
509                                 when '7' # inverse
510                                         @set_attribute_bits 0x080000, 0x080000
511                                 when '8' # invisible. urivt ignores this
512                                         @set_attribute_bits 0x100000, 0x100000
513
514                                 # disable style attributes
515                                 when '21' # not bold (rare)
516                                         @set_attribute_bits 0x010000, 0
517                                 when '22' # not bold
518                                         @set_attribute_bits 0x010000, 0
519                                 when '23' # not italic (rare)
520                                         @set_attribute_bits 0x200000, 0
521                                 when '24' # not underline
522                                         @set_attribute_bits 0x020000, 0
523                                 when '25' # not blink
524                                         @set_attribute_bits 0x040000, 0
525                                 when '27' # not inverse
526                                         @set_attribute_bits 0x080000, 0
527                                 when '28' # not invisible
528                                         @set_attribute_bits 0x100000, 0
529
530                                 when '100' # reset colors but not other attributes
531                                         @set_attribute_bits 0xffff, 0x0007
532
533                                 # 8 fg colors
534                                 when '30' # fg black
535                                         @set_attribute_bits 0xff, 0x00
536                                 when '31' # fg red
537                                         @set_attribute_bits 0xff, 0x01
538                                 when '32' # fg green
539                                         @set_attribute_bits 0xff, 0x02
540                                 when '33' # fg yellow
541                                         @set_attribute_bits 0xff, 0x03
542                                 when '34' # fg blue
543                                         @set_attribute_bits 0xff, 0x04
544                                 when '35' # fg magenta
545                                         @set_attribute_bits 0xff, 0x05
546                                 when '36' # fg cyan
547                                         @set_attribute_bits 0xff, 0x06
548                                 when '37', '39' # fg white  (39 is default)
549                                         @set_attribute_bits 0xff, 0x07
550
551                                 when '38'
552                                         if args.length >= 2 and args[0] is '5'
553                                                 args.shift()
554                                                 @set_attribute_bits 0xff, (0xff & args.shift())
555                                         else
556                                                 @set_attribute_bits 0x20000, 0x20000
557
558                                 # 8 bg colors
559                                 when '40' # bg black
560                                         @set_attribute_bits 0xff00, 0x0000
561                                 when '41' # bg red
562                                         @set_attribute_bits 0xff00, 0x0100
563                                 when '42' # bg green
564                                         @set_attribute_bits 0xff00, 0x0200
565                                 when '43' # bg yellow
566                                         @set_attribute_bits 0xff00, 0x0300
567                                 when '44' # bg blue
568                                         @set_attribute_bits 0xff00, 0x0400
569                                 when '45' # bg magenta
570                                         @set_attribute_bits 0xff00, 0x0500
571                                 when '46' # bg cyan
572                                         @set_attribute_bits 0xff00, 0x0600
573                                 when '47' # bg white
574                                         @set_attribute_bits 0xff00, 0x0700
575                                 when '49' # bg default
576                                         @set_attribute_bits 0xff00, 0x0000
577
578                                 when '48'
579                                         if args.length >= 2 and args[0] is '5'
580                                                 args.shift()
581                                                 @set_attribute_bits 0xff00, ((0xff & args.shift()) << 8)
582                                         else
583                                                 @set_attribute_bits 0x20000, 0x20000
584
585                                 # bright fg colors
586                                 when '90' # fg bright black
587                                         @set_attribute_bits 0xff, 0x08
588                                 when '91' # fg bright red
589                                         @set_attribute_bits 0xff, 0x09
590                                 when '92' # fg bright green
591                                         @set_attribute_bits 0xff, 0x0a
592                                 when '93' # fg bright yellow
593                                         @set_attribute_bits 0xff, 0x0b
594                                 when '94' # fg bright blue
595                                         @set_attribute_bits 0xff, 0x0c
596                                 when '95' # fg bright magenta
597                                         @set_attribute_bits 0xff, 0x0d
598                                 when '96' # fg bright cyan
599                                         @set_attribute_bits 0xff, 0x0e
600                                 when '97' # fg bright white
601                                         @set_attribute_bits 0xff, 0x0f
602
603                                 # bright bg colors
604                                 when '100' # bg bright black
605                                         @set_attribute_bits 0xff00, 0x0800
606                                 when '101' # bg bright red
607                                         @set_attribute_bits 0xff00, 0x0900
608                                 when '102' # bg bright green
609                                         @set_attribute_bits 0xff00, 0x0a00
610                                 when '103' # bg bright yellow
611                                         @set_attribute_bits 0xff00, 0x0b00
612                                 when '104' # bg bright blue
613                                         @set_attribute_bits 0xff00, 0x0c00
614                                 when '105' # bg bright magenta
615                                         @set_attribute_bits 0xff00, 0x0d00
616                                 when '106' # bg bright cyan
617                                         @set_attribute_bits 0xff00, 0x0e00
618                                 when '107' # bg bright white
619                                         @set_attribute_bits 0xff00, 0x0f00
620
621                                 else
622                                         # if we don't recognize the style, go back to default
623                                         log "unrecognized csi_m arg: \"#{arg}\""
624                                         @a = 0
625                 return
626
627         # set scroll region
628         csi_r: (top, bottom) ->
629                 top = -1 + parseInt @fix_esc_arg top, '1'
630                 bottom = -1 + parseInt @fix_esc_arg bottom, '10000'
631                 if top < 0
632                         top = 0
633                 if bottom >= @height
634                         bottom = @height - 1
635                 @scroll_top = top
636                 @scroll_bottom = bottom
637                 return
638
639         # move cursor up one line, if it's at the top, scroll everything down
640         esc_M: ->
641                 if @y > 0
642                         @csi_A '1'
643                 else
644                         @csi_L '1'
645         
646         # esc ]
647         "esc_]": (seq) ->
648                 sem = seq.indexOf ';'
649                 if sem < 1 || seq[0] isnt '0'
650                         log "Unimplemented esc_] (OS command) sequence: #{seq}"
651                         return
652                 if window?
653                         title = seq.substr sem + 1
654                         title = title.substr 0, title.length - 1
655                         window.document.title = title
656
657         # "The auxiliary keypad keys will transmit control sequences."
658         "esc_=": ->
659
660         # esc )
661         "esc_)": ->
662                 @alternate_charset = true
663         # esc ( 0
664         gzd4_0: ->
665                 @alternate_charset = true
666         # esc ( B
667         gzd4_B: ->
668                 @alternate_charset = false
669
670         esc_n: ->
671                 @alternate_charset = false
672
673         esc_o: ->
674                 @alternate_charset = true
675
676         # str is the whole escape sequence (minus the esc character)
677         update_sequence: (str) ->
678                 if str[0] is '['
679                         if str[1] is '?'
680                                 method_prefix = 'csiq_'
681                                 args = str.substr(2, str.length - 3).split ';'
682                         else
683                                 method_prefix = 'csi_'
684                                 args = str.substr(1, str.length - 2).split ';'
685                         method_name = method_prefix + str.substr str.length - 1
686                 else if str[0] is '(' # character set
687                         method_name = 'gzd4_' + str.substr 1, 1
688                         args = [str.substr 1]
689                 else
690                         method_name = 'esc_' + str.substr 0, 1
691                         args = [str.substr 1]
692                 method = @[method_name]
693                 if not method?
694                         log "Unimplemented #{method_name}, code: ESC#{str}"
695                         return
696                 method.apply this, args
697
698         update_sequence_then_text: (str) ->
699                 len = @escape_sequence_length str
700                 if len is -1
701                         log "couldn't find escape sequence here: #{str.substr 0, 25}"
702                         @update_text "ESC" + str
703                 else
704                         @update_sequence str.substr 0, len
705                         @update_text str.substr len
706
707         escape_sequence_length: (str) ->
708                 if str[0] is '['
709                         parts = str.match(/^\[[0-9;?]{0,25}./)
710                         return -1 unless parts?
711                         return parts[0].length
712                 else if str[0] is '('
713                         if str.length == 1
714                                 return -1
715                         if str[1] is '!' or str[1] is '%'
716                                 return 3
717                         else
718                                 return 2
719                 else if str[0] is ']'
720                         st = str.indexOf "\u0007"
721                         if st is -1
722                                 return -1
723                         return st + 1
724                 else
725                         #log "non[: ESC#{str.substr 0, 10}"
726                         if str.length >= 1
727                                 return 1
728                         else
729                                 return -1
730
731 my_exports.new = (width, height) ->
732         return new Terminal width, height