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