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