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