]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - mac/macterm.c
e2e33dec3ef47f35af0695dc7f6cc1fabda24179
[PuTTY.git] / mac / macterm.c
1 /* $Id: macterm.c,v 1.8 2002/11/23 19:01:01 ben Exp $ */
2 /*
3  * Copyright (c) 1999 Simon Tatham
4  * Copyright (c) 1999, 2002 Ben Harris
5  * All rights reserved.
6  *
7  * Permission is hereby granted, free of charge, to any person
8  * obtaining a copy of this software and associated documentation
9  * files (the "Software"), to deal in the Software without
10  * restriction, including without limitation the rights to use,
11  * copy, modify, merge, publish, distribute, sublicense, and/or
12  * sell copies of the Software, and to permit persons to whom the
13  * Software is furnished to do so, subject to the following
14  * conditions:
15  * 
16  * The above copyright notice and this permission notice shall be
17  * included in all copies or substantial portions of the Software.
18  * 
19  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
20  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
21  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
22  * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR
23  * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
24  * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
25  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26  * SOFTWARE.
27  */
28
29 /*
30  * macterm.c -- Macintosh terminal front-end
31  */
32
33 #include <MacTypes.h>
34 #include <Controls.h>
35 #include <ControlDefinitions.h>
36 #include <Fonts.h>
37 #include <Gestalt.h>
38 #include <MacMemory.h>
39 #include <MacWindows.h>
40 #include <MixedMode.h>
41 #include <Palettes.h>
42 #include <Quickdraw.h>
43 #include <QuickdrawText.h>
44 #include <Resources.h>
45 #include <Scrap.h>
46 #include <Script.h>
47 #include <Sound.h>
48 #include <Threads.h>
49 #include <ToolUtils.h>
50
51 #include <assert.h>
52 #include <limits.h>
53 #include <stdlib.h>
54 #include <stdio.h>
55 #include <string.h>
56
57 #include "macresid.h"
58 #include "putty.h"
59 #include "mac.h"
60 #include "terminal.h"
61
62 #define NCOLOURS (lenof(((Config *)0)->colours))
63
64 #define DEFAULT_FG      16
65 #define DEFAULT_FG_BOLD 17
66 #define DEFAULT_BG      18
67 #define DEFAULT_BG_BOLD 19
68 #define CURSOR_FG       20
69 #define CURSOR_BG       21
70
71 #define PTOCC(x) ((x) < 0 ? -(-(x - s->font_width - 1) / s->font_width) : \
72                             (x) / s->font_width)
73 #define PTOCR(y) ((y) < 0 ? -(-(y - s->font_height - 1) / s->font_height) : \
74                             (y) / s->font_height)
75
76 static void mac_initfont(Session *);
77 static void mac_initpalette(Session *);
78 static void mac_adjustwinbg(Session *);
79 static void mac_adjustsize(Session *, int, int);
80 static void mac_drawgrowicon(Session *s);
81 static pascal void mac_scrolltracker(ControlHandle, short);
82 static pascal void do_text_for_device(short, short, GDHandle, long);
83 static pascal void mac_set_attr_mask(short, short, GDHandle, long);
84 static int mac_keytrans(Session *, EventRecord *, unsigned char *);
85 static void text_click(Session *, EventRecord *);
86
87 void pre_paint(Session *s);
88 void post_paint(Session *s);
89
90 #if TARGET_RT_MAC_CFM
91 static RoutineDescriptor mac_scrolltracker_upp =
92     BUILD_ROUTINE_DESCRIPTOR(uppControlActionProcInfo,
93                              (ProcPtr)mac_scrolltracker);
94 static RoutineDescriptor do_text_for_device_upp =
95     BUILD_ROUTINE_DESCRIPTOR(uppDeviceLoopDrawingProcInfo,
96                              (ProcPtr)do_text_for_device);
97 static RoutineDescriptor mac_set_attr_mask_upp =
98     BUILD_ROUTINE_DESCRIPTOR(uppDeviceLoopDrawingProcInfo,
99                              (ProcPtr)mac_set_attr_mask);
100 #else /* not TARGET_RT_MAC_CFM */
101 #define mac_scrolltracker_upp   mac_scrolltracker
102 #define do_text_for_device_upp  do_text_for_device
103 #define mac_set_attr_mask_upp   mac_set_attr_mask
104 #endif /* not TARGET_RT_MAC_CFM */
105
106 static void inbuf_putc(Session *s, int c) {
107     char ch = c;
108
109     from_backend(s->term, 0, &ch, 1);
110 }
111
112 static void inbuf_putstr(Session *s, const char *c) {
113
114     from_backend(s->term, 0, (char *)c, strlen(c));
115 }
116
117 static void display_resource(Session *s, unsigned long type, short id) {
118     Handle h;
119     int len, i;
120     char *t;
121
122     h = GetResource(type, id);
123     if (h == NULL)
124         fatalbox("Can't get test resource");
125     len = GetResourceSizeOnDisk(h);
126     DetachResource(h);
127     HNoPurge(h);
128     HLock(h);
129     t = *h;
130     from_backend(s->term, 0, t, len);
131     term_out(s->term);
132     DisposeHandle(h);
133 }
134         
135
136 void mac_newsession(void) {
137     Session *s;
138     UInt32 starttime;
139     char msg[128];
140     OSErr err;
141
142     /* This should obviously be initialised by other means */
143     s = smalloc(sizeof(*s));
144     memset(s, 0, sizeof(*s));
145     do_defaults(NULL, &s->cfg);
146     s->back = &loop_backend;
147         
148     /* XXX: Own storage management? */
149     if (HAVE_COLOR_QD())
150         s->window = GetNewCWindow(wTerminal, NULL, (WindowPtr)-1);
151     else
152         s->window = GetNewWindow(wTerminal, NULL, (WindowPtr)-1);
153     SetWRefCon(s->window, (long)s);
154     s->scrollbar = GetNewControl(cVScroll, s->window);
155     s->term = term_init(&s->cfg, s);
156
157     s->logctx = log_init(s);
158     term_provide_logctx(s->term, s->logctx);
159
160     s->back->init(s->term, &s->backhandle, "localhost", 23, &s->realhost, 0);
161     s->back->provide_logctx(s->backhandle, s->logctx);
162
163     term_provide_resize_fn(s->term, s->back->size, s->backhandle);
164
165     mac_adjustsize(s, s->cfg.height, s->cfg.width);
166     term_size(s->term, s->cfg.height, s->cfg.width, s->cfg.savelines);
167
168     s->ldisc = ldisc_create(s->term, s->back, s->backhandle, s);
169     ldisc_send(s->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
170
171     mac_initfont(s);
172     mac_initpalette(s);
173     s->attr_mask = ATTR_MASK;
174     if (HAVE_COLOR_QD()) {
175         /* Set to FALSE to not get palette updates in the background. */
176         SetPalette(s->window, s->palette, TRUE); 
177         ActivatePalette(s->window);
178     }
179     ShowWindow(s->window);
180     starttime = TickCount();
181     display_resource(s, 'pTST', 128);
182     sprintf(msg, "Elapsed ticks: %d\015\012", TickCount() - starttime);
183     inbuf_putstr(s, msg);
184     term_out(s->term);
185 }
186
187 static void mac_initfont(Session *s) {
188     Str255 macfont;
189     FontInfo fi;
190  
191     SetPort(s->window);
192     macfont[0] = sprintf((char *)&macfont[1], "%s", s->cfg.font);
193     GetFNum(macfont, &s->fontnum);
194     TextFont(s->fontnum);
195     TextFace(s->cfg.fontisbold ? bold : 0);
196     TextSize(s->cfg.fontheight);
197     GetFontInfo(&fi);
198     s->font_width = CharWidth('W'); /* Well, it's what NCSA uses. */
199     s->font_ascent = fi.ascent;
200     s->font_leading = fi.leading;
201     s->font_height = s->font_ascent + fi.descent + s->font_leading;
202     if (!s->cfg.bold_colour) {
203         TextFace(bold);
204         s->font_boldadjust = s->font_width - CharWidth('W');
205     } else
206         s->font_boldadjust = 0;
207     mac_adjustsize(s, s->term->rows, s->term->cols);
208 }
209
210 /*
211  * To be called whenever the window size changes.
212  * rows and cols should be desired values.
213  * It's assumed the terminal emulator will be informed, and will set rows
214  * and cols for us.
215  */
216 static void mac_adjustsize(Session *s, int newrows, int newcols) {
217     int winwidth, winheight;
218
219     winwidth = newcols * s->font_width + 15;
220     winheight = newrows * s->font_height;
221     SizeWindow(s->window, winwidth, winheight, true);
222     HideControl(s->scrollbar);
223     MoveControl(s->scrollbar, winwidth - 15, -1);
224     SizeControl(s->scrollbar, 16, winheight - 13);
225     ShowControl(s->scrollbar);
226 }
227
228 static void mac_initpalette(Session *s) {
229     int i;
230
231     /*
232      * Most colours should be inhibited on 2bpp displays.
233      * Palette manager documentation suggests inhibiting all tolerant colours
234      * on greyscale displays.
235      */
236 #define PM_NORMAL       ( pmTolerant | pmInhibitC2 |                    \
237                           pmInhibitG2 | pmInhibitG4 | pmInhibitG8 )
238 #define PM_TOLERANCE    0x2000
239     s->palette = NewPalette(22, NULL, PM_NORMAL, PM_TOLERANCE);
240     if (s->palette == NULL)
241         fatalbox("Unable to create palette");
242     /* In 2bpp, these are the colours we want most. */
243     SetEntryUsage(s->palette, DEFAULT_BG,
244                   PM_NORMAL &~ pmInhibitC2, PM_TOLERANCE);
245     SetEntryUsage(s->palette, DEFAULT_FG,
246                   PM_NORMAL &~ pmInhibitC2, PM_TOLERANCE);
247     SetEntryUsage(s->palette, DEFAULT_FG_BOLD,
248                   PM_NORMAL &~ pmInhibitC2, PM_TOLERANCE);
249     SetEntryUsage(s->palette, CURSOR_BG,
250                   PM_NORMAL &~ pmInhibitC2, PM_TOLERANCE);
251     palette_reset(s);
252 }
253
254 /*
255  * Set the background colour of the window correctly.  Should be
256  * called whenever the default background changes.
257  */
258 static void mac_adjustwinbg(Session *s) {
259
260     if (!HAVE_COLOR_QD())
261         return;
262 #if TARGET_RT_CFM /* XXX doesn't link (at least for 68k) */
263     if (mac_gestalts.windattr & gestaltWindowMgrPresent)
264         SetWindowContentColor(s->window,
265                               &(*s->palette)->pmInfo[DEFAULT_BG].ciRGB);
266     else
267 #endif
268     {
269         if (s->wctab == NULL)
270             s->wctab = (WCTabHandle)NewHandle(sizeof(**s->wctab));
271         if (s->wctab == NULL)
272             return; /* do without */
273         (*s->wctab)->wCSeed = 0;
274         (*s->wctab)->wCReserved = 0;
275         (*s->wctab)->ctSize = 0;
276         (*s->wctab)->ctTable[0].value = wContentColor;
277         (*s->wctab)->ctTable[0].rgb = (*s->palette)->pmInfo[DEFAULT_BG].ciRGB;
278         SetWinColor(s->window, s->wctab);
279     }
280 }
281
282 /*
283  * Set the cursor shape correctly
284  */
285 void mac_adjusttermcursor(WindowPtr window, Point mouse, RgnHandle cursrgn) {
286     Session *s;
287     ControlHandle control;
288     short part;
289     int x, y;
290
291     SetPort(window);
292     s = (Session *)GetWRefCon(window);
293     GlobalToLocal(&mouse);
294     part = FindControl(mouse, window, &control);
295     if (control == s->scrollbar) {
296         SetCursor(&qd.arrow);
297         RectRgn(cursrgn, &(*s->scrollbar)->contrlRect);
298         SectRgn(cursrgn, window->visRgn, cursrgn);
299     } else {
300         x = mouse.h / s->font_width;
301         y = mouse.v / s->font_height;
302         if (s->raw_mouse)
303             SetCursor(&qd.arrow);
304         else
305             SetCursor(*GetCursor(iBeamCursor));
306         /* Ask for shape changes if we leave this character cell. */
307         SetRectRgn(cursrgn, x * s->font_width, y * s->font_height,
308                    (x + 1) * s->font_width, (y + 1) * s->font_height);
309         SectRgn(cursrgn, window->visRgn, cursrgn);
310     }
311 }
312
313 /*
314  * Enable/disable menu items based on the active terminal window.
315  */
316 void mac_adjusttermmenus(WindowPtr window) {
317     Session *s;
318     MenuHandle menu;
319     long offset;
320
321     s = (Session *)GetWRefCon(window);
322     menu = GetMenuHandle(mEdit);
323     EnableItem(menu, 0);
324     DisableItem(menu, iUndo);
325     DisableItem(menu, iCut);
326     if (1/*s->term->selstate == SELECTED*/)
327         EnableItem(menu, iCopy);
328     else
329         DisableItem(menu, iCopy);
330     if (GetScrap(NULL, 'TEXT', &offset) == noTypeErr)
331         DisableItem(menu, iPaste);
332     else
333         EnableItem(menu, iPaste);
334     DisableItem(menu, iClear);
335     EnableItem(menu, iSelectAll);
336 }
337
338 void mac_menuterm(WindowPtr window, short menu, short item) {
339     Session *s;
340
341     s = (Session *)GetWRefCon(window);
342     switch (menu) {
343       case mEdit:
344         switch (item) {
345           case iCopy:
346             /* term_copy(s); */
347             break;
348           case iPaste:
349             term_do_paste(s->term);
350             break;
351         }
352     }
353 }
354             
355 void mac_clickterm(WindowPtr window, EventRecord *event) {
356     Session *s;
357     Point mouse;
358     ControlHandle control;
359     int part;
360
361     s = (Session *)GetWRefCon(window);
362     SetPort(window);
363     mouse = event->where;
364     GlobalToLocal(&mouse);
365     part = FindControl(mouse, window, &control);
366     if (control == s->scrollbar) {
367         switch (part) {
368           case kControlIndicatorPart:
369             if (TrackControl(control, mouse, NULL) == kControlIndicatorPart)
370                 term_scroll(s->term, +1, GetControlValue(control));
371             break;
372           case kControlUpButtonPart:
373           case kControlDownButtonPart:
374           case kControlPageUpPart:
375           case kControlPageDownPart:
376             TrackControl(control, mouse, &mac_scrolltracker_upp);
377             break;
378         }
379     } else {
380         text_click(s, event);
381     }
382 }
383
384 static void text_click(Session *s, EventRecord *event) {
385     Point localwhere;
386     int row, col;
387     static UInt32 lastwhen = 0;
388     static Session *lastsess = NULL;
389     static int lastrow = -1, lastcol = -1;
390     static Mouse_Action lastact = MA_NOTHING;
391
392     SetPort(s->window);
393     localwhere = event->where;
394     GlobalToLocal(&localwhere);
395
396     col = PTOCC(localwhere.h);
397     row = PTOCR(localwhere.v);
398     if (event->when - lastwhen < GetDblTime() &&
399         row == lastrow && col == lastcol && s == lastsess)
400         lastact = (lastact == MA_CLICK ? MA_2CLK :
401                    lastact == MA_2CLK ? MA_3CLK :
402                    lastact == MA_3CLK ? MA_CLICK : MA_NOTHING);
403     else
404         lastact = MA_CLICK;
405     /* Fake right button with shift key */
406     term_mouse(s->term, event->modifiers & shiftKey ? MBT_RIGHT : MBT_LEFT,
407                lastact, col, row, event->modifiers & shiftKey,
408                event->modifiers & controlKey, event->modifiers & optionKey);
409     lastsess = s;
410     lastrow = row;
411     lastcol = col;
412     while (StillDown()) {
413         GetMouse(&localwhere);
414         col = PTOCC(localwhere.h);
415         row = PTOCR(localwhere.v);
416         term_mouse(s->term,
417                    event->modifiers & shiftKey ? MBT_RIGHT : MBT_LEFT,
418                    MA_DRAG, col, row, event->modifiers & shiftKey,
419                    event->modifiers & controlKey,
420                    event->modifiers & optionKey);
421         if (row > s->term->rows - 1)
422             term_scroll(s->term, 0, row - (s->term->rows - 1));
423         else if (row < 0)
424             term_scroll(s->term, 0, row);
425     }
426     term_mouse(s->term, event->modifiers & shiftKey ? MBT_RIGHT : MBT_LEFT,
427                MA_RELEASE, col, row, event->modifiers & shiftKey,
428                event->modifiers & controlKey, event->modifiers & optionKey);
429     lastwhen = TickCount();
430 }
431
432 Mouse_Button translate_button(void *frontend, Mouse_Button button)
433 {
434
435     switch (button) {
436       case MBT_LEFT:
437         return MBT_SELECT;
438       case MBT_RIGHT:
439         return MBT_EXTEND;
440       default:
441         return 0;
442     }
443 }
444
445 void write_clip(void *cookie, wchar_t *data, int len, int must_deselect) {
446     
447     /*
448      * See "Programming with the Text Encoding Conversion Manager"
449      * Appendix E for Unicode scrap conventions.
450      *
451      * XXX Need to support TEXT/styl scrap as well.
452      * See STScrpRec in TextEdit (Inside Macintosh: Text) for styl details.
453      * XXX Maybe PICT scrap too.
454      */
455     if (ZeroScrap() != noErr)
456         return;
457     PutScrap(len * sizeof(*data), 'utxt', data);
458 }
459
460 void get_clip(void *frontend, wchar_t **p, int *lenp) {
461     Session *s = frontend;
462     static Handle h = NULL;
463     long offset;
464
465     if (p == NULL) {
466         /* release memory */
467         if (h != NULL)
468             DisposeHandle(h);
469         h = NULL;
470     } else
471         /* XXX Support TEXT-format scrap as well. */
472         if (GetScrap(NULL, 'utxt', &offset) > 0) {
473             h = NewHandle(0);
474             *lenp = GetScrap(h, 'utxt', &offset) / sizeof(**p);
475             HLock(h);
476             *p = (wchar_t *)*h;
477             if (*p == NULL || *lenp <= 0)
478                 fatalbox("Empty scrap");
479         } else {
480             *p = NULL;
481             *lenp = 0;
482         }
483 }
484
485 static pascal void mac_scrolltracker(ControlHandle control, short part) {
486     Session *s;
487
488     s = (Session *)GetWRefCon((*control)->contrlOwner);
489     switch (part) {
490       case kControlUpButtonPart:
491         term_scroll(s->term, 0, -1);
492         break;
493       case kControlDownButtonPart:
494         term_scroll(s->term, 0, +1);
495         break;
496       case kControlPageUpPart:
497         term_scroll(s->term, 0, -(s->term->rows - 1));
498         break;
499       case kControlPageDownPart:
500         term_scroll(s->term, 0, +(s->term->rows - 1));
501         break;
502     }
503 }
504
505 #define K_BS    0x3300
506 #define K_F1    0x7a00
507 #define K_F2    0x7800
508 #define K_F3    0x6300
509 #define K_F4    0x7600
510 #define K_F5    0x6000
511 #define K_F6    0x6100
512 #define K_F7    0x6200
513 #define K_F8    0x6400
514 #define K_F9    0x6500
515 #define K_F10   0x6d00
516 #define K_F11   0x6700
517 #define K_F12   0x6f00
518 #define K_F13   0x6900
519 #define K_F14   0x6b00
520 #define K_F15   0x7100
521 #define K_INSERT 0x7200
522 #define K_HOME  0x7300
523 #define K_PRIOR 0x7400
524 #define K_DELETE 0x7500
525 #define K_END   0x7700
526 #define K_NEXT  0x7900
527 #define K_LEFT  0x7b00
528 #define K_RIGHT 0x7c00
529 #define K_DOWN  0x7d00
530 #define K_UP    0x7e00
531 #define KP_0    0x5200
532 #define KP_1    0x5300
533 #define KP_2    0x5400
534 #define KP_3    0x5500
535 #define KP_4    0x5600
536 #define KP_5    0x5700
537 #define KP_6    0x5800
538 #define KP_7    0x5900
539 #define KP_8    0x5b00
540 #define KP_9    0x5c00
541 #define KP_CLEAR 0x4700
542 #define KP_EQUAL 0x5100
543 #define KP_SLASH 0x4b00
544 #define KP_STAR 0x4300
545 #define KP_PLUS 0x4500
546 #define KP_MINUS 0x4e00
547 #define KP_DOT  0x4100
548 #define KP_ENTER 0x4c00
549
550 void mac_keyterm(WindowPtr window, EventRecord *event) {
551     unsigned char buf[20];
552     int len;
553     Session *s;
554
555     s = (Session *)GetWRefCon(window);
556     len = mac_keytrans(s, event, buf);
557     ldisc_send(s->ldisc, (char *)buf, len, 1);
558     ObscureCursor();
559     term_seen_key_event(s->term);
560     term_out(s->term);
561     term_update(s->term);
562 }
563
564 static int mac_keytrans(Session *s, EventRecord *event,
565                         unsigned char *output) {
566     unsigned char *p = output;
567     int code;
568
569     /* No meta key yet -- that'll be rather fun. */
570
571     /* Keys that we handle locally */
572     if (event->modifiers & shiftKey) {
573         switch (event->message & keyCodeMask) {
574           case K_PRIOR: /* shift-pageup */
575             term_scroll(s->term, 0, -(s->term->rows - 1));
576             return 0;
577           case K_NEXT:  /* shift-pagedown */
578             term_scroll(s->term, 0, +(s->term->rows - 1));
579             return 0;
580         }
581     }
582
583     /*
584      * Control-2 should return ^@ (0x00), Control-6 should return
585      * ^^ (0x1E), and Control-Minus should return ^_ (0x1F). Since
586      * the DOS keyboard handling did it, and we have nothing better
587      * to do with the key combo in question, we'll also map
588      * Control-Backquote to ^\ (0x1C).
589      */
590
591     if (event->modifiers & controlKey) {
592         switch (event->message & charCodeMask) {
593           case ' ': case '2':
594             *p++ = 0x00;
595             return p - output;
596           case '`':
597             *p++ = 0x1c;
598             return p - output;
599           case '6':
600             *p++ = 0x1e;
601             return p - output;
602           case '/':
603             *p++ = 0x1f;
604             return p - output;
605         }
606     }
607
608     /*
609      * First, all the keys that do tilde codes. (ESC '[' nn '~',
610      * for integer decimal nn.)
611      *
612      * We also deal with the weird ones here. Linux VCs replace F1
613      * to F5 by ESC [ [ A to ESC [ [ E. rxvt doesn't do _that_, but
614      * does replace Home and End (1~ and 4~) by ESC [ H and ESC O w
615      * respectively.
616      */
617     code = 0;
618     switch (event->message & keyCodeMask) {
619       case K_F1: code = (event->modifiers & shiftKey ? 23 : 11); break;
620       case K_F2: code = (event->modifiers & shiftKey ? 24 : 12); break;
621       case K_F3: code = (event->modifiers & shiftKey ? 25 : 13); break;
622       case K_F4: code = (event->modifiers & shiftKey ? 26 : 14); break;
623       case K_F5: code = (event->modifiers & shiftKey ? 28 : 15); break;
624       case K_F6: code = (event->modifiers & shiftKey ? 29 : 17); break;
625       case K_F7: code = (event->modifiers & shiftKey ? 31 : 18); break;
626       case K_F8: code = (event->modifiers & shiftKey ? 32 : 19); break;
627       case K_F9: code = (event->modifiers & shiftKey ? 33 : 20); break;
628       case K_F10: code = (event->modifiers & shiftKey ? 34 : 21); break;
629       case K_F11: code = 23; break;
630       case K_F12: code = 24; break;
631       case K_HOME: code = 1; break;
632       case K_INSERT: code = 2; break;
633       case K_DELETE: code = 3; break;
634       case K_END: code = 4; break;
635       case K_PRIOR: code = 5; break;
636       case K_NEXT: code = 6; break;
637     }
638     if (s->cfg.funky_type == 1 && code >= 11 && code <= 15) {
639         p += sprintf((char *)p, "\x1B[[%c", code + 'A' - 11);
640         return p - output;
641     }
642     if (s->cfg.rxvt_homeend && (code == 1 || code == 4)) {
643         p += sprintf((char *)p, code == 1 ? "\x1B[H" : "\x1BOw");
644         return p - output;
645     }
646     if (code) {
647         p += sprintf((char *)p, "\x1B[%d~", code);
648         return p - output;
649     }
650
651     if (s->term->app_keypad_keys) {
652         switch (event->message & keyCodeMask) {
653           case KP_ENTER: p += sprintf((char *)p, "\x1BOM"); return p - output;
654           case KP_CLEAR: p += sprintf((char *)p, "\x1BOP"); return p - output;
655           case KP_EQUAL: p += sprintf((char *)p, "\x1BOQ"); return p - output;
656           case KP_SLASH: p += sprintf((char *)p, "\x1BOR"); return p - output;
657           case KP_STAR:  p += sprintf((char *)p, "\x1BOS"); return p - output;
658           case KP_PLUS:  p += sprintf((char *)p, "\x1BOl"); return p - output;
659           case KP_MINUS: p += sprintf((char *)p, "\x1BOm"); return p - output;
660           case KP_DOT:   p += sprintf((char *)p, "\x1BOn"); return p - output;
661           case KP_0:     p += sprintf((char *)p, "\x1BOp"); return p - output;
662           case KP_1:     p += sprintf((char *)p, "\x1BOq"); return p - output;
663           case KP_2:     p += sprintf((char *)p, "\x1BOr"); return p - output;
664           case KP_3:     p += sprintf((char *)p, "\x1BOs"); return p - output;
665           case KP_4:     p += sprintf((char *)p, "\x1BOt"); return p - output;
666           case KP_5:     p += sprintf((char *)p, "\x1BOu"); return p - output;
667           case KP_6:     p += sprintf((char *)p, "\x1BOv"); return p - output;
668           case KP_7:     p += sprintf((char *)p, "\x1BOw"); return p - output;
669           case KP_8:     p += sprintf((char *)p, "\x1BOx"); return p - output;
670           case KP_9:     p += sprintf((char *)p, "\x1BOy"); return p - output;
671         }
672     }
673
674     switch (event->message & keyCodeMask) {
675       case K_UP:
676         p += sprintf((char *)p,
677                      s->term->app_cursor_keys ? "\x1BOA" : "\x1B[A");
678         return p - output;
679       case K_DOWN:
680         p += sprintf((char *)p,
681                      s->term->app_cursor_keys ? "\x1BOB" : "\x1B[B");
682         return p - output;
683       case K_RIGHT:
684         p += sprintf((char *)p,
685                      s->term->app_cursor_keys ? "\x1BOC" : "\x1B[C");
686         return p - output;
687       case K_LEFT:
688         p += sprintf((char *)p,
689                      s->term->app_cursor_keys ? "\x1BOD" : "\x1B[D");
690         return p - output;
691       case KP_ENTER:
692         *p++ = 0x0d;
693         return p - output;
694       case K_BS:
695         *p++ = (s->cfg.bksp_is_delete ? 0x7f : 0x08);
696         return p - output;
697       default:
698         *p++ = event->message & charCodeMask;
699         return p - output;
700     }
701 }
702
703 void request_paste(void *frontend)
704 {
705     Session *s = frontend;
706
707     /*
708      * In the Mac OS, pasting is synchronous: we can read the
709      * clipboard with no difficulty, so request_paste() can just go
710      * ahead and paste.
711      */
712     term_do_paste(s->term);
713 }
714
715 void mac_growterm(WindowPtr window, EventRecord *event) {
716     Rect limits;
717     long grow_result;
718     int newrows, newcols;
719     Session *s;
720
721     s = (Session *)GetWRefCon(window);
722     SetRect(&limits, s->font_width + 15, s->font_height, SHRT_MAX, SHRT_MAX);
723     grow_result = GrowWindow(window, event->where, &limits);
724     if (grow_result != 0) {
725         newrows = HiWord(grow_result) / s->font_height;
726         newcols = (LoWord(grow_result) - 15) / s->font_width;
727         mac_adjustsize(s, newrows, newcols);
728         term_size(s->term, newrows, newcols, s->cfg.savelines);
729     }
730 }
731
732 void mac_activateterm(WindowPtr window, Boolean active) {
733     Session *s;
734
735     s = (Session *)GetWRefCon(window);
736     s->term->has_focus = active;
737     term_update(s->term);
738     if (active)
739         ShowControl(s->scrollbar);
740     else {
741         if (HAVE_COLOR_QD())
742             PmBackColor(DEFAULT_BG);/* HideControl clears behind the control */
743         else
744             BackColor(blackColor);
745         HideControl(s->scrollbar);
746     }
747     mac_drawgrowicon(s);
748 }
749
750 void mac_updateterm(WindowPtr window) {
751     Session *s;
752
753     s = (Session *)GetWRefCon(window);
754     SetPort(window);
755     BeginUpdate(window);
756     pre_paint(s);
757     term_paint(s->term, s,
758                PTOCC((*window->visRgn)->rgnBBox.left),
759                PTOCR((*window->visRgn)->rgnBBox.top),
760                PTOCC((*window->visRgn)->rgnBBox.right),
761                PTOCR((*window->visRgn)->rgnBBox.bottom), 1);
762     /* Restore default colours in case the Window Manager uses them */
763     if (HAVE_COLOR_QD()) {
764         PmForeColor(DEFAULT_FG);
765         PmBackColor(DEFAULT_BG);
766     } else {
767         ForeColor(whiteColor);
768         BackColor(blackColor);
769     }
770     if (FrontWindow() != window)
771         EraseRect(&(*s->scrollbar)->contrlRect);
772     UpdateControls(window, window->visRgn);
773     mac_drawgrowicon(s);
774     post_paint(s);
775     EndUpdate(window);
776 }
777
778 static void mac_drawgrowicon(Session *s) {
779     Rect clip;
780
781     SetPort(s->window);
782     /* Stop DrawGrowIcon giving us space for a horizontal scrollbar */
783     SetRect(&clip, s->window->portRect.right - 15, SHRT_MIN,
784             SHRT_MAX, SHRT_MAX);
785     ClipRect(&clip);
786     DrawGrowIcon(s->window);
787     clip.left = SHRT_MIN;
788     ClipRect(&clip);
789 }    
790
791 struct do_text_args {
792     Session *s;
793     Rect textrect;
794     Rect leadrect;
795     char *text;
796     int len;
797     unsigned long attr;
798     int lattr;
799 };
800
801 /*
802  * Call from the terminal emulator to draw a bit of text
803  *
804  * x and y are text row and column (zero-based)
805  */
806 void do_text(Context ctx, int x, int y, char *text, int len,
807              unsigned long attr, int lattr) {
808     Session *s = ctx;
809     int style = 0;
810     struct do_text_args a;
811     RgnHandle textrgn;
812
813     SetPort(s->window);
814     
815     /* First check this text is relevant */
816     a.textrect.top = y * s->font_height;
817     a.textrect.bottom = (y + 1) * s->font_height;
818     a.textrect.left = x * s->font_width;
819     a.textrect.right = (x + len) * s->font_width;
820     if (!RectInRgn(&a.textrect, s->window->visRgn))
821         return;
822
823     a.s = s;
824     a.text = text;
825     a.len = len;
826     a.attr = attr;
827     a.lattr = lattr;
828     if (s->font_leading > 0)
829         SetRect(&a.leadrect,
830                 a.textrect.left, a.textrect.bottom - s->font_leading,
831                 a.textrect.right, a.textrect.bottom);
832     else
833         SetRect(&a.leadrect, 0, 0, 0, 0);
834     SetPort(s->window);
835     TextFont(s->fontnum);
836     if (s->cfg.fontisbold || (attr & ATTR_BOLD) && !s->cfg.bold_colour)
837         style |= bold;
838     if (attr & ATTR_UNDER)
839         style |= underline;
840     TextFace(style);
841     TextSize(s->cfg.fontheight);
842     SetFractEnable(FALSE); /* We want characters on pixel boundaries */
843     if (HAVE_COLOR_QD())
844         if (style & bold) {
845             SpaceExtra(s->font_boldadjust << 16);
846             CharExtra(s->font_boldadjust << 16);
847         } else {
848             SpaceExtra(0);
849             CharExtra(0);
850         }
851     textrgn = NewRgn();
852     RectRgn(textrgn, &a.textrect);
853     if (HAVE_COLOR_QD())
854         DeviceLoop(textrgn, &do_text_for_device_upp, (long)&a, 0);
855     else
856         do_text_for_device(1, 0, NULL, (long)&a);
857     DisposeRgn(textrgn);
858     /* Tell the window manager about it in case this isn't an update */
859     ValidRect(&a.textrect);
860 }
861
862 static pascal void do_text_for_device(short depth, short devflags,
863                                       GDHandle device, long cookie) {
864     struct do_text_args *a;
865     int bgcolour, fgcolour, bright;
866
867     a = (struct do_text_args *)cookie;
868
869     bright = (a->attr & ATTR_BOLD) && a->s->cfg.bold_colour;
870
871     TextMode(a->attr & ATTR_REVERSE ? notSrcCopy : srcCopy);
872
873     switch (depth) {
874       case 1:
875         /* XXX This should be done with a _little_ more configurability */
876         ForeColor(whiteColor);
877         BackColor(blackColor);
878         if (a->attr & TATTR_ACTCURS)
879             TextMode(a->attr & ATTR_REVERSE ? srcCopy : notSrcCopy);
880         break;
881       case 2:
882         if (a->attr & TATTR_ACTCURS) {
883             PmForeColor(CURSOR_FG);
884             PmBackColor(CURSOR_BG);
885             TextMode(srcCopy);
886         } else {
887             PmForeColor(bright ? DEFAULT_FG_BOLD : DEFAULT_FG);
888             PmBackColor(DEFAULT_BG);
889         }
890         break;
891       default:
892         if (a->attr & TATTR_ACTCURS) {
893             fgcolour = CURSOR_FG;
894             bgcolour = CURSOR_BG;
895             TextMode(srcCopy);
896         } else {
897             fgcolour = ((a->attr & ATTR_FGMASK) >> ATTR_FGSHIFT) * 2;
898             bgcolour = ((a->attr & ATTR_BGMASK) >> ATTR_BGSHIFT) * 2;
899             if (bright)
900                 if (a->attr & ATTR_REVERSE)
901                     bgcolour++;
902                 else
903                     fgcolour++;
904         }
905         PmForeColor(fgcolour);
906         PmBackColor(bgcolour);
907         break;
908     }
909
910     if (a->attr & ATTR_REVERSE)
911         PaintRect(&a->leadrect);
912     else
913         EraseRect(&a->leadrect);
914     MoveTo(a->textrect.left, a->textrect.top + a->s->font_ascent);
915     /* FIXME: Sort out bold width adjustments on Original QuickDraw. */
916     DrawText(a->text, 0, a->len);
917
918     if (a->attr & TATTR_PASCURS) {
919         PenNormal();
920         switch (depth) {
921           case 1:
922             PenMode(patXor);
923             break;
924           default:
925             PmForeColor(CURSOR_BG);
926             break;
927         }
928         FrameRect(&a->textrect);
929     }
930 }
931
932 void do_cursor(Context ctx, int x, int y, char *text, int len,
933              unsigned long attr, int lattr)
934 {
935
936     do_text(ctx, x, y, text, len, attr, lattr);
937 }
938
939 /*
940  * Call from the terminal emulator to get its graphics context.
941  * Should probably be called start_redraw or something.
942  */
943 void pre_paint(Session *s) {
944
945     s->attr_mask = ATTR_INVALID;
946     if (HAVE_COLOR_QD())
947         DeviceLoop(s->window->visRgn, &mac_set_attr_mask_upp, (long)s, 0);
948     else
949         mac_set_attr_mask(1, 0, NULL, (long)s);
950 }
951
952 Context get_ctx(void *frontend) {
953     Session *s = frontend;
954
955     pre_paint(s);
956     return s;
957 }
958
959 void free_ctx(Context ctx) {
960
961 }
962
963 static pascal void mac_set_attr_mask(short depth, short devflags,
964                                      GDHandle device, long cookie) {
965
966     Session *s = (Session *)cookie;
967
968     switch (depth) {
969       default:
970         s->attr_mask |= ATTR_FGMASK | ATTR_BGMASK;
971         /* FALLTHROUGH */
972       case 2:
973         s->attr_mask |= ATTR_BOLD;
974         /* FALLTHROUGH */
975       case 1:
976         s->attr_mask |= ATTR_UNDER | ATTR_REVERSE | TATTR_ACTCURS |
977             TATTR_PASCURS | ATTR_ASCII | ATTR_GBCHR | ATTR_LINEDRW |
978             (s->cfg.bold_colour ? 0 : ATTR_BOLD); 
979         break;
980     }
981 }
982
983 /*
984  * Presumably this does something in Windows
985  */
986 void post_paint(Session *s) {
987
988 }
989
990 /*
991  * Set the scroll bar position
992  *
993  * total is the line number of the bottom of the working screen
994  * start is the line number of the top of the display
995  * page is the length of the displayed page
996  */
997 void set_sbar(void *frontend, int total, int start, int page) {
998     Session *s = frontend;
999
1000     /* We don't redraw until we've set everything up, to avoid glitches */
1001     (*s->scrollbar)->contrlMin = 0;
1002     (*s->scrollbar)->contrlMax = total - page;
1003     SetControlValue(s->scrollbar, start);
1004 #if TARGET_RT_CFM
1005     /* XXX: This doesn't link for me. */
1006     if (mac_gestalts.cntlattr & gestaltControlMgrPresent)
1007         SetControlViewSize(s->scrollbar, page);
1008 #endif
1009 }
1010
1011 void sys_cursor(void *frontend, int x, int y)
1012 {
1013     /*
1014      * I think his is meaningless under Mac OS.
1015      */
1016 }
1017
1018 /*
1019  * This is still called when mode==BELL_VISUAL, even though the
1020  * visual bell is handled entirely within terminal.c, because we
1021  * may want to perform additional actions on any kind of bell (for
1022  * example, taskbar flashing in Windows).
1023  */
1024 void beep(void *frontend, int mode)
1025 {
1026     if (mode != BELL_VISUAL)
1027         SysBeep(30);
1028     /*
1029      * XXX We should indicate the relevant window and/or use the
1030      * Notification Manager
1031      */
1032 }
1033
1034 int char_width(Context ctx, int uc)
1035 {
1036     /*
1037      * Until we support exciting character-set stuff, assume all chars are
1038      * single-width.
1039      */
1040     return 1;
1041 }
1042
1043 /*
1044  * Set icon string -- a no-op here (Windowshade?)
1045  */
1046 void set_icon(void *frontend, char *icon) {
1047     Session *s = frontend;
1048
1049 }
1050
1051 /*
1052  * Set the window title
1053  */
1054 void set_title(void *frontend, char *title) {
1055     Session *s = frontend;
1056     Str255 mactitle;
1057
1058     mactitle[0] = sprintf((char *)&mactitle[1], "%s", title);
1059     SetWTitle(s->window, mactitle);
1060 }
1061
1062 /*
1063  * set or clear the "raw mouse message" mode
1064  */
1065 void set_raw_mouse_mode(void *frontend, int activate)
1066 {
1067     Session *s = frontend;
1068
1069     s->raw_mouse = activate;
1070     /* FIXME: Should call mac_updatetermcursor as appropriate. */
1071 }
1072
1073 /*
1074  * Resize the window at the emulator's request
1075  */
1076 void request_resize(void *frontend, int w, int h) {
1077     Session *s = frontend;
1078
1079     s->term->cols = w;
1080     s->term->rows = h;
1081     mac_initfont(s);
1082 }
1083
1084 /*
1085  * Iconify (actually collapse) the window at the emulator's request.
1086  */
1087 void set_iconic(void *frontend, int iconic)
1088 {
1089     Session *s = frontend;
1090     UInt32 features;
1091
1092     if (mac_gestalts.apprvers >= 0x0100 &&
1093         GetWindowFeatures(s->window, &features) == noErr &&
1094         (features & kWindowCanCollapse))
1095         CollapseWindow(s->window, iconic);
1096 }
1097
1098 /*
1099  * Move the window in response to a server-side request.
1100  */
1101 void move_window(void *frontend, int x, int y)
1102 {
1103     Session *s = frontend;
1104
1105     MoveWindow(s->window, x, y, FALSE);
1106 }
1107
1108 /*
1109  * Move the window to the top or bottom of the z-order in response
1110  * to a server-side request.
1111  */
1112 void set_zorder(void *frontend, int top)
1113 {
1114     Session *s = frontend;
1115
1116     /* 
1117      * We also change the input focus to point to the topmost window,
1118      * since that's probably what the Human Interface Guidelines would
1119      * like us to do.
1120      */
1121     if (top)
1122         SelectWindow(s->window);
1123     else
1124         SendBehind(s->window, NULL);
1125 }
1126
1127 /*
1128  * Refresh the window in response to a server-side request.
1129  */
1130 void refresh_window(void *frontend)
1131 {
1132     Session *s = frontend;
1133
1134     term_invalidate(s->term);
1135 }
1136
1137 /*
1138  * Maximise or restore the window in response to a server-side
1139  * request.
1140  */
1141 void set_zoomed(void *frontend, int zoomed)
1142 {
1143     Session *s = frontend;
1144
1145     ZoomWindow(s->window, zoomed ? inZoomOut : inZoomIn, FALSE);
1146 }
1147
1148 /*
1149  * Report whether the window is iconic, for terminal reports.
1150  */
1151 int is_iconic(void *frontend)
1152 {
1153     Session *s = frontend;
1154     UInt32 features;
1155
1156     if (mac_gestalts.apprvers >= 0x0100 &&
1157         GetWindowFeatures(s->window, &features) == noErr &&
1158         (features & kWindowCanCollapse))
1159         return IsWindowCollapsed(s->window);
1160     return FALSE;
1161 }
1162
1163 /*
1164  * Report the window's position, for terminal reports.
1165  */
1166 void get_window_pos(void *frontend, int *x, int *y)
1167 {
1168     Session *s = frontend;
1169
1170     *x = s->window->portRect.left;
1171     *y = s->window->portRect.top;
1172 }
1173
1174 /*
1175  * Report the window's pixel size, for terminal reports.
1176  */
1177 void get_window_pixels(void *frontend, int *x, int *y)
1178 {
1179     Session *s = frontend;
1180
1181     *x = s->window->portRect.right - s->window->portRect.left;
1182     *y = s->window->portRect.bottom - s->window->portRect.top;
1183 }
1184
1185 /*
1186  * Return the window or icon title.
1187  */
1188 char *get_window_title(void *frontend, int icon)
1189 {
1190     Session *s = frontend;
1191
1192     /* Erm, we don't save this at the moment */
1193     return "";
1194 }
1195
1196 /*
1197  * real_palette_set(): This does the actual palette-changing work on behalf
1198  * of palette_set().  Does _not_ call ActivatePalette() in case the caller
1199  * is doing a batch of updates.
1200  */
1201 static void real_palette_set(Session *s, int n, int r, int g, int b)
1202 {
1203     RGBColor col;
1204
1205     if (!HAVE_COLOR_QD())
1206         return;
1207     col.red   = r * 0x0101;
1208     col.green = g * 0x0101;
1209     col.blue  = b * 0x0101;
1210     SetEntryColor(s->palette, n, &col);
1211 }
1212
1213 /*
1214  * Set the logical palette.  Called by the terminal emulator.
1215  */
1216 void palette_set(void *frontend, int n, int r, int g, int b) {
1217     Session *s = frontend;
1218     static const int first[21] = {
1219         0, 2, 4, 6, 8, 10, 12, 14,
1220         1, 3, 5, 7, 9, 11, 13, 15,
1221         16, 17, 18, 20, 21
1222     };
1223     
1224     if (!HAVE_COLOR_QD())
1225         return;
1226     real_palette_set(s, first[n], r, g, b);
1227     if (first[n] == 18)
1228         real_palette_set(s, first[n]+1, r, g, b);
1229     if (first[n] == DEFAULT_BG)
1230         mac_adjustwinbg(s);
1231     ActivatePalette(s->window);
1232 }
1233
1234 /*
1235  * Reset to the default palette
1236  */
1237 void palette_reset(void *frontend) {
1238     Session *s = frontend;
1239     /* This maps colour indices in cfg to those used in our palette. */
1240     static const int ww[] = {
1241         6, 7, 8, 9, 10, 11, 12, 13,
1242         14, 15, 16, 17, 18, 19, 20, 21,
1243         0, 1, 2, 3, 4, 5
1244     };
1245     int i;
1246
1247     if (!HAVE_COLOR_QD())
1248         return;
1249
1250     assert(lenof(ww) == NCOLOURS);
1251
1252     for (i = 0; i < NCOLOURS; i++) {
1253         real_palette_set(s, i,
1254                          s->cfg.colours[ww[i]][0],
1255                          s->cfg.colours[ww[i]][1],
1256                          s->cfg.colours[ww[i]][2]);
1257     }
1258     mac_adjustwinbg(s);
1259     ActivatePalette(s->window);
1260     /* Palette Manager will generate update events as required. */
1261 }
1262
1263 /*
1264  * Scroll the screen. (`lines' is +ve for scrolling forward, -ve
1265  * for backward.)
1266  */
1267 void do_scroll(void *frontend, int topline, int botline, int lines) {
1268     Session *s = frontend;
1269     Rect r;
1270     RgnHandle update;
1271
1272     /* FIXME: This is seriously broken on Original QuickDraw.  No idea why. */
1273     SetPort(s->window);
1274     if (HAVE_COLOR_QD())
1275         PmBackColor(DEFAULT_BG);
1276     else
1277         BackColor(blackColor);
1278     update = NewRgn();
1279     SetRect(&r, 0, topline * s->font_height,
1280             s->term->cols * s->font_width, (botline + 1) * s->font_height);
1281     ScrollRect(&r, 0, - lines * s->font_height, update);
1282     /* XXX: move update region? */
1283     InvalRgn(update);
1284     DisposeRgn(update);
1285 }
1286
1287 void logevent(void *frontend, char *str) {
1288
1289     /* XXX Do something */
1290 }
1291
1292 /* Dummy routine, only required in plink. */
1293 void ldisc_update(void *frontend, int echo, int edit)
1294 {
1295 }
1296
1297 /*
1298  * Mac PuTTY doesn't support printing yet.
1299  */
1300 printer_job *printer_start_job(char *printer)
1301 {
1302
1303     return NULL;
1304 }
1305
1306 void printer_job_data(printer_job *pj, void *data, int len)
1307 {
1308 }
1309
1310 void printer_finish_job(printer_job *pj)
1311 {
1312 }
1313
1314 void frontend_keypress(void *handle)
1315 {
1316     /*
1317      * Keypress termination in non-Close-On-Exit mode is not
1318      * currently supported in PuTTY proper, because the window
1319      * always has a perfectly good Close button anyway. So we do
1320      * nothing here.
1321      */
1322     return;
1323 }
1324
1325 /*
1326  * Ask whether to wipe a session log file before writing to it.
1327  * Returns 2 for wipe, 1 for append, 0 for cancel (don't log).
1328  */
1329 int askappend(void *frontend, char *filename)
1330 {
1331
1332     /* FIXME: not implemented yet. */
1333     return 2;
1334 }
1335
1336 /*
1337  * Emacs magic:
1338  * Local Variables:
1339  * c-file-style: "simon"
1340  * End:
1341  */
1342