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