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