]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - macterm.c
39a0d9b7e6db7668e4bc70596b1077785026c939
[PuTTY.git] / macterm.c
1 /* $Id: macterm.c,v 1.1.2.34 1999/04/04 18:23:34 ben Exp $ */
2 /*
3  * Copyright (c) 1999 Simon Tatham
4  * Copyright (c) 1999 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 <Fonts.h>
36 #include <Gestalt.h>
37 #include <MacMemory.h>
38 #include <MacWindows.h>
39 #include <MixedMode.h>
40 #include <Palettes.h>
41 #include <Quickdraw.h>
42 #include <QuickdrawText.h>
43 #include <Resources.h>
44 #include <Scrap.h>
45 #include <Script.h>
46 #include <Sound.h>
47 #include <ToolUtils.h>
48
49 #include <limits.h>
50 #include <stdlib.h>
51 #include <stdio.h>
52 #include <string.h>
53
54 #include "macresid.h"
55 #include "putty.h"
56 #include "mac.h"
57
58 #define DEFAULT_FG      16
59 #define DEFAULT_FG_BOLD 17
60 #define DEFAULT_BG      18
61 #define DEFAULT_BG_BOLD 19
62 #define CURSOR_FG       20
63 #define CURSOR_FG_BOLD  21
64 #define CURSOR_BG       22
65 #define CURSOR_BG_BOLD  23
66
67 #define PTOCC(x) ((x) < 0 ? -(-(x - s->font_width - 1) / s->font_width) : \
68                             (x) / s->font_width)
69 #define PTOCR(y) ((y) < 0 ? -(-(y - s->font_height - 1) / s->font_height) : \
70                             (y) / s->font_height)
71
72 static void mac_initfont(Session *);
73 static void mac_initpalette(Session *);
74 static void mac_adjustwinbg(Session *);
75 static void mac_adjustsize(Session *, int, int);
76 static void mac_drawgrowicon(Session *s);
77 static pascal void mac_scrolltracker(ControlHandle, short);
78 static pascal void do_text_for_device(short, short, GDHandle, long);
79 static pascal void mac_set_attr_mask(short, short, GDHandle, long);
80 static int mac_keytrans(Session *, EventRecord *, unsigned char *);
81 static void text_click(Session *, EventRecord *);
82
83 #if TARGET_RT_MAC_CFM
84 static RoutineDescriptor mac_scrolltracker_upp =
85     BUILD_ROUTINE_DESCRIPTOR(uppControlActionProcInfo,
86                              (ProcPtr)mac_scrolltracker);
87 static RoutineDescriptor do_text_for_device_upp =
88     BUILD_ROUTINE_DESCRIPTOR(uppDeviceLoopDrawingProcInfo,
89                              (ProcPtr)do_text_for_device);
90 static RoutineDescriptor mac_set_attr_mask_upp =
91     BUILD_ROUTINE_DESCRIPTOR(uppDeviceLoopDrawingProcInfo,
92                              (ProcPtr)mac_set_attr_mask);
93 #else /* not TARGET_RT_MAC_CFM */
94 #define mac_scrolltracker_upp   mac_scrolltracker
95 #define do_text_for_device_upp  do_text_for_device
96 #define mac_set_attr_mask_upp   mac_set_attr_mask
97 #endif /* not TARGET_RT_MAC_CFM */
98
99 /*
100  * Temporary hack till I get the terminal emulator supporting multiple
101  * sessions
102  */
103
104 static void inbuf_putc(Session *s, int c) {
105     s->inbuf[s->inbuf_head] = c;
106     s->inbuf_head = (s->inbuf_head+1) & INBUF_MASK;
107 }
108
109 static void inbuf_putstr(Session *s, const char *c) {
110     while (*c)
111         inbuf_putc(s, *c++);
112 }
113
114 static void display_resource(Session *s, unsigned long type, short id) {
115     Handle h;
116     int len, i;
117     char *t;
118
119     h = GetResource(type, id);
120     if (h == NULL)
121         fatalbox("Can't get test resource");
122     SetResAttrs(h, GetResAttrs(h) | resLocked);
123     t = *h;
124     len = GetResourceSizeOnDisk(h);
125     for (i = 0; i < len; i++) {
126         inbuf_putc(s, t[i]);
127         term_out(s);
128     }
129     SetResAttrs(h, GetResAttrs(h) & ~resLocked);
130     ReleaseResource(h);
131 }
132         
133
134 void mac_newsession(void) {
135     Session *s;
136     UInt32 starttime;
137     char msg[128];
138
139     /* This should obviously be initialised by other means */
140     s = smalloc(sizeof(*s));
141     memset(s, 0, sizeof(*s));
142     mac_loadconfig(&s->cfg);
143     s->back = &telnet_backend;
144         
145     /* XXX: Own storage management? */
146     if (mac_gestalts.qdvers == gestaltOriginalQD)
147         s->window = GetNewWindow(wTerminal, NULL, (WindowPtr)-1);
148     else
149         s->window = GetNewCWindow(wTerminal, NULL, (WindowPtr)-1);
150     SetWRefCon(s->window, (long)s);
151     s->scrollbar = GetNewControl(cVScroll, s->window);
152     term_init(s);
153     term_size(s, s->cfg.height, s->cfg.width, s->cfg.savelines);
154     mac_initfont(s);
155     mac_initpalette(s);
156     s->attr_mask = ATTR_MASK;
157     /* Set to FALSE to not get palette updates in the background. */
158     SetPalette(s->window, s->palette, TRUE); 
159     ActivatePalette(s->window);
160     ShowWindow(s->window);
161     s->back->init(s);
162 /*     starttime = TickCount(); */
163 /*     display_resource(s, 'pTST', 128); */
164 /*     sprintf(msg, "Elapsed ticks: %d\015\012", TickCount() - starttime); */
165 /*     inbuf_putstr(s, msg); */
166 /*     term_out(s); */
167 }
168
169 static void mac_initfont(Session *s) {
170     Str255 macfont;
171     FontInfo fi;
172  
173     SetPort(s->window);
174     macfont[0] = sprintf((char *)&macfont[1], "%s", s->cfg.font);
175     GetFNum(macfont, &s->fontnum);
176     TextFont(s->fontnum);
177     TextFace(s->cfg.fontisbold ? bold : 0);
178     TextSize(s->cfg.fontheight);
179     GetFontInfo(&fi);
180     s->font_width = CharWidth('W'); /* Well, it's what NCSA uses. */
181     s->font_ascent = fi.ascent;
182     s->font_leading = fi.leading;
183     s->font_height = s->font_ascent + fi.descent + s->font_leading;
184     if (!s->cfg.bold_colour) {
185         TextFace(bold);
186         s->font_boldadjust = s->font_width - CharWidth('W');
187     } else
188         s->font_boldadjust = 0;
189     mac_adjustsize(s, s->rows, s->cols);
190 }
191
192 /*
193  * To be called whenever the window size changes.
194  * rows and cols should be desired values.
195  * It's assumed the terminal emulator will be informed, and will set rows
196  * and cols for us.
197  */
198 static void mac_adjustsize(Session *s, int newrows, int newcols) {
199     int winwidth, winheight;
200
201     winwidth = newcols * s->font_width + 15;
202     winheight = newrows * s->font_height;
203     SizeWindow(s->window, winwidth, winheight, true);
204     HideControl(s->scrollbar);
205     MoveControl(s->scrollbar, winwidth - 15, -1);
206     SizeControl(s->scrollbar, 16, winheight - 13);
207     ShowControl(s->scrollbar);
208 }
209
210 static void mac_initpalette(Session *s) {
211   
212     if (mac_gestalts.qdvers == gestaltOriginalQD)
213         return;
214     s->palette = NewPalette((*s->cfg.colours)->pmEntries,
215                             NULL, pmCourteous, 0);
216     if (s->palette == NULL)
217         fatalbox("Unable to create palette");
218     CopyPalette(s->cfg.colours, s->palette, 0, 0,
219                 (*s->cfg.colours)->pmEntries);
220     mac_adjustwinbg(s);
221 }
222
223 /*
224  * Set the background colour of the window correctly.  Should be
225  * called whenever the default background changes.
226  */
227 static void mac_adjustwinbg(Session *s) {
228
229 #if TARGET_RT_CFM /* XXX doesn't link (at least for 68k) */
230     if (mac_gestalts.windattr & gestaltWindowMgrPresent)
231         SetWindowContentColor(s->window,
232                               &(*s->palette)->pmInfo[DEFAULT_BG].ciRGB);
233     else
234 #endif
235     {
236         if (s->wctab == NULL)
237             s->wctab = (WCTabHandle)NewHandle(sizeof(**s->wctab));
238         if (s->wctab == NULL)
239             return; /* do without */
240         (*s->wctab)->wCSeed = 0;
241         (*s->wctab)->wCReserved = 0;
242         (*s->wctab)->ctSize = 0;
243         (*s->wctab)->ctTable[0].value = wContentColor;
244         (*s->wctab)->ctTable[0].rgb = (*s->palette)->pmInfo[DEFAULT_BG].ciRGB;
245         SetWinColor(s->window, s->wctab);
246     }
247 }
248
249 /*
250  * Set the cursor shape correctly
251  */
252 void mac_adjusttermcursor(WindowPtr window, Point mouse, RgnHandle cursrgn) {
253     Session *s;
254     ControlHandle control;
255     short part;
256     int x, y;
257
258     SetPort(window);
259     s = (Session *)GetWRefCon(window);
260     GlobalToLocal(&mouse);
261     part = FindControl(mouse, window, &control);
262     if (control == s->scrollbar) {
263         SetCursor(&qd.arrow);
264         RectRgn(cursrgn, &(*s->scrollbar)->contrlRect);
265         SectRgn(cursrgn, window->visRgn, cursrgn);
266     } else {
267         x = mouse.h / s->font_width;
268         y = mouse.v / s->font_height;
269         SetCursor(*GetCursor(iBeamCursor));
270         /* Ask for shape changes if we leave this character cell. */
271         SetRectRgn(cursrgn, x * s->font_width, y * s->font_height,
272                    (x + 1) * s->font_width, (y + 1) * s->font_height);
273         SectRgn(cursrgn, window->visRgn, cursrgn);
274     }
275 }
276
277 /*
278  * Enable/disable menu items based on the active terminal window.
279  */
280 void mac_adjusttermmenus(WindowPtr window) {
281     Session *s;
282     MenuHandle menu;
283     long offset;
284
285     s = (Session *)GetWRefCon(window);
286     menu = GetMenuHandle(mEdit);
287     EnableItem(menu, 0);
288     DisableItem(menu, iUndo);
289     DisableItem(menu, iCut);
290     if (term_hasselection(s))
291         EnableItem(menu, iCopy);
292     else
293         DisableItem(menu, iCopy);
294     if (GetScrap(NULL, 'TEXT', &offset) == noTypeErr)
295         DisableItem(menu, iPaste);
296     else
297         EnableItem(menu, iPaste);
298     DisableItem(menu, iClear);
299     EnableItem(menu, iSelectAll);
300 }
301
302 void mac_menuterm(WindowPtr window, short menu, short item) {
303     Session *s;
304
305     s = (Session *)GetWRefCon(window);
306     switch (menu) {
307       case mEdit:
308         switch (item) {
309           case iCopy:
310             term_copy(s);
311             break;
312           case iPaste:
313             term_paste(s);
314             break;
315         }
316     }
317 }
318             
319 void mac_clickterm(WindowPtr window, EventRecord *event) {
320     Session *s;
321     Point mouse;
322     ControlHandle control;
323     int part;
324
325     s = (Session *)GetWRefCon(window);
326     SetPort(window);
327     mouse = event->where;
328     GlobalToLocal(&mouse);
329     part = FindControl(mouse, window, &control);
330     if (control == s->scrollbar) {
331         switch (part) {
332           case kControlIndicatorPart:
333             if (TrackControl(control, mouse, NULL) == kControlIndicatorPart)
334                 term_scroll(s, +1, GetControlValue(control));
335             break;
336           case kControlUpButtonPart:
337           case kControlDownButtonPart:
338           case kControlPageUpPart:
339           case kControlPageDownPart:
340             TrackControl(control, mouse, &mac_scrolltracker_upp);
341             break;
342         }
343     } else {
344         text_click(s, event);
345     }
346 }
347
348 static void text_click(Session *s, EventRecord *event) {
349     Point localwhere;
350     int row, col;
351     static UInt32 lastwhen = 0;
352     static Session *lastsess = NULL;
353     static int lastrow = -1, lastcol = -1;
354     static Mouse_Action lastact = MA_NOTHING;
355
356     SetPort(s->window);
357     localwhere = event->where;
358     GlobalToLocal(&localwhere);
359
360     col = PTOCC(localwhere.h);
361     row = PTOCR(localwhere.v);
362     if (event->when - lastwhen < GetDblTime() &&
363         row == lastrow && col == lastcol && s == lastsess)
364         lastact = (lastact == MA_CLICK ? MA_2CLK :
365                    lastact == MA_2CLK ? MA_3CLK :
366                    lastact == MA_3CLK ? MA_CLICK : MA_NOTHING);
367     else
368         lastact = MA_CLICK;
369     term_mouse(s, event->modifiers & shiftKey ? MB_EXTEND : MB_SELECT, lastact,
370                col, row);
371     lastsess = s;
372     lastrow = row;
373     lastcol = col;
374     while (StillDown()) {
375         GetMouse(&localwhere);
376         col = PTOCC(localwhere.h);
377         row = PTOCR(localwhere.v);
378         term_mouse(s, event->modifiers & shiftKey ? MB_EXTEND : MB_SELECT,
379                    MA_DRAG, col, row);
380         if (row > s->rows - 1)
381             term_scroll(s, 0, row - (s->rows - 1));
382         else if (row < 0)
383             term_scroll(s, 0, row);
384     }
385     term_mouse(s, event->modifiers & shiftKey ? MB_EXTEND : MB_SELECT,
386                MA_RELEASE, col, row);
387     lastwhen = TickCount();
388 }
389
390 void write_clip(void *data, int len) {
391     
392     if (ZeroScrap() != noErr)
393         return;
394     PutScrap(len, 'TEXT', data);
395 }
396
397 void get_clip(void **p, int *lenp) {
398     static Handle h = NULL;
399     long offset;
400
401     if (p == NULL) {
402         /* release memory */
403         if (h != NULL)
404             DisposeHandle(h);
405         h = NULL;
406     } else
407         if (GetScrap(NULL, 'TEXT', &offset) > 0) {
408             h = NewHandle(0);
409             *lenp = GetScrap(h, 'TEXT', &offset);
410             HLock(h);
411             *p = *h;
412             if (*p == NULL || *lenp <= 0)
413                 fatalbox("Empty scrap");
414         } else {
415             *p = NULL;
416             *lenp = 0;
417         }
418 }
419
420 static pascal void mac_scrolltracker(ControlHandle control, short part) {
421     Session *s;
422
423     s = (Session *)GetWRefCon((*control)->contrlOwner);
424     switch (part) {
425       case kControlUpButtonPart:
426         term_scroll(s, 0, -1);
427         break;
428       case kControlDownButtonPart:
429         term_scroll(s, 0, +1);
430         break;
431       case kControlPageUpPart:
432         term_scroll(s, 0, -(s->rows - 1));
433         break;
434       case kControlPageDownPart:
435         term_scroll(s, 0, +(s->rows - 1));
436         break;
437     }
438 }
439
440 #define K_BS    0x3300
441 #define K_F1    0x7a00
442 #define K_F2    0x7800
443 #define K_F3    0x6300
444 #define K_F4    0x7600
445 #define K_F5    0x6000
446 #define K_F6    0x6100
447 #define K_F7    0x6200
448 #define K_F8    0x6400
449 #define K_F9    0x6500
450 #define K_F10   0x6d00
451 #define K_F11   0x6700
452 #define K_F12   0x6f00
453 #define K_F13   0x6900
454 #define K_F14   0x6b00
455 #define K_F15   0x7100
456 #define K_INSERT 0x7200
457 #define K_HOME  0x7300
458 #define K_PRIOR 0x7400
459 #define K_DELETE 0x7500
460 #define K_END   0x7700
461 #define K_NEXT  0x7900
462 #define K_LEFT  0x7b00
463 #define K_RIGHT 0x7c00
464 #define K_DOWN  0x7d00
465 #define K_UP    0x7e00
466 #define KP_0    0x5200
467 #define KP_1    0x5300
468 #define KP_2    0x5400
469 #define KP_3    0x5500
470 #define KP_4    0x5600
471 #define KP_5    0x5700
472 #define KP_6    0x5800
473 #define KP_7    0x5900
474 #define KP_8    0x5b00
475 #define KP_9    0x5c00
476 #define KP_CLEAR 0x4700
477 #define KP_EQUAL 0x5100
478 #define KP_SLASH 0x4b00
479 #define KP_STAR 0x4300
480 #define KP_PLUS 0x4500
481 #define KP_MINUS 0x4e00
482 #define KP_DOT  0x4100
483 #define KP_ENTER 0x4c00
484
485 void mac_keyterm(WindowPtr window, EventRecord *event) {
486     unsigned char buf[20];
487     int len;
488     Session *s;
489
490     s = (Session *)GetWRefCon(window);
491     len = mac_keytrans(s, event, buf);
492     s->back->send(s, (char *)buf, len);
493 }
494
495 static UInt32 mac_rekey(EventModifiers newmodifiers, UInt32 oldmessage) {
496     UInt32 transresult, state;
497     Ptr kchr;
498
499     state = 0;
500     kchr = (Ptr)GetScriptManagerVariable(smKCHRCache);
501     transresult = KeyTranslate(kchr,
502                                (oldmessage & keyCodeMask) >> 8 |
503                                newmodifiers & 0xff00,
504                                &state);
505     /*
506      * KeyTranslate returns two character codes.  We only worry about
507      * one.  Yes, this is slightly bogus, but it makes life less
508      * painful.
509      */
510     return oldmessage & ~charCodeMask | transresult & 0xff;
511 }
512
513
514 static int mac_keytrans(Session *s, EventRecord *event,
515                         unsigned char *output) {
516     unsigned char *p = output;
517     int code;
518
519     /* No meta key yet -- that'll be rather fun. */
520
521     /* Check if the meta "key" was held down */
522
523     if ((event->modifiers & s->cfg.meta_modifiers) == s->cfg.meta_modifiers) {
524         *p++ = '\033';
525         event->modifiers &= ~s->cfg.meta_modifiers;
526         event->message = mac_rekey(event->modifiers, event->message);
527     }
528
529     /* Keys that we handle locally */
530     if (event->modifiers & shiftKey) {
531         switch (event->message & keyCodeMask) {
532           case K_PRIOR: /* shift-pageup */
533             term_scroll(s, 0, -(s->rows - 1));
534             return 0;
535           case K_NEXT:  /* shift-pagedown */
536             term_scroll(s, 0, +(s->rows - 1));
537             return 0;
538         }
539     }
540
541     /*
542      * Control-2 should return ^@ (0x00), Control-6 should return
543      * ^^ (0x1E), and Control-Minus should return ^_ (0x1F). Since
544      * the DOS keyboard handling did it, and we have nothing better
545      * to do with the key combo in question, we'll also map
546      * Control-Backquote to ^\ (0x1C).
547      */
548
549     if (event->modifiers & controlKey) {
550         switch (event->message & charCodeMask) {
551           case ' ': case '2':
552             *p++ = 0x00;
553             return p - output;
554           case '`':
555             *p++ = 0x1c;
556             return p - output;
557           case '6':
558             *p++ = 0x1e;
559             return p - output;
560           case '/':
561             *p++ = 0x1f;
562             return p - output;
563         }
564     }
565
566     /*
567      * First, all the keys that do tilde codes. (ESC '[' nn '~',
568      * for integer decimal nn.)
569      *
570      * We also deal with the weird ones here. Linux VCs replace F1
571      * to F5 by ESC [ [ A to ESC [ [ E. rxvt doesn't do _that_, but
572      * does replace Home and End (1~ and 4~) by ESC [ H and ESC O w
573      * respectively.
574      */
575     code = 0;
576     switch (event->message & keyCodeMask) {
577       case K_F1: code = (event->modifiers & shiftKey ? 23 : 11); break;
578       case K_F2: code = (event->modifiers & shiftKey ? 24 : 12); break;
579       case K_F3: code = (event->modifiers & shiftKey ? 25 : 13); break;
580       case K_F4: code = (event->modifiers & shiftKey ? 26 : 14); break;
581       case K_F5: code = (event->modifiers & shiftKey ? 28 : 15); break;
582       case K_F6: code = (event->modifiers & shiftKey ? 29 : 17); break;
583       case K_F7: code = (event->modifiers & shiftKey ? 31 : 18); break;
584       case K_F8: code = (event->modifiers & shiftKey ? 32 : 19); break;
585       case K_F9: code = (event->modifiers & shiftKey ? 33 : 20); break;
586       case K_F10: code = (event->modifiers & shiftKey ? 34 : 21); break;
587       case K_F11: code = 23; break;
588       case K_F12: code = 24; break;
589       case K_HOME: code = 1; break;
590       case K_INSERT: code = 2; break;
591       case K_DELETE: code = 3; break;
592       case K_END: code = 4; break;
593       case K_PRIOR: code = 5; break;
594       case K_NEXT: code = 6; break;
595     }
596     if (s->cfg.linux_funkeys && code >= 11 && code <= 15) {
597         p += sprintf((char *)p, "\x1B[[%c", code + 'A' - 11);
598         return p - output;
599     }
600     if (s->cfg.rxvt_homeend && (code == 1 || code == 4)) {
601         p += sprintf((char *)p, code == 1 ? "\x1B[H" : "\x1BOw");
602         return p - output;
603     }
604     if (code) {
605         p += sprintf((char *)p, "\x1B[%d~", code);
606         return p - output;
607     }
608
609     if (s->app_keypad_keys) {
610         switch (event->message & keyCodeMask) {
611           case KP_ENTER: p += sprintf((char *)p, "\x1BOM"); return p - output;
612           case KP_CLEAR: p += sprintf((char *)p, "\x1BOP"); return p - output;
613           case KP_EQUAL: p += sprintf((char *)p, "\x1BOQ"); return p - output;
614           case KP_SLASH: p += sprintf((char *)p, "\x1BOR"); return p - output;
615           case KP_STAR:  p += sprintf((char *)p, "\x1BOS"); return p - output;
616           case KP_PLUS:  p += sprintf((char *)p, "\x1BOl"); return p - output;
617           case KP_MINUS: p += sprintf((char *)p, "\x1BOm"); return p - output;
618           case KP_DOT:   p += sprintf((char *)p, "\x1BOn"); return p - output;
619           case KP_0:     p += sprintf((char *)p, "\x1BOp"); return p - output;
620           case KP_1:     p += sprintf((char *)p, "\x1BOq"); return p - output;
621           case KP_2:     p += sprintf((char *)p, "\x1BOr"); return p - output;
622           case KP_3:     p += sprintf((char *)p, "\x1BOs"); return p - output;
623           case KP_4:     p += sprintf((char *)p, "\x1BOt"); return p - output;
624           case KP_5:     p += sprintf((char *)p, "\x1BOu"); return p - output;
625           case KP_6:     p += sprintf((char *)p, "\x1BOv"); return p - output;
626           case KP_7:     p += sprintf((char *)p, "\x1BOw"); return p - output;
627           case KP_8:     p += sprintf((char *)p, "\x1BOx"); return p - output;
628           case KP_9:     p += sprintf((char *)p, "\x1BOy"); return p - output;
629         }
630     }
631
632     switch (event->message & keyCodeMask) {
633       case K_UP:
634         p += sprintf((char *)p, s->app_cursor_keys ? "\x1BOA" : "\x1B[A");
635         return p - output;
636       case K_DOWN:
637         p += sprintf((char *)p, s->app_cursor_keys ? "\x1BOB" : "\x1B[B");
638         return p - output;
639       case K_RIGHT:
640         p += sprintf((char *)p, s->app_cursor_keys ? "\x1BOC" : "\x1B[C");
641         return p - output;
642       case K_LEFT:
643         p += sprintf((char *)p, s->app_cursor_keys ? "\x1BOD" : "\x1B[D");
644         return p - output;
645       case KP_ENTER:
646         *p++ = 0x0d;
647         return p - output;
648       case K_BS:
649         *p++ = (s->cfg.bksp_is_delete ? 0x7f : 0x08);
650         return p - output;
651       default:
652         *p++ = event->message & charCodeMask;
653         return p - output;
654     }
655 }
656
657 void mac_growterm(WindowPtr window, EventRecord *event) {
658     Rect limits;
659     long grow_result;
660     int newrows, newcols;
661     Session *s;
662
663     s = (Session *)GetWRefCon(window);
664     SetRect(&limits, s->font_width + 15, s->font_height, SHRT_MAX, SHRT_MAX);
665     grow_result = GrowWindow(window, event->where, &limits);
666     if (grow_result != 0) {
667         newrows = HiWord(grow_result) / s->font_height;
668         newcols = (LoWord(grow_result) - 15) / s->font_width;
669         mac_adjustsize(s, newrows, newcols);
670         term_size(s, newrows, newcols, s->cfg.savelines);
671     }
672 }
673
674 void mac_activateterm(WindowPtr window, Boolean active) {
675     Session *s;
676
677     s = (Session *)GetWRefCon(window);
678     s->has_focus = active;
679     term_update(s);
680     if (active)
681         ShowControl(s->scrollbar);
682     else {
683         PmBackColor(DEFAULT_BG); /* HideControl clears behind the control */
684         HideControl(s->scrollbar);
685     }
686     mac_drawgrowicon(s);
687 }
688
689 void mac_updateterm(WindowPtr window) {
690     Session *s;
691
692     s = (Session *)GetWRefCon(window);
693     SetPort(window);
694     BeginUpdate(window);
695     pre_paint(s);
696     term_paint(s,
697                (*window->visRgn)->rgnBBox.left,
698                (*window->visRgn)->rgnBBox.top,
699                (*window->visRgn)->rgnBBox.right,
700                (*window->visRgn)->rgnBBox.bottom);
701     /* Restore default colours in case the Window Manager uses them */
702     PmForeColor(DEFAULT_FG);
703     PmBackColor(DEFAULT_BG);
704     if (FrontWindow() != window)
705         EraseRect(&(*s->scrollbar)->contrlRect);
706     UpdateControls(window, window->visRgn);
707     mac_drawgrowicon(s);
708     post_paint(s);
709     EndUpdate(window);
710 }
711
712 static void mac_drawgrowicon(Session *s) {
713     Rect clip;
714
715     SetPort(s->window);
716     /* Stop DrawGrowIcon giving us space for a horizontal scrollbar */
717     SetRect(&clip, s->window->portRect.right - 15, SHRT_MIN,
718             SHRT_MAX, SHRT_MAX);
719     ClipRect(&clip);
720     DrawGrowIcon(s->window);
721     clip.left = SHRT_MIN;
722     ClipRect(&clip);
723 }    
724
725 struct do_text_args {
726     Session *s;
727     Rect textrect;
728     Rect leadrect;
729     char *text;
730     int len;
731     unsigned long attr;
732 };
733
734 /*
735  * Call from the terminal emulator to draw a bit of text
736  *
737  * x and y are text row and column (zero-based)
738  */
739 void do_text(Session *s, int x, int y, char *text, int len,
740              unsigned long attr) {
741     int style = 0;
742     struct do_text_args a;
743     RgnHandle textrgn;
744
745     SetPort(s->window);
746     
747     /* First check this text is relevant */
748     a.textrect.top = y * s->font_height;
749     a.textrect.bottom = (y + 1) * s->font_height;
750     a.textrect.left = x * s->font_width;
751     a.textrect.right = (x + len) * s->font_width;
752     if (!RectInRgn(&a.textrect, s->window->visRgn))
753         return;
754
755     a.s = s;
756     a.text = text;
757     a.len = len;
758     a.attr = attr;
759     if (s->font_leading > 0)
760         SetRect(&a.leadrect,
761                 a.textrect.left, a.textrect.bottom - s->font_leading,
762                 a.textrect.right, a.textrect.bottom);
763     else
764         SetRect(&a.leadrect, 0, 0, 0, 0);
765     SetPort(s->window);
766     TextFont(s->fontnum);
767     if (s->cfg.fontisbold || (attr & ATTR_BOLD) && !s->cfg.bold_colour)
768         style |= bold;
769     if (attr & ATTR_UNDER)
770         style |= underline;
771     TextFace(style);
772     TextSize(s->cfg.fontheight);
773     SetFractEnable(FALSE); /* We want characters on pixel boundaries */
774     if (mac_gestalts.qdvers > gestaltOriginalQD)
775         if (style & bold) {
776             SpaceExtra(s->font_boldadjust << 16);
777             CharExtra(s->font_boldadjust << 16);
778         } else {
779             SpaceExtra(0);
780             CharExtra(0);
781         }
782     textrgn = NewRgn();
783     RectRgn(textrgn, &a.textrect);
784     if (mac_gestalts.qdvers == gestaltOriginalQD)
785         do_text_for_device(1, 0, NULL, (long)&a);
786     else
787         DeviceLoop(textrgn, &do_text_for_device_upp, (long)&a, 0);
788     DisposeRgn(textrgn);
789     /* Tell the window manager about it in case this isn't an update */
790     ValidRect(&a.textrect);
791 }
792
793 static pascal void do_text_for_device(short depth, short devflags,
794                                       GDHandle device, long cookie) {
795     struct do_text_args *a;
796     int bgcolour, fgcolour, bright;
797
798     a = (struct do_text_args *)cookie;
799
800     bright = (a->attr & ATTR_BOLD) && a->s->cfg.bold_colour;
801
802     TextMode(a->attr & ATTR_REVERSE ? notSrcCopy : srcCopy);
803
804     switch (depth) {
805       case 1:
806         /* XXX This should be done with a _little_ more configurability */
807         ForeColor(whiteColor);
808         BackColor(blackColor);
809         if (a->attr & ATTR_ACTCURS)
810             TextMode(a->attr & ATTR_REVERSE ? srcCopy : notSrcCopy);
811         break;
812       case 2:
813         if (a->attr & ATTR_ACTCURS) {
814             PmForeColor(bright ? CURSOR_FG_BOLD : CURSOR_FG);
815             PmBackColor(CURSOR_BG);
816             TextMode(srcCopy);
817         } else {
818             PmForeColor(bright ? DEFAULT_FG_BOLD : DEFAULT_FG);
819             PmBackColor(DEFAULT_BG);
820         }
821         break;
822       default:
823         if (a->attr & ATTR_ACTCURS) {
824             fgcolour = bright ? CURSOR_FG_BOLD : CURSOR_FG;
825             bgcolour = CURSOR_BG;
826             TextMode(srcCopy);
827         } else {
828             fgcolour = ((a->attr & ATTR_FGMASK) >> ATTR_FGSHIFT) * 2;
829             bgcolour = ((a->attr & ATTR_BGMASK) >> ATTR_BGSHIFT) * 2;
830             if (bright)
831                 if (a->attr & ATTR_REVERSE)
832                     bgcolour++;
833                 else
834                     fgcolour++;
835         }
836         PmForeColor(fgcolour);
837         PmBackColor(bgcolour);
838         break;
839     }
840
841     if (a->attr & ATTR_REVERSE)
842         PaintRect(&a->leadrect);
843     else
844         EraseRect(&a->leadrect);
845     MoveTo(a->textrect.left, a->textrect.top + a->s->font_ascent);
846     DrawText(a->text, 0, a->len);
847
848     if (a->attr & ATTR_PASCURS) {
849         PenNormal();
850         switch (depth) {
851           case 1:
852             PenMode(patXor);
853             break;
854           default:
855             PmForeColor(CURSOR_BG);
856             break;
857         }
858         FrameRect(&a->textrect);
859     }
860 }
861
862 /*
863  * Call from the terminal emulator to get its graphics context.
864  * Should probably be called start_redraw or something.
865  */
866 void pre_paint(Session *s) {
867
868     s->attr_mask = ATTR_INVALID;
869     DeviceLoop(s->window->visRgn, &mac_set_attr_mask_upp, (long)s, 0);
870 }
871
872 static pascal void mac_set_attr_mask(short depth, short devflags,
873                                      GDHandle device, long cookie) {
874
875     Session *s = (Session *)cookie;
876
877     switch (depth) {
878       default:
879         s->attr_mask |= ATTR_FGMASK | ATTR_BGMASK;
880         /* FALLTHROUGH */
881       case 2:
882         s->attr_mask |= ATTR_BOLD;
883         /* FALLTHROUGH */
884       case 1:
885         s->attr_mask |= ATTR_UNDER | ATTR_REVERSE | ATTR_ACTCURS |
886             ATTR_PASCURS | ATTR_ASCII | ATTR_GBCHR | ATTR_LINEDRW |
887             (s->cfg.bold_colour ? 0 : ATTR_BOLD); 
888         break;
889     }
890 }
891
892 /*
893  * Presumably this does something in Windows
894  */
895 void post_paint(Session *s) {
896
897 }
898
899 /*
900  * Set the scroll bar position
901  *
902  * total is the line number of the bottom of the working screen
903  * start is the line number of the top of the display
904  * page is the length of the displayed page
905  */
906 void set_sbar(Session *s, int total, int start, int page) {
907
908     /* We don't redraw until we've set everything up, to avoid glitches */
909     (*s->scrollbar)->contrlMin = 0;
910     (*s->scrollbar)->contrlMax = total - page;
911     SetControlValue(s->scrollbar, start);
912 #if TARGET_RT_CFM
913     /* XXX: This doesn't link for me. */
914     if (mac_gestalts.cntlattr & gestaltControlMgrPresent)
915         SetControlViewSize(s->scrollbar, page);
916 #endif
917 }
918
919 /*
920  * Beep
921  */
922 void beep(Session *s) {
923
924     SysBeep(30);
925     /*
926      * XXX We should indicate the relevant window and/or use the
927      * Notification Manager
928      */
929 }
930
931 /*
932  * Set icon string -- a no-op here (Windowshade?)
933  */
934 void set_icon(Session *s, char *icon) {
935
936 }
937
938 /*
939  * Set the window title
940  */
941 void set_title(Session *s, char *title) {
942     Str255 mactitle;
943
944     mactitle[0] = sprintf((char *)&mactitle[1], "%s", title);
945     SetWTitle(s->window, mactitle);
946 }
947
948 /*
949  * Resize the window at the emulator's request
950  */
951 void request_resize(Session *s, int w, int h) {
952
953     s->cols = w;
954     s->rows = h;
955     mac_initfont(s);
956 }
957
958 /*
959  * Set the logical palette
960  */
961 void palette_set(Session *s, int n, int r, int g, int b) {
962     RGBColor col;
963     static const int first[21] = {
964         0, 2, 4, 6, 8, 10, 12, 14,
965         1, 3, 5, 7, 9, 11, 13, 15,
966         16, 17, 18, 20, 22
967     };
968     
969     if (mac_gestalts.qdvers == gestaltOriginalQD)
970       return;
971     col.red   = r * 0x0101;
972     col.green = g * 0x0101;
973     col.blue  = b * 0x0101;
974     SetEntryColor(s->palette, first[n], &col);
975     if (first[n] >= 18)
976         SetEntryColor(s->palette, first[n]+1, &col);
977     if (first[n] == DEFAULT_BG)
978         mac_adjustwinbg(s);
979     ActivatePalette(s->window);
980 }
981
982 /*
983  * Reset to the default palette
984  */
985 void palette_reset(Session *s) {
986
987     if (mac_gestalts.qdvers == gestaltOriginalQD)
988         return;
989     CopyPalette(s->cfg.colours, s->palette, 0, 0,
990                 (*s->cfg.colours)->pmEntries);
991     mac_adjustwinbg(s);
992     ActivatePalette(s->window);
993     /* Palette Manager will generate update events as required. */
994 }
995
996 /*
997  * Scroll the screen. (`lines' is +ve for scrolling forward, -ve
998  * for backward.)
999  */
1000 void do_scroll(Session *s, int topline, int botline, int lines) {
1001     Rect r;
1002     RgnHandle update;
1003
1004     SetPort(s->window);
1005     PmBackColor(DEFAULT_BG);
1006     update = NewRgn();
1007     SetRect(&r, 0, topline * s->font_height,
1008             s->cols * s->font_width, (botline + 1) * s->font_height);
1009     ScrollRect(&r, 0, - lines * s->font_height, update);
1010     /* XXX: move update region? */
1011     InvalRgn(update);
1012     DisposeRgn(update);
1013 }
1014
1015 void lognegot(/*Session *s,*/ const char *str) {
1016
1017     /* XXX Do something */
1018 }
1019
1020 /*
1021  * Emacs magic:
1022  * Local Variables:
1023  * c-file-style: "simon"
1024  * End:
1025  */
1026