]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - macosx/osxwin.m
361f548f246f361e6397e270c3cacc7833b4f640
[PuTTY.git] / macosx / osxwin.m
1 /*
2  * osxwin.m: code to manage a session window in Mac OS X PuTTY.
3  */
4
5 #import <Cocoa/Cocoa.h>
6 #include "putty.h"
7 #include "terminal.h"
8 #include "osxclass.h"
9
10 /* Colours come in two flavours: configurable, and xterm-extended. */
11 #define NCFGCOLOURS (lenof(((Config *)0)->colours))
12 #define NEXTCOLOURS 240 /* 216 colour-cube plus 24 shades of grey */
13 #define NALLCOLOURS (NCFGCOLOURS + NEXTCOLOURS)
14
15 /*
16  * The key component of the per-session data is the SessionWindow
17  * class. A pointer to this is used as the frontend handle, to be
18  * passed to all the platform-independent subsystems that require
19  * one.
20  */
21
22 @interface TerminalView : NSImageView
23 {
24     NSFont *font;
25     NSImage *image;
26     Terminal *term;
27     Config cfg;
28     NSColor *colours[NALLCOLOURS];
29     float fw, fasc, fdesc, fh;
30 }
31 - (void)drawStartFinish:(BOOL)start;
32 - (void)setColour:(int)n r:(float)r g:(float)g b:(float)b;
33 - (void)doText:(wchar_t *)text len:(int)len x:(int)x y:(int)y
34     attr:(unsigned long)attr lattr:(int)lattr;
35 @end
36
37 @implementation TerminalView
38 - (BOOL)isFlipped
39 {
40     return YES;
41 }
42 - (id)initWithTerminal:(Terminal *)aTerm config:(Config)aCfg
43 {
44     float w, h;
45
46     self = [self initWithFrame:NSMakeRect(0,0,100,100)];
47
48     term = aTerm;
49     cfg = aCfg;
50
51     /*
52      * Initialise the fonts we're going to use.
53      * 
54      * FIXME: for the moment I'm sticking with exactly one default font.
55      */
56     font = [NSFont userFixedPitchFontOfSize:0];
57
58     /*
59      * Now determine the size of the primary font.
60      * 
61      * FIXME: If we have multiple fonts, we may need to set fasc
62      * and fdesc to the _maximum_ asc and desc out of all the
63      * fonts, _before_ adding them together to get fh.
64      */
65     fw = [font widthOfString:@"A"];
66     fasc = [font ascender];
67     fdesc = -[font descender];
68     fh = fasc + fdesc;
69     fh = (int)fh + (fh > (int)fh);     /* round up, ickily */
70
71     /*
72      * Use this to figure out the size of the terminal view.
73      */
74     w = fw * term->cols;
75     h = fh * term->rows;
76
77     /*
78      * And set our size and subimage.
79      */
80     image = [[NSImage alloc] initWithSize:NSMakeSize(w,h)];
81     [image setFlipped:YES];
82     [self setImage:image];
83     [self setFrame:NSMakeRect(0,0,w,h)];
84
85     term_invalidate(term);
86
87     return self;
88 }
89 - (void)drawStartFinish:(BOOL)start
90 {
91     if (start)
92         [image lockFocus];
93     else
94         [image unlockFocus];
95 }
96 - (void)doText:(wchar_t *)text len:(int)len x:(int)x y:(int)y
97     attr:(unsigned long)attr lattr:(int)lattr
98 {
99     int nfg, nbg, rlen, widefactor;
100     float ox, oy, tw, th;
101     NSDictionary *attrdict;
102
103     /* FIXME: TATTR_COMBINING */
104
105     nfg = ((attr & ATTR_FGMASK) >> ATTR_FGSHIFT);
106     nbg = ((attr & ATTR_BGMASK) >> ATTR_BGSHIFT);
107     if (attr & ATTR_REVERSE) {
108         int t = nfg;
109         nfg = nbg;
110         nbg = t;
111     }
112     if (cfg.bold_colour && (attr & ATTR_BOLD)) {
113         if (nfg < 16) nfg |= 8;
114         else if (nfg >= 256) nfg |= 1;
115     }
116     if (cfg.bold_colour && (attr & ATTR_BLINK)) {
117         if (nbg < 16) nbg |= 8;
118         else if (nbg >= 256) nbg |= 1;
119     }
120     if (attr & TATTR_ACTCURS) {
121         nfg = 260;
122         nbg = 261;
123     }
124
125     if (attr & ATTR_WIDE) {
126         widefactor = 2;
127         /* FIXME: what do we actually have to do about wide characters? */
128     } else {
129         widefactor = 1;
130     }
131
132     /* FIXME: ATTR_BOLD without cfg.bold_colour */
133
134     if ((lattr & LATTR_MODE) != LATTR_NORM) {
135         x *= 2;
136         if (x >= term->cols)
137             return;
138         if (x + len*2*widefactor > term->cols)
139             len = (term->cols-x)/2/widefactor;/* trim to LH half */
140         rlen = len * 2;
141     } else
142         rlen = len;
143
144     /* FIXME: how do we actually implement double-{width,height} lattrs? */
145
146     ox = x * fw;
147     oy = y * fh;
148     tw = rlen * widefactor * fw;
149     th = fh;
150
151     /*
152      * Set the clipping rectangle.
153      */
154     [[NSGraphicsContext currentContext] saveGraphicsState];
155     [NSBezierPath clipRect:NSMakeRect(ox, oy, tw, th)];
156
157     attrdict = [NSDictionary dictionaryWithObjectsAndKeys:
158                 colours[nfg], NSForegroundColorAttributeName,
159                 colours[nbg], NSBackgroundColorAttributeName,
160                 font, NSFontAttributeName, nil];
161
162     /*
163      * Create an NSString and draw it.
164      * 
165      * Annoyingly, although our input is wchar_t which is four
166      * bytes wide on OS X and terminal.c supports 32-bit Unicode,
167      * we must convert into the two-byte type `unichar' to store in
168      * NSString, so we lose display capability for extra-BMP stuff
169      * at this point.
170      */
171     {
172         NSString *string;
173         unichar *utext;
174         int i;
175
176         utext = snewn(len, unichar);
177         for (i = 0; i < len; i++)
178             utext[i] = (text[i] >= 0x10000 ? 0xFFFD : text[i]);
179
180         string = [NSString stringWithCharacters:utext length:len];
181         [string drawAtPoint:NSMakePoint(ox, oy) withAttributes:attrdict];
182
183         sfree(utext);
184     }
185
186     /*
187      * Restore the graphics state from before the clipRect: call.
188      */
189     [[NSGraphicsContext currentContext] restoreGraphicsState];
190
191     /*
192      * And flag this area as needing display.
193      */
194     [self setNeedsDisplayInRect:NSMakeRect(ox, oy, tw, th)];
195 }
196
197 - (void)setColour:(int)n r:(float)r g:(float)g b:(float)b
198 {
199     assert(n >= 0 && n < lenof(colours));
200     colours[n] = [[NSColor colorWithDeviceRed:r green:g blue:b alpha:1.0]
201                   retain];
202 }
203 @end
204
205 @implementation SessionWindow
206 - (id)initWithConfig:(Config)aCfg
207 {
208     NSRect rect = { {0,0}, {0,0} };
209
210     alert_ctx = NULL;
211
212     cfg = aCfg;                        /* structure copy */
213
214     init_ucs(&ucsdata, cfg.line_codepage, cfg.utf8_override,
215              CS_UTF8, cfg.vtmode);
216     term = term_init(&cfg, &ucsdata, self);
217     logctx = log_init(self, &cfg);
218     term_provide_logctx(term, logctx);
219     term_size(term, cfg.height, cfg.width, cfg.savelines);
220
221     termview = [[[TerminalView alloc] initWithTerminal:term config:cfg]
222                 autorelease];
223
224     /*
225      * Now work out the size of the window.
226      */
227     rect = [termview frame];
228     rect.origin = NSMakePoint(0,0);
229     rect.size.width += 2 * cfg.window_border;
230     rect.size.height += 2 * cfg.window_border;
231
232     /*
233      * Set up a backend.
234      */
235     {
236         int i;
237         back = &pty_backend;
238         for (i = 0; backends[i].backend != NULL; i++)
239             if (backends[i].protocol == cfg.protocol) {
240                 back = backends[i].backend;
241                 break;
242             }
243     }
244
245     {
246         const char *error;
247         char *realhost = NULL;
248         error = back->init(self, &backhandle, &cfg, cfg.host, cfg.port,
249                            &realhost, cfg.tcp_nodelay, cfg.tcp_keepalives);
250         if (error) {
251             fatalbox("%s\n", error);   /* FIXME: connection_fatal at worst */
252         }
253
254         if (realhost)
255             sfree(realhost);           /* FIXME: do something with this */
256     }
257     back->provide_logctx(backhandle, logctx);
258
259     /*
260      * Create a line discipline. (This must be done after creating
261      * the terminal _and_ the backend, since it needs to be passed
262      * pointers to both.)
263      */
264     ldisc = ldisc_create(&cfg, term, back, backhandle, self);
265
266     /*
267      * FIXME: Set up a scrollbar.
268      */
269
270     self = [super initWithContentRect:rect
271             styleMask:(NSTitledWindowMask | NSMiniaturizableWindowMask |
272                        NSClosableWindowMask)
273             backing:NSBackingStoreBuffered
274             defer:YES];
275     [self setTitle:@"PuTTY"];
276
277     [self setIgnoresMouseEvents:NO];
278
279     /*
280      * Put the terminal view in the window.
281      */
282     rect = [termview frame];
283     rect.origin = NSMakePoint(cfg.window_border, cfg.window_border);
284     [termview setFrame:rect];
285     [[self contentView] addSubview:termview];
286
287     /*
288      * Set up the colour palette.
289      */
290     palette_reset(self);
291
292     /*
293      * FIXME: Only the _first_ document window should be centred.
294      * The subsequent ones should appear down and to the right of
295      * it, probably using the cascade function provided by Cocoa.
296      * Also we're apparently required by the HIG to remember and
297      * reuse previous positions of windows, although I'm not sure
298      * how that works if the user opens more than one of the same
299      * session type.
300      */
301     [self center];                     /* :-) */
302
303     exited = FALSE;
304
305     return self;
306 }
307
308 - (void)dealloc
309 {
310     /*
311      * FIXME: Here we must deallocate all sorts of stuff: the
312      * terminal, the backend, the ldisc, the logctx, you name it.
313      * Do so.
314      */
315     sfree(alert_ctx);
316     if (back)
317         back->free(backhandle);
318     if (ldisc)
319         ldisc_free(ldisc);
320     /* ldisc must be freed before term, since ldisc_free expects term
321      * still to be around. */
322     if (logctx)
323         log_free(logctx);
324     if (term)
325         term_free(term);
326     [super dealloc];
327 }
328
329 - (void)drawStartFinish:(BOOL)start
330 {
331     [termview drawStartFinish:start];
332 }
333
334 - (void)setColour:(int)n r:(float)r g:(float)g b:(float)b
335 {
336     [termview setColour:n r:r g:g b:b];
337 }
338
339 - (void)doText:(wchar_t *)text len:(int)len x:(int)x y:(int)y
340     attr:(unsigned long)attr lattr:(int)lattr
341 {
342     /* Pass this straight on to the TerminalView. */
343     [termview doText:text len:len x:x y:y attr:attr lattr:lattr];
344 }
345
346 - (Config *)cfg
347 {
348     return &cfg;
349 }
350
351 - (void)keyDown:(NSEvent *)ev
352 {
353     NSString *s = [ev characters];
354     int i;
355     int n = [s length], c = [s characterAtIndex:0], m = [ev modifierFlags];
356     int cm = [[ev charactersIgnoringModifiers] characterAtIndex:0];
357     wchar_t output[32];
358     char coutput[32];
359     int use_coutput = FALSE, special = FALSE, start, end;
360
361 //printf("n=%d c=U+%04x cm=U+%04x m=%08x\n", n, c, cm, m);
362
363     /*
364      * FIXME: Alt+numberpad codes.
365      */
366
367     /*
368      * Shift and Ctrl with PageUp/PageDown for scrollback.
369      */
370     if (n == 1 && c == NSPageUpFunctionKey && (m & NSShiftKeyMask)) {
371         term_scroll(term, 0, -term->rows/2);
372         return;
373     }
374     if (n == 1 && c == NSPageUpFunctionKey && (m & NSControlKeyMask)) {
375         term_scroll(term, 0, -1);
376         return;
377     }
378     if (n == 1 && c == NSPageDownFunctionKey && (m & NSShiftKeyMask)) {
379         term_scroll(term, 0, +term->rows/2);
380         return;
381     }
382     if (n == 1 && c == NSPageDownFunctionKey && (m & NSControlKeyMask)) {
383         term_scroll(term, 0, +1);
384         return;
385     }
386
387     /*
388      * FIXME: Shift-Ins for paste? Or is that not Maccy enough?
389      */
390
391     /*
392      * FIXME: Alt (Option? Command?) prefix in general.
393      * 
394      * (Note that Alt-Shift-thing will work just by looking at
395      * charactersIgnoringModifiers; but Alt-Ctrl-thing will need
396      * processing properly, and Alt-as-in-Option won't happen at
397      * all. Hmmm.)
398      * 
399      * (Note also that we need to be able to override menu key
400      * equivalents before this is particularly useful.)
401      */
402     start = 1;
403     end = start;
404
405     /*
406      * Ctrl-` is the same as Ctrl-\, unless we already have a
407      * better idea.
408      */
409     if ((m & NSControlKeyMask) && n == 1 && cm == '`' && c == '`') {
410         output[1] = '\x1c';
411         end = 2;
412     }
413
414     /* We handle Return ourselves, because it needs to be flagged as
415      * special to ldisc. */
416     if (n == 1 && c == '\015') {
417         coutput[1] = '\015';
418         use_coutput = TRUE;
419         end = 2;
420         special = TRUE;
421     }
422
423     /* Control-Shift-Space is 160 (ISO8859 nonbreaking space) */
424     if (n == 1 && (m & NSControlKeyMask) && (m & NSShiftKeyMask) &&
425         cm == ' ') {
426         output[1] = '\240';
427         end = 2;
428     }
429
430     /* Control-2, Control-Space and Control-@ are all NUL. */
431     if ((m & NSControlKeyMask) && n == 1 &&
432         (cm == '2' || cm == '@' || cm == ' ') && c == cm) {
433         output[1] = '\0';
434         end = 2;
435     }
436
437     /* We don't let MacOS tell us what Backspace is! We know better. */
438     if (cm == 0x7F && !(m & NSShiftKeyMask)) {
439         coutput[1] = cfg.bksp_is_delete ? '\x7F' : '\x08';
440         end = 2;
441         use_coutput = special = TRUE;
442     }
443     /* For Shift Backspace, do opposite of what is configured. */
444     if (cm == 0x7F && (m & NSShiftKeyMask)) {
445         coutput[1] = cfg.bksp_is_delete ? '\x08' : '\x7F';
446         end = 2;
447         use_coutput = special = TRUE;
448     }
449
450     /* Shift-Tab is ESC [ Z. Oddly, this combination generates ^Y by
451      * default on MacOS! */
452     if (cm == 0x19 && (m & NSShiftKeyMask) && !(m & NSControlKeyMask)) {
453         end = 1;
454         output[end++] = '\033';
455         output[end++] = '[';
456         output[end++] = 'Z';
457     }
458
459     /*
460      * NetHack keypad mode.
461      */
462     if (cfg.nethack_keypad && (m & NSNumericPadKeyMask)) {
463         wchar_t *keys = NULL;
464         switch (cm) {
465           case '1': keys = L"bB"; break;
466           case '2': keys = L"jJ"; break;
467           case '3': keys = L"nN"; break;
468           case '4': keys = L"hH"; break;
469           case '5': keys = L".."; break;
470           case '6': keys = L"lL"; break;
471           case '7': keys = L"yY"; break;
472           case '8': keys = L"kK"; break;
473           case '9': keys = L"uU"; break;
474         }
475         if (keys) {
476             end = 2;
477             if (m & NSShiftKeyMask)
478                 output[1] = keys[1];
479             else
480                 output[1] = keys[0];
481             goto done;
482         }
483     }
484
485     /*
486      * Application keypad mode.
487      */
488     if (term->app_keypad_keys && !cfg.no_applic_k &&
489         (m & NSNumericPadKeyMask)) {
490         int xkey = 0;
491         switch (cm) {
492           case NSClearLineFunctionKey: xkey = 'P'; break;
493           case '=': xkey = 'Q'; break;
494           case '/': xkey = 'R'; break;
495           case '*': xkey = 'S'; break;
496             /*
497              * FIXME: keypad - and + need to be mapped to ESC O l
498              * and ESC O k, or ESC O l and ESC O m, depending on
499              * xterm function key mode, and I can't remember which
500              * goes where.
501              */
502           case '\003': xkey = 'M'; break;
503           case '0': xkey = 'p'; break;
504           case '1': xkey = 'q'; break;
505           case '2': xkey = 'r'; break;
506           case '3': xkey = 's'; break;
507           case '4': xkey = 't'; break;
508           case '5': xkey = 'u'; break;
509           case '6': xkey = 'v'; break;
510           case '7': xkey = 'w'; break;
511           case '8': xkey = 'x'; break;
512           case '9': xkey = 'y'; break;
513           case '.': xkey = 'n'; break;
514         }
515         if (xkey) {
516             if (term->vt52_mode) {
517                 if (xkey >= 'P' && xkey <= 'S') {
518                     output[end++] = '\033';
519                     output[end++] = xkey;
520                 } else {
521                     output[end++] = '\033';
522                     output[end++] = '?';
523                     output[end++] = xkey;
524                 }
525             } else {
526                 output[end++] = '\033';
527                 output[end++] = 'O';
528                 output[end++] = xkey;
529             }
530             goto done;
531         }
532     }
533
534     /*
535      * Next, all the keys that do tilde codes. (ESC '[' nn '~',
536      * for integer decimal nn.)
537      *
538      * We also deal with the weird ones here. Linux VCs replace F1
539      * to F5 by ESC [ [ A to ESC [ [ E. rxvt doesn't do _that_, but
540      * does replace Home and End (1~ and 4~) by ESC [ H and ESC O w
541      * respectively.
542      */
543     {
544         int code = 0;
545         switch (cm) {
546           case NSF1FunctionKey:
547             code = (m & NSShiftKeyMask ? 23 : 11);
548             break;
549           case NSF2FunctionKey:
550             code = (m & NSShiftKeyMask ? 24 : 12);
551             break;
552           case NSF3FunctionKey:
553             code = (m & NSShiftKeyMask ? 25 : 13);
554             break;
555           case NSF4FunctionKey:
556             code = (m & NSShiftKeyMask ? 26 : 14);
557             break;
558           case NSF5FunctionKey:
559             code = (m & NSShiftKeyMask ? 28 : 15);
560             break;
561           case NSF6FunctionKey:
562             code = (m & NSShiftKeyMask ? 29 : 17);
563             break;
564           case NSF7FunctionKey:
565             code = (m & NSShiftKeyMask ? 31 : 18);
566             break;
567           case NSF8FunctionKey:
568             code = (m & NSShiftKeyMask ? 32 : 19);
569             break;
570           case NSF9FunctionKey:
571             code = (m & NSShiftKeyMask ? 33 : 20);
572             break;
573           case NSF10FunctionKey:
574             code = (m & NSShiftKeyMask ? 34 : 21);
575             break;
576           case NSF11FunctionKey:
577             code = 23;
578             break;
579           case NSF12FunctionKey:
580             code = 24;
581             break;
582           case NSF13FunctionKey:
583             code = 25;
584             break;
585           case NSF14FunctionKey:
586             code = 26;
587             break;
588           case NSF15FunctionKey:
589             code = 28;
590             break;
591           case NSF16FunctionKey:
592             code = 29;
593             break;
594           case NSF17FunctionKey:
595             code = 31;
596             break;
597           case NSF18FunctionKey:
598             code = 32;
599             break;
600           case NSF19FunctionKey:
601             code = 33;
602             break;
603           case NSF20FunctionKey:
604             code = 34;
605             break;
606         }
607         if (!(m & NSControlKeyMask)) switch (cm) {
608           case NSHomeFunctionKey:
609             code = 1;
610             break;
611 #ifdef FIXME
612           case GDK_Insert: case GDK_KP_Insert:
613             code = 2;
614             break;
615 #endif
616           case NSDeleteFunctionKey:
617             code = 3;
618             break;
619           case NSEndFunctionKey:
620             code = 4;
621             break;
622           case NSPageUpFunctionKey:
623             code = 5;
624             break;
625           case NSPageDownFunctionKey:
626             code = 6;
627             break;
628         }
629         /* Reorder edit keys to physical order */
630         if (cfg.funky_type == FUNKY_VT400 && code <= 6)
631             code = "\0\2\1\4\5\3\6"[code];
632
633         if (term->vt52_mode && code > 0 && code <= 6) {
634             output[end++] = '\033';
635             output[end++] = " HLMEIG"[code];
636             goto done;
637         }
638
639         if (cfg.funky_type == FUNKY_SCO &&     /* SCO function keys */
640             code >= 11 && code <= 34) {
641             char codes[] = "MNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz@[\\]^_`{";
642             int index = 0;
643             switch (cm) {
644               case NSF1FunctionKey: index = 0; break;
645               case NSF2FunctionKey: index = 1; break;
646               case NSF3FunctionKey: index = 2; break;
647               case NSF4FunctionKey: index = 3; break;
648               case NSF5FunctionKey: index = 4; break;
649               case NSF6FunctionKey: index = 5; break;
650               case NSF7FunctionKey: index = 6; break;
651               case NSF8FunctionKey: index = 7; break;
652               case NSF9FunctionKey: index = 8; break;
653               case NSF10FunctionKey: index = 9; break;
654               case NSF11FunctionKey: index = 10; break;
655               case NSF12FunctionKey: index = 11; break;
656             }
657             if (m & NSShiftKeyMask) index += 12;
658             if (m & NSControlKeyMask) index += 24;
659             output[end++] = '\033';
660             output[end++] = '[';
661             output[end++] = codes[index];
662             goto done;
663         }
664         if (cfg.funky_type == FUNKY_SCO &&     /* SCO small keypad */
665             code >= 1 && code <= 6) {
666             char codes[] = "HL.FIG";
667             if (code == 3) {
668                 output[1] = '\x7F';
669                 end = 2;
670             } else {
671                 output[end++] = '\033';
672                 output[end++] = '[';
673                 output[end++] = codes[code-1];
674             }
675             goto done;
676         }
677         if ((term->vt52_mode || cfg.funky_type == FUNKY_VT100P) &&
678             code >= 11 && code <= 24) {
679             int offt = 0;
680             if (code > 15)
681                 offt++;
682             if (code > 21)
683                 offt++;
684             if (term->vt52_mode) {
685                 output[end++] = '\033';
686                 output[end++] = code + 'P' - 11 - offt;
687             } else {
688                 output[end++] = '\033';
689                 output[end++] = 'O';
690                 output[end++] = code + 'P' - 11 - offt;
691             }
692             goto done;
693         }
694         if (cfg.funky_type == FUNKY_LINUX && code >= 11 && code <= 15) {
695             output[end++] = '\033';
696             output[end++] = '[';
697             output[end++] = '[';        
698             output[end++] = code + 'A' - 11;
699             goto done;
700         }
701         if (cfg.funky_type == FUNKY_XTERM && code >= 11 && code <= 14) {
702             if (term->vt52_mode) {
703                 output[end++] = '\033';
704                 output[end++] = code + 'P' - 11;
705             } else {
706                 output[end++] = '\033';
707                 output[end++] = 'O';
708                 output[end++] = code + 'P' - 11;
709             }
710             goto done;
711         }
712         if (cfg.rxvt_homeend && (code == 1 || code == 4)) {
713             if (code == 1) {
714                 output[end++] = '\033';
715                 output[end++] = '[';
716                 output[end++] = 'H';
717             } else {
718                 output[end++] = '\033';
719                 output[end++] = 'O';
720                 output[end++] = 'w';
721             }
722             goto done;
723         }
724         if (code) {
725             char buf[20];
726             sprintf(buf, "\x1B[%d~", code);
727             for (i = 0; buf[i]; i++)
728                 output[end++] = buf[i];
729             goto done;
730         }
731     }
732
733     /*
734      * Cursor keys. (This includes the numberpad cursor keys,
735      * if we haven't already done them due to app keypad mode.)
736      */
737     {
738         int xkey = 0;
739         switch (cm) {
740           case NSUpArrowFunctionKey: xkey = 'A'; break;
741           case NSDownArrowFunctionKey: xkey = 'B'; break;
742           case NSRightArrowFunctionKey: xkey = 'C'; break;
743           case NSLeftArrowFunctionKey: xkey = 'D'; break;
744         }
745         if (xkey) {
746             /*
747              * The arrow keys normally do ESC [ A and so on. In
748              * app cursor keys mode they do ESC O A instead.
749              * Ctrl toggles the two modes.
750              */
751             if (term->vt52_mode) {
752                 output[end++] = '\033';
753                 output[end++] = xkey;
754             } else if (!term->app_cursor_keys ^ !(m & NSControlKeyMask)) {
755                 output[end++] = '\033';
756                 output[end++] = 'O';
757                 output[end++] = xkey;
758             } else {
759                 output[end++] = '\033';
760                 output[end++] = '[';
761                 output[end++] = xkey;
762             }
763             goto done;
764         }
765     }
766
767     done:
768
769     /*
770      * Failing everything else, send the exact Unicode we got from
771      * OS X.
772      */
773     if (end == start) {
774         if (n > lenof(output)-start)
775             n = lenof(output)-start;   /* _shouldn't_ happen! */
776         for (i = 0; i < n; i++) {
777             output[i+start] = [s characterAtIndex:i];
778         }
779         end = n+start;
780     }
781
782     if (use_coutput) {
783         assert(special);
784         assert(end < lenof(coutput));
785         coutput[end] = '\0';
786         ldisc_send(ldisc, coutput+start, -2, TRUE);
787     } else {
788         luni_send(ldisc, output+start, end-start, TRUE);
789     }
790 }
791
792 - (int)fromBackend:(const char *)data len:(int)len isStderr:(int)is_stderr
793 {
794     return term_data(term, is_stderr, data, len);
795 }
796
797 - (int)fromBackendUntrusted:(const char *)data len:(int)len
798 {
799     return term_data_untrusted(term, data, len);
800 }
801
802 - (void)startAlert:(NSAlert *)alert
803     withCallback:(void (*)(void *, int))callback andCtx:(void *)ctx
804 {
805     if (alert_ctx || alert_qhead) {
806         /*
807          * Queue this alert to be shown later.
808          */
809         struct alert_queue *qitem = snew(struct alert_queue);
810         qitem->next = NULL;
811         qitem->alert = alert;
812         qitem->callback = callback;
813         qitem->ctx = ctx;
814         if (alert_qtail)
815             alert_qtail->next = qitem;
816         else
817             alert_qhead = qitem;
818         alert_qtail = qitem;
819     } else {
820         alert_callback = callback;
821         alert_ctx = ctx;               /* NB this is assumed to need freeing! */
822         [alert beginSheetModalForWindow:self modalDelegate:self
823          didEndSelector:@selector(alertSheetDidEnd:returnCode:contextInfo:)
824          contextInfo:NULL];
825     }
826 }
827
828 - (void)alertSheetDidEnd:(NSAlert *)alert returnCode:(int)returnCode
829     contextInfo:(void *)contextInfo
830 {
831     [self performSelectorOnMainThread:
832      @selector(alertSheetDidFinishEnding:)
833      withObject:[NSNumber numberWithInt:returnCode]
834      waitUntilDone:NO];
835 }
836
837 - (void)alertSheetDidFinishEnding:(id)object
838 {
839     int returnCode = [object intValue];
840
841     alert_callback(alert_ctx, returnCode);   /* transfers ownership of ctx */
842
843     /*
844      * If there's an alert in our queue (either already or because
845      * the callback just queued it), start it.
846      */
847     if (alert_qhead) {
848         struct alert_queue *qnext;
849
850         alert_callback = alert_qhead->callback;
851         alert_ctx = alert_qhead->ctx;
852         [alert_qhead->alert beginSheetModalForWindow:self modalDelegate:self
853          didEndSelector:@selector(alertSheetDidEnd:returnCode:contextInfo:)
854          contextInfo:NULL];
855
856         qnext = alert_qhead->next;
857         sfree(alert_qhead);
858         alert_qhead = qnext;
859         if (!qnext)
860             alert_qtail = NULL;
861     } else {
862         alert_ctx = NULL;
863     }
864 }
865
866 - (void)notifyRemoteExit
867 {
868     int exitcode;
869
870     if (!exited && (exitcode = back->exitcode(backhandle)) >= 0)
871         [self endSession:(exitcode == 0)];
872 }
873
874 - (void)endSession:(int)clean
875 {
876     exited = TRUE;
877     if (ldisc) {
878         ldisc_free(ldisc);
879         ldisc = NULL;
880     }
881     if (back) {
882         back->free(backhandle);
883         backhandle = NULL;
884         back = NULL;
885         //FIXME: update specials menu;
886     }
887     if (cfg.close_on_exit == FORCE_ON ||
888         (cfg.close_on_exit == AUTO && clean))
889         [self close];
890     // FIXME: else show restart menu item
891 }
892
893 - (Terminal *)term
894 {
895     return term;
896 }
897
898 @end
899
900 int from_backend(void *frontend, int is_stderr, const char *data, int len)
901 {
902     SessionWindow *win = (SessionWindow *)frontend;
903     return [win fromBackend:data len:len isStderr:is_stderr];
904 }
905
906 int from_backend_untrusted(void *frontend, const char *data, int len)
907 {
908     SessionWindow *win = (SessionWindow *)frontend;
909     return [win fromBackendUntrusted:data len:len];
910 }
911
912 int get_userpass_input(prompts_t *p, unsigned char *in, int inlen)
913 {
914     SessionWindow *win = (SessionWindow *)p->frontend;
915     Terminal *term = [win term];
916     return term_get_userpass_input(term, p, in, inlen);
917 }
918
919 void frontend_keypress(void *handle)
920 {
921     /* FIXME */
922 }
923
924 void notify_remote_exit(void *frontend)
925 {
926     SessionWindow *win = (SessionWindow *)frontend;
927
928     [win notifyRemoteExit];
929 }
930
931 void ldisc_update(void *frontend, int echo, int edit)
932 {
933     //SessionWindow *win = (SessionWindow *)frontend;
934     /*
935      * In a GUI front end, this need do nothing.
936      */
937 }
938
939 char *get_ttymode(void *frontend, const char *mode)
940 {
941     SessionWindow *win = (SessionWindow *)frontend;
942     Terminal *term = [win term];
943     return term_get_ttymode(term, mode);
944 }
945
946 void update_specials_menu(void *frontend)
947 {
948     //SessionWindow *win = (SessionWindow *)frontend;
949     /* FIXME */
950 }
951
952 /*
953  * This is still called when mode==BELL_VISUAL, even though the
954  * visual bell is handled entirely within terminal.c, because we
955  * may want to perform additional actions on any kind of bell (for
956  * example, taskbar flashing in Windows).
957  */
958 void do_beep(void *frontend, int mode)
959 {
960     //SessionWindow *win = (SessionWindow *)frontend;
961     if (mode != BELL_VISUAL)
962         NSBeep();
963 }
964
965 int char_width(Context ctx, int uc)
966 {
967     /*
968      * Under X, any fixed-width font really _is_ fixed-width.
969      * Double-width characters will be dealt with using a separate
970      * font. For the moment we can simply return 1.
971      */
972     return 1;
973 }
974
975 void palette_set(void *frontend, int n, int r, int g, int b)
976 {
977     SessionWindow *win = (SessionWindow *)frontend;
978
979     if (n >= 16)
980         n += 256 - 16;
981     if (n > NALLCOLOURS)
982         return;
983     [win setColour:n r:r/255.0 g:g/255.0 b:b/255.0];
984
985     /*
986      * FIXME: do we need an OS X equivalent of set_window_background?
987      */
988 }
989
990 void palette_reset(void *frontend)
991 {
992     SessionWindow *win = (SessionWindow *)frontend;
993     Config *cfg = [win cfg];
994
995     /* This maps colour indices in cfg to those used in colours[]. */
996     static const int ww[] = {
997         256, 257, 258, 259, 260, 261,
998         0, 8, 1, 9, 2, 10, 3, 11,
999         4, 12, 5, 13, 6, 14, 7, 15
1000     };
1001
1002     int i;
1003
1004     for (i = 0; i < NCFGCOLOURS; i++) {
1005         [win setColour:ww[i] r:cfg->colours[i][0]/255.0
1006          g:cfg->colours[i][1]/255.0 b:cfg->colours[i][2]/255.0];
1007     }
1008
1009     for (i = 0; i < NEXTCOLOURS; i++) {
1010         if (i < 216) {
1011             int r = i / 36, g = (i / 6) % 6, b = i % 6;
1012             r = r ? r*40+55 : 0; g = g ? b*40+55 : 0; b = b ? b*40+55 : 0;
1013             [win setColour:i+16 r:r/255.0 g:g/255.0 b:b/255.0];
1014         } else {
1015             int shade = i - 216;
1016             float fshade = (shade * 10 + 8) / 255.0;
1017             [win setColour:i+16 r:fshade g:fshade b:fshade];
1018         }
1019     }
1020
1021     /*
1022      * FIXME: do we need an OS X equivalent of set_window_background?
1023      */
1024 }
1025
1026 Context get_ctx(void *frontend)
1027 {
1028     SessionWindow *win = (SessionWindow *)frontend;
1029
1030     /*
1031      * Lock the drawing focus on the image inside the TerminalView.
1032      */
1033     [win drawStartFinish:YES];
1034
1035     [[NSGraphicsContext currentContext] setShouldAntialias:YES];
1036
1037     /*
1038      * Cocoa drawing functions don't take a graphics context: that
1039      * parameter is implicit. Therefore, we'll use the frontend
1040      * handle itself as the context, on the grounds that it's as
1041      * good a thing to use as any.
1042      */
1043     return frontend;
1044 }
1045
1046 void free_ctx(Context ctx)
1047 {
1048     SessionWindow *win = (SessionWindow *)ctx;
1049
1050     [win drawStartFinish:NO];
1051 }
1052
1053 void do_text(Context ctx, int x, int y, wchar_t *text, int len,
1054              unsigned long attr, int lattr)
1055 {
1056     SessionWindow *win = (SessionWindow *)ctx;
1057
1058     [win doText:text len:len x:x y:y attr:attr lattr:lattr];
1059 }
1060
1061 void do_cursor(Context ctx, int x, int y, wchar_t *text, int len,
1062                unsigned long attr, int lattr)
1063 {
1064     SessionWindow *win = (SessionWindow *)ctx;
1065     Config *cfg = [win cfg];
1066     int active, passive;
1067
1068     if (attr & TATTR_PASCURS) {
1069         attr &= ~TATTR_PASCURS;
1070         passive = 1;
1071     } else
1072         passive = 0;
1073     if ((attr & TATTR_ACTCURS) && cfg->cursor_type != 0) {
1074         attr &= ~TATTR_ACTCURS;
1075         active = 1;
1076     } else
1077         active = 0;
1078
1079     [win doText:text len:len x:x y:y attr:attr lattr:lattr];
1080
1081     /*
1082      * FIXME: now draw the various cursor types (both passive and
1083      * active underlines and vertical lines, plus passive blocks).
1084      */
1085 }
1086
1087 /*
1088  * Minimise or restore the window in response to a server-side
1089  * request.
1090  */
1091 void set_iconic(void *frontend, int iconic)
1092 {
1093     //SessionWindow *win = (SessionWindow *)frontend;
1094     /* FIXME */
1095 }
1096
1097 /*
1098  * Move the window in response to a server-side request.
1099  */
1100 void move_window(void *frontend, int x, int y)
1101 {
1102     //SessionWindow *win = (SessionWindow *)frontend; 
1103     /* FIXME */
1104 }
1105
1106 /*
1107  * Move the window to the top or bottom of the z-order in response
1108  * to a server-side request.
1109  */
1110 void set_zorder(void *frontend, int top)
1111 {
1112     //SessionWindow *win = (SessionWindow *)frontend;
1113     /* FIXME */
1114 }
1115
1116 /*
1117  * Refresh the window in response to a server-side request.
1118  */
1119 void refresh_window(void *frontend)
1120 {
1121     //SessionWindow *win = (SessionWindow *)frontend;
1122     /* FIXME */
1123 }
1124
1125 /*
1126  * Maximise or restore the window in response to a server-side
1127  * request.
1128  */
1129 void set_zoomed(void *frontend, int zoomed)
1130 {
1131     //SessionWindow *win = (SessionWindow *)frontend;
1132     /* FIXME */
1133 }
1134
1135 /*
1136  * Report whether the window is iconic, for terminal reports.
1137  */
1138 int is_iconic(void *frontend)
1139 {
1140     //SessionWindow *win = (SessionWindow *)frontend;
1141     return NO;                         /* FIXME */
1142 }
1143
1144 /*
1145  * Report the window's position, for terminal reports.
1146  */
1147 void get_window_pos(void *frontend, int *x, int *y)
1148 {
1149     //SessionWindow *win = (SessionWindow *)frontend;
1150     /* FIXME */
1151 }
1152
1153 /*
1154  * Report the window's pixel size, for terminal reports.
1155  */
1156 void get_window_pixels(void *frontend, int *x, int *y)
1157 {
1158     //SessionWindow *win = (SessionWindow *)frontend;
1159     /* FIXME */
1160 }
1161
1162 /*
1163  * Return the window or icon title.
1164  */
1165 char *get_window_title(void *frontend, int icon)
1166 {
1167     //SessionWindow *win = (SessionWindow *)frontend;
1168     return NULL; /* FIXME */
1169 }
1170
1171 void set_title(void *frontend, char *title)
1172 {
1173     //SessionWindow *win = (SessionWindow *)frontend;
1174     /* FIXME */
1175 }
1176
1177 void set_icon(void *frontend, char *title)
1178 {
1179     //SessionWindow *win = (SessionWindow *)frontend;
1180     /* FIXME */
1181 }
1182
1183 void set_sbar(void *frontend, int total, int start, int page)
1184 {
1185     //SessionWindow *win = (SessionWindow *)frontend;
1186     /* FIXME */
1187 }
1188
1189 void get_clip(void *frontend, wchar_t ** p, int *len)
1190 {
1191     //SessionWindow *win = (SessionWindow *)frontend;
1192     /* FIXME */
1193 }
1194
1195 void write_clip(void *frontend, wchar_t *data, int *attr, int len, int must_deselect)
1196 {
1197     //SessionWindow *win = (SessionWindow *)frontend;
1198     /* FIXME */
1199 }
1200
1201 void request_paste(void *frontend)
1202 {
1203     //SessionWindow *win = (SessionWindow *)frontend;
1204     /* FIXME */
1205 }
1206
1207 void set_raw_mouse_mode(void *frontend, int activate)
1208 {
1209     //SessionWindow *win = (SessionWindow *)frontend;
1210     /* FIXME */
1211 }
1212
1213 void request_resize(void *frontend, int w, int h)
1214 {
1215     //SessionWindow *win = (SessionWindow *)frontend;
1216     /* FIXME */
1217 }
1218
1219 void sys_cursor(void *frontend, int x, int y)
1220 {
1221     //SessionWindow *win = (SessionWindow *)frontend;
1222     /*
1223      * This is probably meaningless under OS X. FIXME: find out for
1224      * sure.
1225      */
1226 }
1227
1228 void logevent(void *frontend, const char *string)
1229 {
1230     //SessionWindow *win = (SessionWindow *)frontend;
1231     /* FIXME */
1232 printf("logevent: %s\n", string);
1233 }
1234
1235 int font_dimension(void *frontend, int which)/* 0 for width, 1 for height */
1236 {
1237     //SessionWindow *win = (SessionWindow *)frontend;
1238     return 1; /* FIXME */
1239 }
1240
1241 void set_busy_status(void *frontend, int status)
1242 {
1243     /*
1244      * We need do nothing here: the OS X `application is busy'
1245      * beachball pointer appears _automatically_ when the
1246      * application isn't responding to GUI messages.
1247      */
1248 }