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