]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - mac/macterm.c
2e1a406b5bbfb2ec66b697e740af610d0ab33b48
[PuTTY.git] / mac / macterm.c
1 /* $Id: macterm.c,v 1.30 2003/01/01 19:51:13 ben Exp $ */
2 /*
3  * Copyright (c) 1999 Simon Tatham
4  * Copyright (c) 1999, 2002 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 <ControlDefinitions.h>
36 #include <Fonts.h>
37 #include <Gestalt.h>
38 #include <LowMem.h>
39 #include <MacMemory.h>
40 #include <MacWindows.h>
41 #include <MixedMode.h>
42 #include <Palettes.h>
43 #include <Quickdraw.h>
44 #include <QuickdrawText.h>
45 #include <Resources.h>
46 #include <Scrap.h>
47 #include <Script.h>
48 #include <Sound.h>
49 #include <StandardFile.h>
50 #include <TextCommon.h>
51 #include <Threads.h>
52 #include <ToolUtils.h>
53 #include <UnicodeConverter.h>
54
55 #include <assert.h>
56 #include <limits.h>
57 #include <stdlib.h>
58 #include <stdio.h>
59 #include <string.h>
60
61 #include "macresid.h"
62 #include "putty.h"
63 #include "charset.h"
64 #include "mac.h"
65 #include "storage.h"
66 #include "terminal.h"
67
68 #define NCOLOURS (lenof(((Config *)0)->colours))
69
70 #define DEFAULT_FG      16
71 #define DEFAULT_FG_BOLD 17
72 #define DEFAULT_BG      18
73 #define DEFAULT_BG_BOLD 19
74 #define CURSOR_FG       20
75 #define CURSOR_BG       21
76
77 #define PTOCC(x) ((x) < 0 ? -(-(x - s->font_width - 1) / s->font_width) : \
78                             (x) / s->font_width)
79 #define PTOCR(y) ((y) < 0 ? -(-(y - s->font_height - 1) / s->font_height) : \
80                             (y) / s->font_height)
81
82 static void mac_initfont(Session *);
83 static pascal OSStatus uni_to_font_fallback(UniChar *, ByteCount, ByteCount *,
84                                             TextPtr, ByteCount, ByteCount *,
85                                             LogicalAddress *,
86                                             ConstUnicodeMappingPtr);
87 static void mac_initpalette(Session *);
88 static void mac_adjustwinbg(Session *);
89 static void mac_adjustsize(Session *, int, int);
90 static void mac_drawgrowicon(Session *s);
91 static pascal void mac_growtermdraghook(void);
92 static pascal void mac_scrolltracker(ControlHandle, short);
93 static pascal void do_text_for_device(short, short, GDHandle, long);
94 static int mac_keytrans(Session *, EventRecord *, unsigned char *);
95 static void text_click(Session *, EventRecord *);
96
97 void pre_paint(Session *s);
98 void post_paint(Session *s);
99
100 #if TARGET_RT_MAC_CFM
101 static RoutineDescriptor mac_scrolltracker_upp =
102     BUILD_ROUTINE_DESCRIPTOR(uppControlActionProcInfo,
103                              (ProcPtr)mac_scrolltracker);
104 static RoutineDescriptor do_text_for_device_upp =
105     BUILD_ROUTINE_DESCRIPTOR(uppDeviceLoopDrawingProcInfo,
106                              (ProcPtr)do_text_for_device);
107 #else /* not TARGET_RT_MAC_CFM */
108 #define mac_scrolltracker_upp   mac_scrolltracker
109 #define do_text_for_device_upp  do_text_for_device
110 #endif /* not TARGET_RT_MAC_CFM */
111
112 static void inbuf_putc(Session *s, int c) {
113     char ch = c;
114
115     from_backend(s->term, 0, &ch, 1);
116 }
117
118 static void inbuf_putstr(Session *s, const char *c) {
119
120     from_backend(s->term, 0, (char *)c, strlen(c));
121 }
122
123 static void display_resource(Session *s, unsigned long type, short id) {
124     Handle h;
125     int len;
126     char *t;
127
128     h = GetResource(type, id);
129     if (h == NULL)
130         fatalbox("Can't get test resource");
131     len = GetResourceSizeOnDisk(h);
132     DetachResource(h);
133     HNoPurge(h);
134     HLock(h);
135     t = *h;
136     from_backend(s->term, 0, t, len);
137     term_out(s->term);
138     DisposeHandle(h);
139 }
140         
141 void mac_opensession(void) {
142     Session *s;
143     StandardFileReply sfr;
144     static const OSType sftypes[] = { 'Sess', 0, 0, 0 };
145     void *sesshandle;
146
147     s = smalloc(sizeof(*s));
148     memset(s, 0, sizeof(*s));
149
150     StandardGetFile(NULL, 1, sftypes, &sfr);
151     if (!sfr.sfGood) goto fail;
152
153     sesshandle = open_settings_r_fsp(&sfr.sfFile);
154     if (sesshandle == NULL) goto fail;
155     load_open_settings(sesshandle, TRUE, &s->cfg);
156     close_settings_r(sesshandle);
157     s->back = &loop_backend;
158     mac_startsession(s);
159     return;
160
161   fail:
162     sfree(s);
163     return;
164 }
165
166 void mac_startsession(Session *s)
167 {
168     UInt32 starttime;
169     char msg[128];
170
171     /* XXX: Own storage management? */
172     if (HAVE_COLOR_QD())
173         s->window = GetNewCWindow(wTerminal, NULL, (WindowPtr)-1);
174     else
175         s->window = GetNewWindow(wTerminal, NULL, (WindowPtr)-1);
176     SetWRefCon(s->window, (long)s);
177     s->scrollbar = GetNewControl(cVScroll, s->window);
178     s->term = term_init(&s->cfg, s);
179
180     s->logctx = log_init(s);
181     term_provide_logctx(s->term, s->logctx);
182
183     s->back->init(s->term, &s->backhandle, "localhost", 23, &s->realhost, 0);
184     s->back->provide_logctx(s->backhandle, s->logctx);
185
186     term_provide_resize_fn(s->term, s->back->size, s->backhandle);
187
188     mac_adjustsize(s, s->cfg.height, s->cfg.width);
189     term_size(s->term, s->cfg.height, s->cfg.width, s->cfg.savelines);
190
191     s->ldisc = ldisc_create(&s->cfg, s->term, s->back, s->backhandle, s);
192     ldisc_send(s->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
193
194     mac_initfont(s);
195     mac_initpalette(s);
196     if (HAVE_COLOR_QD()) {
197         /* Set to FALSE to not get palette updates in the background. */
198         SetPalette(s->window, s->palette, TRUE); 
199         ActivatePalette(s->window);
200     }
201     ShowWindow(s->window);
202     starttime = TickCount();
203     display_resource(s, 'pTST', 128);
204     sprintf(msg, "Elapsed ticks: %d\015\012", TickCount() - starttime);
205     inbuf_putstr(s, msg);
206     term_out(s->term);
207 }
208
209 static UnicodeToTextFallbackUPP uni_to_font_fallback_upp;
210
211 static void mac_initfont(Session *s) {
212     Str255 macfont;
213     FontInfo fi;
214     TextEncoding enc;
215
216     SetPort(s->window);
217     macfont[0] = sprintf((char *)&macfont[1], "%s", s->cfg.font);
218     GetFNum(macfont, &s->fontnum);
219     TextFont(s->fontnum);
220     TextFace(s->cfg.fontisbold ? bold : 0);
221     TextSize(s->cfg.fontheight);
222     GetFontInfo(&fi);
223     s->font_width = CharWidth('W'); /* Well, it's what NCSA uses. */
224     s->font_ascent = fi.ascent;
225     s->font_leading = fi.leading;
226     s->font_height = s->font_ascent + fi.descent + s->font_leading;
227     if (!s->cfg.bold_colour) {
228         TextFace(bold);
229         s->font_boldadjust = s->font_width - CharWidth('W');
230     } else
231         s->font_boldadjust = 0;
232
233     if (s->uni_to_font != NULL)
234         DisposeUnicodeToTextInfo(&s->uni_to_font);
235     if (mac_gestalts.encvvers != 0 &&
236         UpgradeScriptInfoToTextEncoding(kTextScriptDontCare,
237                                         kTextLanguageDontCare,
238                                         kTextRegionDontCare, macfont,
239                                         &enc) == noErr &&
240         CreateUnicodeToTextInfoByEncoding(enc, &s->uni_to_font) == noErr) {
241         if (uni_to_font_fallback_upp == NULL)
242             uni_to_font_fallback_upp =
243                 NewUnicodeToTextFallbackProc(&uni_to_font_fallback);
244         if (SetFallbackUnicodeToText(s->uni_to_font,
245             uni_to_font_fallback_upp, 
246             kUnicodeFallbackCustomOnly | kUnicodeFallbackInterruptSafeMask,
247             NULL) != noErr) {
248             DisposeUnicodeToTextInfo(&s->uni_to_font);
249             s->uni_to_font = NULL;
250         }
251     } else {
252         s->uni_to_font = NULL;
253         s->font_charset =
254             charset_from_macenc(FontToScript(s->fontnum),
255                                 GetScriptManagerVariable(smRegionCode),
256                                 mac_gestalts.sysvers, s->cfg.font);
257     }
258
259     mac_adjustsize(s, s->term->rows, s->term->cols);
260 }
261
262 static pascal OSStatus uni_to_font_fallback(UniChar *ucp,
263     ByteCount ilen, ByteCount *iusedp, TextPtr obuf, ByteCount olen,
264     ByteCount *ousedp, LogicalAddress *cookie, ConstUnicodeMappingPtr mapping)
265 {
266
267     if (olen < 1)
268         return kTECOutputBufferFullStatus;
269     /*
270      * What I'd _like_ to do here is to somehow generate the
271      * missing-character glyph that every font is required to have.
272      * Unfortunately (and somewhat surprisingly), I can't find any way
273      * to actually ask for it explicitly.  Bah.
274      */
275     *obuf = '.';
276     *iusedp = ilen;
277     *ousedp = 1;
278     return noErr;
279 }
280
281
282 /*
283  * To be called whenever the window size changes.
284  * rows and cols should be desired values.
285  * It's assumed the terminal emulator will be informed, and will set rows
286  * and cols for us.
287  */
288 static void mac_adjustsize(Session *s, int newrows, int newcols) {
289     int winwidth, winheight;
290
291     winwidth = newcols * s->font_width + 15;
292     winheight = newrows * s->font_height;
293     SizeWindow(s->window, winwidth, winheight, true);
294     HideControl(s->scrollbar);
295     MoveControl(s->scrollbar, winwidth - 15, -1);
296     SizeControl(s->scrollbar, 16, winheight - 13);
297     ShowControl(s->scrollbar);
298     mac_drawgrowicon(s);
299 }
300
301 static void mac_initpalette(Session *s) {
302
303     if (!HAVE_COLOR_QD())
304         return;
305     /*
306      * Most colours should be inhibited on 2bpp displays.
307      * Palette manager documentation suggests inhibiting all tolerant colours
308      * on greyscale displays.
309      */
310 #define PM_NORMAL       ( pmTolerant | pmInhibitC2 |                    \
311                           pmInhibitG2 | pmInhibitG4 | pmInhibitG8 )
312 #define PM_TOLERANCE    0x2000
313     s->palette = NewPalette(22, NULL, PM_NORMAL, PM_TOLERANCE);
314     if (s->palette == NULL)
315         fatalbox("Unable to create palette");
316     /* In 2bpp, these are the colours we want most. */
317     SetEntryUsage(s->palette, DEFAULT_BG,
318                   PM_NORMAL &~ pmInhibitC2, PM_TOLERANCE);
319     SetEntryUsage(s->palette, DEFAULT_FG,
320                   PM_NORMAL &~ pmInhibitC2, PM_TOLERANCE);
321     SetEntryUsage(s->palette, DEFAULT_FG_BOLD,
322                   PM_NORMAL &~ pmInhibitC2, PM_TOLERANCE);
323     SetEntryUsage(s->palette, CURSOR_BG,
324                   PM_NORMAL &~ pmInhibitC2, PM_TOLERANCE);
325     palette_reset(s);
326 }
327
328 /*
329  * Set the background colour of the window correctly.  Should be
330  * called whenever the default background changes.
331  */
332 static void mac_adjustwinbg(Session *s) {
333
334     if (!HAVE_COLOR_QD())
335         return;
336 #if TARGET_RT_CFM /* XXX doesn't link (at least for 68k) */
337     if (mac_gestalts.windattr & gestaltWindowMgrPresent)
338         SetWindowContentColor(s->window,
339                               &(*s->palette)->pmInfo[DEFAULT_BG].ciRGB);
340     else
341 #endif
342     {
343         if (s->wctab == NULL)
344             s->wctab = (WCTabHandle)NewHandle(sizeof(**s->wctab));
345         if (s->wctab == NULL)
346             return; /* do without */
347         (*s->wctab)->wCSeed = 0;
348         (*s->wctab)->wCReserved = 0;
349         (*s->wctab)->ctSize = 0;
350         (*s->wctab)->ctTable[0].value = wContentColor;
351         (*s->wctab)->ctTable[0].rgb = (*s->palette)->pmInfo[DEFAULT_BG].ciRGB;
352         SetWinColor(s->window, s->wctab);
353     }
354 }
355
356 /*
357  * Set the cursor shape correctly
358  */
359 void mac_adjusttermcursor(WindowPtr window, Point mouse, RgnHandle cursrgn) {
360     Session *s;
361     ControlHandle control;
362     short part;
363     int x, y;
364
365     SetPort(window);
366     s = (Session *)GetWRefCon(window);
367     GlobalToLocal(&mouse);
368     part = FindControl(mouse, window, &control);
369     if (control == s->scrollbar) {
370         SetCursor(&qd.arrow);
371         RectRgn(cursrgn, &(*s->scrollbar)->contrlRect);
372         SectRgn(cursrgn, window->visRgn, cursrgn);
373     } else {
374         x = mouse.h / s->font_width;
375         y = mouse.v / s->font_height;
376         if (s->raw_mouse)
377             SetCursor(&qd.arrow);
378         else
379             SetCursor(*GetCursor(iBeamCursor));
380         /* Ask for shape changes if we leave this character cell. */
381         SetRectRgn(cursrgn, x * s->font_width, y * s->font_height,
382                    (x + 1) * s->font_width, (y + 1) * s->font_height);
383         SectRgn(cursrgn, window->visRgn, cursrgn);
384     }
385 }
386
387 /*
388  * Enable/disable menu items based on the active terminal window.
389  */
390 void mac_adjusttermmenus(WindowPtr window) {
391     Session *s;
392     MenuHandle menu;
393     long offset;
394
395     s = (Session *)GetWRefCon(window);
396     menu = GetMenuHandle(mEdit);
397     EnableItem(menu, 0);
398     DisableItem(menu, iUndo);
399     DisableItem(menu, iCut);
400     if (1/*s->term->selstate == SELECTED*/)
401         EnableItem(menu, iCopy);
402     else
403         DisableItem(menu, iCopy);
404     if (GetScrap(NULL, 'TEXT', &offset) == noTypeErr)
405         DisableItem(menu, iPaste);
406     else
407         EnableItem(menu, iPaste);
408     DisableItem(menu, iClear);
409     EnableItem(menu, iSelectAll);
410 }
411
412 void mac_menuterm(WindowPtr window, short menu, short item) {
413     Session *s;
414
415     s = (Session *)GetWRefCon(window);
416     switch (menu) {
417       case mEdit:
418         switch (item) {
419           case iCopy:
420             /* term_copy(s); */
421             break;
422           case iPaste:
423             term_do_paste(s->term);
424             break;
425         }
426     }
427 }
428             
429 void mac_clickterm(WindowPtr window, EventRecord *event) {
430     Session *s;
431     Point mouse;
432     ControlHandle control;
433     int part;
434
435     s = (Session *)GetWRefCon(window);
436     SetPort(window);
437     mouse = event->where;
438     GlobalToLocal(&mouse);
439     part = FindControl(mouse, window, &control);
440     if (control == s->scrollbar) {
441         switch (part) {
442           case kControlIndicatorPart:
443             if (TrackControl(control, mouse, NULL) == kControlIndicatorPart)
444                 term_scroll(s->term, +1, GetControlValue(control));
445             break;
446           case kControlUpButtonPart:
447           case kControlDownButtonPart:
448           case kControlPageUpPart:
449           case kControlPageDownPart:
450             TrackControl(control, mouse, &mac_scrolltracker_upp);
451             break;
452         }
453     } else {
454         text_click(s, event);
455     }
456 }
457
458 static void text_click(Session *s, EventRecord *event) {
459     Point localwhere;
460     int row, col;
461     static UInt32 lastwhen = 0;
462     static Session *lastsess = NULL;
463     static int lastrow = -1, lastcol = -1;
464     static Mouse_Action lastact = MA_NOTHING;
465
466     SetPort(s->window);
467     localwhere = event->where;
468     GlobalToLocal(&localwhere);
469
470     col = PTOCC(localwhere.h);
471     row = PTOCR(localwhere.v);
472     if (event->when - lastwhen < GetDblTime() &&
473         row == lastrow && col == lastcol && s == lastsess)
474         lastact = (lastact == MA_CLICK ? MA_2CLK :
475                    lastact == MA_2CLK ? MA_3CLK :
476                    lastact == MA_3CLK ? MA_CLICK : MA_NOTHING);
477     else
478         lastact = MA_CLICK;
479     /* Fake right button with shift key */
480     term_mouse(s->term, event->modifiers & shiftKey ? MBT_RIGHT : MBT_LEFT,
481                lastact, col, row, event->modifiers & shiftKey,
482                event->modifiers & controlKey, event->modifiers & optionKey);
483     lastsess = s;
484     lastrow = row;
485     lastcol = col;
486     while (StillDown()) {
487         GetMouse(&localwhere);
488         col = PTOCC(localwhere.h);
489         row = PTOCR(localwhere.v);
490         term_mouse(s->term,
491                    event->modifiers & shiftKey ? MBT_RIGHT : MBT_LEFT,
492                    MA_DRAG, col, row, event->modifiers & shiftKey,
493                    event->modifiers & controlKey,
494                    event->modifiers & optionKey);
495         if (row > s->term->rows - 1)
496             term_scroll(s->term, 0, row - (s->term->rows - 1));
497         else if (row < 0)
498             term_scroll(s->term, 0, row);
499     }
500     term_mouse(s->term, event->modifiers & shiftKey ? MBT_RIGHT : MBT_LEFT,
501                MA_RELEASE, col, row, event->modifiers & shiftKey,
502                event->modifiers & controlKey, event->modifiers & optionKey);
503     lastwhen = TickCount();
504 }
505
506 Mouse_Button translate_button(void *frontend, Mouse_Button button)
507 {
508
509     switch (button) {
510       case MBT_LEFT:
511         return MBT_SELECT;
512       case MBT_RIGHT:
513         return MBT_EXTEND;
514       default:
515         return 0;
516     }
517 }
518
519 void write_clip(void *cookie, wchar_t *data, int len, int must_deselect) {
520     
521     /*
522      * See "Programming with the Text Encoding Conversion Manager"
523      * Appendix E for Unicode scrap conventions.
524      *
525      * XXX Need to support TEXT/styl scrap as well.
526      * See STScrpRec in TextEdit (Inside Macintosh: Text) for styl details.
527      * XXX Maybe PICT scrap too.
528      */
529     if (ZeroScrap() != noErr)
530         return;
531     PutScrap(len * sizeof(*data), 'utxt', data);
532 }
533
534 void get_clip(void *frontend, wchar_t **p, int *lenp) {
535     Session *s = frontend;
536     static Handle h = NULL;
537     long offset;
538
539     if (p == NULL) {
540         /* release memory */
541         if (h != NULL)
542             DisposeHandle(h);
543         h = NULL;
544     } else
545         /* XXX Support TEXT-format scrap as well. */
546         if (GetScrap(NULL, 'utxt', &offset) > 0) {
547             h = NewHandle(0);
548             *lenp = GetScrap(h, 'utxt', &offset) / sizeof(**p);
549             HLock(h);
550             *p = (wchar_t *)*h;
551             if (*p == NULL || *lenp <= 0)
552                 fatalbox("Empty scrap");
553         } else {
554             *p = NULL;
555             *lenp = 0;
556         }
557 }
558
559 static pascal void mac_scrolltracker(ControlHandle control, short part) {
560     Session *s;
561
562     s = (Session *)GetWRefCon((*control)->contrlOwner);
563     switch (part) {
564       case kControlUpButtonPart:
565         term_scroll(s->term, 0, -1);
566         break;
567       case kControlDownButtonPart:
568         term_scroll(s->term, 0, +1);
569         break;
570       case kControlPageUpPart:
571         term_scroll(s->term, 0, -(s->term->rows - 1));
572         break;
573       case kControlPageDownPart:
574         term_scroll(s->term, 0, +(s->term->rows - 1));
575         break;
576     }
577 }
578
579 #define K_BS    0x3300
580 #define K_F1    0x7a00
581 #define K_F2    0x7800
582 #define K_F3    0x6300
583 #define K_F4    0x7600
584 #define K_F5    0x6000
585 #define K_F6    0x6100
586 #define K_F7    0x6200
587 #define K_F8    0x6400
588 #define K_F9    0x6500
589 #define K_F10   0x6d00
590 #define K_F11   0x6700
591 #define K_F12   0x6f00
592 #define K_F13   0x6900
593 #define K_F14   0x6b00
594 #define K_F15   0x7100
595 #define K_INSERT 0x7200
596 #define K_HOME  0x7300
597 #define K_PRIOR 0x7400
598 #define K_DELETE 0x7500
599 #define K_END   0x7700
600 #define K_NEXT  0x7900
601 #define K_LEFT  0x7b00
602 #define K_RIGHT 0x7c00
603 #define K_DOWN  0x7d00
604 #define K_UP    0x7e00
605 #define KP_0    0x5200
606 #define KP_1    0x5300
607 #define KP_2    0x5400
608 #define KP_3    0x5500
609 #define KP_4    0x5600
610 #define KP_5    0x5700
611 #define KP_6    0x5800
612 #define KP_7    0x5900
613 #define KP_8    0x5b00
614 #define KP_9    0x5c00
615 #define KP_CLEAR 0x4700
616 #define KP_EQUAL 0x5100
617 #define KP_SLASH 0x4b00
618 #define KP_STAR 0x4300
619 #define KP_PLUS 0x4500
620 #define KP_MINUS 0x4e00
621 #define KP_DOT  0x4100
622 #define KP_ENTER 0x4c00
623
624 void mac_keyterm(WindowPtr window, EventRecord *event) {
625     unsigned char buf[20];
626     int len;
627     Session *s;
628
629     s = (Session *)GetWRefCon(window);
630     len = mac_keytrans(s, event, buf);
631     ldisc_send(s->ldisc, (char *)buf, len, 1);
632     ObscureCursor();
633     term_seen_key_event(s->term);
634     term_out(s->term);
635     term_update(s->term);
636 }
637
638 static int mac_keytrans(Session *s, EventRecord *event,
639                         unsigned char *output) {
640     unsigned char *p = output;
641     int code;
642
643     /* No meta key yet -- that'll be rather fun. */
644
645     /* Keys that we handle locally */
646     if (event->modifiers & shiftKey) {
647         switch (event->message & keyCodeMask) {
648           case K_PRIOR: /* shift-pageup */
649             term_scroll(s->term, 0, -(s->term->rows - 1));
650             return 0;
651           case K_NEXT:  /* shift-pagedown */
652             term_scroll(s->term, 0, +(s->term->rows - 1));
653             return 0;
654         }
655     }
656
657     /*
658      * Control-2 should return ^@ (0x00), Control-6 should return
659      * ^^ (0x1E), and Control-Minus should return ^_ (0x1F). Since
660      * the DOS keyboard handling did it, and we have nothing better
661      * to do with the key combo in question, we'll also map
662      * Control-Backquote to ^\ (0x1C).
663      */
664
665     if (event->modifiers & controlKey) {
666         switch (event->message & charCodeMask) {
667           case ' ': case '2':
668             *p++ = 0x00;
669             return p - output;
670           case '`':
671             *p++ = 0x1c;
672             return p - output;
673           case '6':
674             *p++ = 0x1e;
675             return p - output;
676           case '/':
677             *p++ = 0x1f;
678             return p - output;
679         }
680     }
681
682     /*
683      * First, all the keys that do tilde codes. (ESC '[' nn '~',
684      * for integer decimal nn.)
685      *
686      * We also deal with the weird ones here. Linux VCs replace F1
687      * to F5 by ESC [ [ A to ESC [ [ E. rxvt doesn't do _that_, but
688      * does replace Home and End (1~ and 4~) by ESC [ H and ESC O w
689      * respectively.
690      */
691     code = 0;
692     switch (event->message & keyCodeMask) {
693       case K_F1: code = (event->modifiers & shiftKey ? 23 : 11); break;
694       case K_F2: code = (event->modifiers & shiftKey ? 24 : 12); break;
695       case K_F3: code = (event->modifiers & shiftKey ? 25 : 13); break;
696       case K_F4: code = (event->modifiers & shiftKey ? 26 : 14); break;
697       case K_F5: code = (event->modifiers & shiftKey ? 28 : 15); break;
698       case K_F6: code = (event->modifiers & shiftKey ? 29 : 17); break;
699       case K_F7: code = (event->modifiers & shiftKey ? 31 : 18); break;
700       case K_F8: code = (event->modifiers & shiftKey ? 32 : 19); break;
701       case K_F9: code = (event->modifiers & shiftKey ? 33 : 20); break;
702       case K_F10: code = (event->modifiers & shiftKey ? 34 : 21); break;
703       case K_F11: code = 23; break;
704       case K_F12: code = 24; break;
705       case K_HOME: code = 1; break;
706       case K_INSERT: code = 2; break;
707       case K_DELETE: code = 3; break;
708       case K_END: code = 4; break;
709       case K_PRIOR: code = 5; break;
710       case K_NEXT: code = 6; break;
711     }
712     if (s->cfg.funky_type == 1 && code >= 11 && code <= 15) {
713         p += sprintf((char *)p, "\x1B[[%c", code + 'A' - 11);
714         return p - output;
715     }
716     if (s->cfg.rxvt_homeend && (code == 1 || code == 4)) {
717         p += sprintf((char *)p, code == 1 ? "\x1B[H" : "\x1BOw");
718         return p - output;
719     }
720     if (code) {
721         p += sprintf((char *)p, "\x1B[%d~", code);
722         return p - output;
723     }
724
725     if (s->term->app_keypad_keys) {
726         switch (event->message & keyCodeMask) {
727           case KP_ENTER: p += sprintf((char *)p, "\x1BOM"); return p - output;
728           case KP_CLEAR: p += sprintf((char *)p, "\x1BOP"); return p - output;
729           case KP_EQUAL: p += sprintf((char *)p, "\x1BOQ"); return p - output;
730           case KP_SLASH: p += sprintf((char *)p, "\x1BOR"); return p - output;
731           case KP_STAR:  p += sprintf((char *)p, "\x1BOS"); return p - output;
732           case KP_PLUS:  p += sprintf((char *)p, "\x1BOl"); return p - output;
733           case KP_MINUS: p += sprintf((char *)p, "\x1BOm"); return p - output;
734           case KP_DOT:   p += sprintf((char *)p, "\x1BOn"); return p - output;
735           case KP_0:     p += sprintf((char *)p, "\x1BOp"); return p - output;
736           case KP_1:     p += sprintf((char *)p, "\x1BOq"); return p - output;
737           case KP_2:     p += sprintf((char *)p, "\x1BOr"); return p - output;
738           case KP_3:     p += sprintf((char *)p, "\x1BOs"); return p - output;
739           case KP_4:     p += sprintf((char *)p, "\x1BOt"); return p - output;
740           case KP_5:     p += sprintf((char *)p, "\x1BOu"); return p - output;
741           case KP_6:     p += sprintf((char *)p, "\x1BOv"); return p - output;
742           case KP_7:     p += sprintf((char *)p, "\x1BOw"); return p - output;
743           case KP_8:     p += sprintf((char *)p, "\x1BOx"); return p - output;
744           case KP_9:     p += sprintf((char *)p, "\x1BOy"); return p - output;
745         }
746     }
747
748     switch (event->message & keyCodeMask) {
749       case K_UP:
750         p += sprintf((char *)p,
751                      s->term->app_cursor_keys ? "\x1BOA" : "\x1B[A");
752         return p - output;
753       case K_DOWN:
754         p += sprintf((char *)p,
755                      s->term->app_cursor_keys ? "\x1BOB" : "\x1B[B");
756         return p - output;
757       case K_RIGHT:
758         p += sprintf((char *)p,
759                      s->term->app_cursor_keys ? "\x1BOC" : "\x1B[C");
760         return p - output;
761       case K_LEFT:
762         p += sprintf((char *)p,
763                      s->term->app_cursor_keys ? "\x1BOD" : "\x1B[D");
764         return p - output;
765       case KP_ENTER:
766         *p++ = 0x0d;
767         return p - output;
768       case K_BS:
769         *p++ = (s->cfg.bksp_is_delete ? 0x7f : 0x08);
770         return p - output;
771       default:
772         *p++ = event->message & charCodeMask;
773         return p - output;
774     }
775 }
776
777 void request_paste(void *frontend)
778 {
779     Session *s = frontend;
780
781     /*
782      * In the Mac OS, pasting is synchronous: we can read the
783      * clipboard with no difficulty, so request_paste() can just go
784      * ahead and paste.
785      */
786     term_do_paste(s->term);
787 }
788
789 static struct {
790     Rect msgrect;
791     Point msgorigin;
792     Point startmouse;
793     Session *s;
794     char oldmsg[20];
795 } growterm_state;
796
797 void mac_growterm(WindowPtr window, EventRecord *event) {
798     Rect limits;
799     long grow_result;
800     int newrows, newcols;
801     Session *s;
802     DragGrayRgnUPP draghooksave;
803     GrafPtr portsave;
804     FontInfo fi;
805
806     s = (Session *)GetWRefCon(window);
807
808     draghooksave = LMGetDragHook();
809     growterm_state.oldmsg[0] = '\0';
810     growterm_state.startmouse = event->where;
811     growterm_state.s = s;
812     GetPort(&portsave);
813     SetPort(s->window);
814     BackColor(whiteColor);
815     ForeColor(blackColor);
816     TextFont(systemFont);
817     TextFace(0);
818     TextSize(12);
819     GetFontInfo(&fi);
820     SetRect(&growterm_state.msgrect, 0, 0,
821             StringWidth("\p99999x99999") + 4, fi.ascent + fi.descent + 4);
822     SetPt(&growterm_state.msgorigin, 2, fi.ascent + 2);
823     LMSetDragHook(NewDragGrayRgnUPP(mac_growtermdraghook));
824
825     SetRect(&limits, s->font_width + 15, s->font_height, SHRT_MAX, SHRT_MAX);
826     grow_result = GrowWindow(window, event->where, &limits);
827
828     DisposeDragGrayRgnUPP(LMGetDragHook());
829     LMSetDragHook(draghooksave);
830     InvalRect(&growterm_state.msgrect);
831
832     SetPort(portsave);
833
834     if (grow_result != 0) {
835         newrows = HiWord(grow_result) / s->font_height;
836         newcols = (LoWord(grow_result) - 15) / s->font_width;
837         mac_adjustsize(s, newrows, newcols);
838         term_size(s->term, newrows, newcols, s->cfg.savelines);
839     }
840 }
841
842 static pascal void mac_growtermdraghook(void)
843 {
844     Session *s = growterm_state.s;
845     GrafPtr portsave;
846     Point mouse;
847     char buf[20];
848     int newrows, newcols;
849     
850     GetMouse(&mouse);
851     newrows = (mouse.v - growterm_state.startmouse.v) / s->font_height +
852         s->term->rows;
853     if (newrows < 1) newrows = 1;
854     newcols = (mouse.h - growterm_state.startmouse.h) / s->font_width +
855         s->term->cols;
856     if (newcols < 1) newcols = 1;
857     sprintf(buf, "%dx%d", newcols, newrows);
858     if (strcmp(buf, growterm_state.oldmsg) == 0)
859         return;
860     strcpy(growterm_state.oldmsg, buf);
861     c2pstr(buf);
862
863     GetPort(&portsave);
864     SetPort(growterm_state.s->window);
865     EraseRect(&growterm_state.msgrect);
866     MoveTo(growterm_state.msgorigin.h, growterm_state.msgorigin.v);
867     DrawString((StringPtr)buf);
868     SetPort(portsave);
869 }
870
871 void mac_activateterm(WindowPtr window, Boolean active) {
872     Session *s;
873
874     s = (Session *)GetWRefCon(window);
875     s->term->has_focus = active;
876     term_update(s->term);
877     if (active)
878         ShowControl(s->scrollbar);
879     else {
880         if (HAVE_COLOR_QD())
881             PmBackColor(DEFAULT_BG);/* HideControl clears behind the control */
882         else
883             BackColor(blackColor);
884         HideControl(s->scrollbar);
885     }
886     mac_drawgrowicon(s);
887 }
888
889 void mac_updateterm(WindowPtr window) {
890     Session *s;
891
892     s = (Session *)GetWRefCon(window);
893     SetPort(window);
894     BeginUpdate(window);
895     pre_paint(s);
896     term_paint(s->term, s,
897                PTOCC((*window->visRgn)->rgnBBox.left),
898                PTOCR((*window->visRgn)->rgnBBox.top),
899                PTOCC((*window->visRgn)->rgnBBox.right),
900                PTOCR((*window->visRgn)->rgnBBox.bottom), 1);
901     /* Restore default colours in case the Window Manager uses them */
902     if (HAVE_COLOR_QD()) {
903         PmForeColor(DEFAULT_FG);
904         PmBackColor(DEFAULT_BG);
905     } else {
906         ForeColor(whiteColor);
907         BackColor(blackColor);
908     }
909     if (FrontWindow() != window)
910         EraseRect(&(*s->scrollbar)->contrlRect);
911     UpdateControls(window, window->visRgn);
912     mac_drawgrowicon(s);
913     post_paint(s);
914     EndUpdate(window);
915 }
916
917 static void mac_drawgrowicon(Session *s) {
918     Rect clip;
919     RgnHandle savergn;
920
921     SetPort(s->window);
922     /*
923      * Stop DrawGrowIcon giving us space for a horizontal scrollbar
924      * See Tech Note TB575 for details.
925      */
926     clip = s->window->portRect;
927     clip.left = clip.right - 15;
928     savergn = NewRgn();
929     GetClip(savergn);
930     ClipRect(&clip);
931     DrawGrowIcon(s->window);
932     SetClip(savergn);
933     DisposeRgn(savergn);
934 }    
935
936 struct do_text_args {
937     Session *s;
938     Rect textrect;
939     char *text;
940     int len;
941     unsigned long attr;
942     int lattr;
943     Point numer, denom;
944 };
945
946 /*
947  * Call from the terminal emulator to draw a bit of text
948  *
949  * x and y are text row and column (zero-based)
950  */
951 void do_text(Context ctx, int x, int y, char *text, int len,
952              unsigned long attr, int lattr) {
953     Session *s = ctx;
954     int style = 0;
955     struct do_text_args a;
956     RgnHandle textrgn;
957     char mactextbuf[1024];
958     UniChar unitextbuf[1024];
959     wchar_t *unitextptr;
960     int i;
961     ByteCount iread, olen;
962     OSStatus err;
963
964     assert(len <= 1024);
965
966     SetPort(s->window);
967     
968     /* First check this text is relevant */
969     a.textrect.top = y * s->font_height;
970     a.textrect.bottom = (y + 1) * s->font_height;
971     a.textrect.left = x * s->font_width;
972     a.textrect.right = (x + len) * s->font_width;
973     if (!RectInRgn(&a.textrect, s->window->visRgn))
974         return;
975
976     /* Unpack Unicode from the mad format we get passed */
977     for (i = 0; i < len; i++)
978         unitextbuf[i] = (unsigned char)text[i] | (attr & CSET_MASK);
979
980     if (s->uni_to_font != NULL) {
981         err = ConvertFromUnicodeToText(s->uni_to_font, len * sizeof(UniChar),
982                                        unitextbuf, kUnicodeUseFallbacksMask,
983                                        0, NULL, NULL, NULL,
984                                        1024, &iread, &olen, mactextbuf);
985         if (err != noErr && err != kTECUsedFallbacksStatus)
986             /* XXX Should handle this more sensibly */
987             return;
988     } else  if (s->font_charset != CS_NONE) {
989         /* XXX this is bogus if wchar_t and UniChar are different sizes. */
990         unitextptr = (wchar_t *)unitextbuf;
991         olen = charset_from_unicode(&unitextptr, &len, mactextbuf, 1024,
992                                     s->font_charset, NULL, ".", 1);
993     } else
994         return;
995
996     a.s = s;
997     a.text = mactextbuf;
998     a.len = olen;
999     a.attr = attr;
1000     a.lattr = lattr;
1001     a.numer.h = a.numer.v = a.denom.h = a.denom.v = 1;
1002     SetPort(s->window);
1003     TextFont(s->fontnum);
1004     if (s->cfg.fontisbold || (attr & ATTR_BOLD) && !s->cfg.bold_colour)
1005         style |= bold;
1006     if (attr & ATTR_UNDER)
1007         style |= underline;
1008     TextFace(style);
1009     TextSize(s->cfg.fontheight);
1010     TextMode(srcOr);
1011     if (HAVE_COLOR_QD())
1012         if (style & bold) {
1013             SpaceExtra(s->font_boldadjust << 16);
1014             CharExtra(s->font_boldadjust << 16);
1015         } else {
1016             SpaceExtra(0);
1017             CharExtra(0);
1018         }
1019     textrgn = NewRgn();
1020     RectRgn(textrgn, &a.textrect);
1021     if (HAVE_COLOR_QD())
1022         DeviceLoop(textrgn, &do_text_for_device_upp, (long)&a, 0);
1023     else
1024         do_text_for_device(1, 0, NULL, (long)&a);
1025     DisposeRgn(textrgn);
1026     /* Tell the window manager about it in case this isn't an update */
1027     ValidRect(&a.textrect);
1028 }
1029
1030 static pascal void do_text_for_device(short depth, short devflags,
1031                                       GDHandle device, long cookie) {
1032     struct do_text_args *a;
1033     int bgcolour, fgcolour, bright, reverse, tmp;
1034
1035     a = (struct do_text_args *)cookie;
1036
1037     bright = (a->attr & ATTR_BOLD) && a->s->cfg.bold_colour;
1038     reverse = a->attr & ATTR_REVERSE;
1039
1040     if (depth == 1 && (a->attr & TATTR_ACTCURS))
1041         reverse = !reverse;
1042
1043     if (HAVE_COLOR_QD()) {
1044         if (depth > 2) {
1045             fgcolour = ((a->attr & ATTR_FGMASK) >> ATTR_FGSHIFT) * 2;
1046             bgcolour = ((a->attr & ATTR_BGMASK) >> ATTR_BGSHIFT) * 2;
1047         } else {
1048             /*
1049              * NB: bold reverse in 2bpp breaks with the usual PuTTY model and
1050              * boldens the background, because that's all we can do.
1051              */
1052             fgcolour = bright ? DEFAULT_FG_BOLD : DEFAULT_FG;
1053             bgcolour = DEFAULT_BG;
1054         }
1055         if (reverse) {
1056             tmp = fgcolour;
1057             fgcolour = bgcolour;
1058             bgcolour = tmp;
1059         }
1060         if (bright && depth > 2)
1061             fgcolour++;
1062         if ((a->attr & TATTR_ACTCURS) && depth > 1) {
1063             fgcolour = CURSOR_FG;
1064             bgcolour = CURSOR_BG;
1065         }
1066         PmForeColor(fgcolour);
1067         PmBackColor(bgcolour);
1068     } else { /* No Color Quickdraw */
1069         /* XXX This should be done with a _little_ more configurability */
1070         if (reverse) {
1071             ForeColor(blackColor);
1072             BackColor(whiteColor);
1073         } else {
1074             ForeColor(whiteColor);
1075             BackColor(blackColor);
1076         }
1077     }
1078
1079     EraseRect(&a->textrect);
1080     MoveTo(a->textrect.left, a->textrect.top + a->s->font_ascent);
1081     /* FIXME: Sort out bold width adjustments on Original QuickDraw. */
1082     if (a->s->window->grafProcs != NULL)
1083         InvokeQDTextUPP(a->len, a->text, a->numer, a->denom,
1084                         a->s->window->grafProcs->textProc);
1085     else
1086         StdText(a->len, a->text, a->numer, a->denom);
1087
1088     if (a->attr & TATTR_PASCURS) {
1089         PenNormal();
1090         switch (depth) {
1091           case 1:
1092             PenMode(patXor);
1093             break;
1094           default:
1095             PmForeColor(CURSOR_BG);
1096             break;
1097         }
1098         FrameRect(&a->textrect);
1099     }
1100 }
1101
1102 void do_cursor(Context ctx, int x, int y, char *text, int len,
1103              unsigned long attr, int lattr)
1104 {
1105
1106     do_text(ctx, x, y, text, len, attr, lattr);
1107 }
1108
1109 /*
1110  * Call from the terminal emulator to get its graphics context.
1111  * Should probably be called start_redraw or something.
1112  */
1113 void pre_paint(Session *s) {
1114     GDHandle gdh;
1115     Rect myrect, tmprect;
1116
1117     if (HAVE_COLOR_QD()) {
1118         s->term->attr_mask = 0;
1119         SetPort(s->window);
1120         myrect = (*s->window->visRgn)->rgnBBox;
1121         LocalToGlobal((Point *)&myrect.top);
1122         LocalToGlobal((Point *)&myrect.bottom);
1123         for (gdh = GetDeviceList();
1124              gdh != NULL;
1125              gdh = GetNextDevice(gdh)) {
1126             if (TestDeviceAttribute(gdh, screenDevice) &&
1127                 TestDeviceAttribute(gdh, screenActive) &&
1128                 SectRect(&(*gdh)->gdRect, &myrect, &tmprect)) {
1129                 switch ((*(*gdh)->gdPMap)->pixelSize) {
1130                   case 1:
1131                     if (s->cfg.bold_colour)
1132                         s->term->attr_mask |= ~(ATTR_COLOURS |
1133                             (s->cfg.bold_colour ? ATTR_BOLD : 0));
1134                     break;
1135                   case 2:
1136                     s->term->attr_mask |= ~ATTR_COLOURS;
1137                     break;
1138                   default:
1139                     s->term->attr_mask = ~0;
1140                     return; /* No point checking more screens. */
1141                 }
1142             }
1143         }
1144     } else
1145         s->term->attr_mask = ~(ATTR_COLOURS |
1146                                 (s->cfg.bold_colour ? ATTR_BOLD : 0));
1147 }
1148
1149 Context get_ctx(void *frontend) {
1150     Session *s = frontend;
1151
1152     pre_paint(s);
1153     return s;
1154 }
1155
1156 void free_ctx(Context ctx) {
1157
1158 }
1159
1160 /*
1161  * Presumably this does something in Windows
1162  */
1163 void post_paint(Session *s) {
1164
1165 }
1166
1167 /*
1168  * Set the scroll bar position
1169  *
1170  * total is the line number of the bottom of the working screen
1171  * start is the line number of the top of the display
1172  * page is the length of the displayed page
1173  */
1174 void set_sbar(void *frontend, int total, int start, int page) {
1175     Session *s = frontend;
1176
1177     /* We don't redraw until we've set everything up, to avoid glitches */
1178     (*s->scrollbar)->contrlMin = 0;
1179     (*s->scrollbar)->contrlMax = total - page;
1180     SetControlValue(s->scrollbar, start);
1181 #if TARGET_RT_CFM
1182     /* XXX: This doesn't link for me. */
1183     if (mac_gestalts.cntlattr & gestaltControlMgrPresent)
1184         SetControlViewSize(s->scrollbar, page);
1185 #endif
1186 }
1187
1188 void sys_cursor(void *frontend, int x, int y)
1189 {
1190     /*
1191      * I think his is meaningless under Mac OS.
1192      */
1193 }
1194
1195 /*
1196  * This is still called when mode==BELL_VISUAL, even though the
1197  * visual bell is handled entirely within terminal.c, because we
1198  * may want to perform additional actions on any kind of bell (for
1199  * example, taskbar flashing in Windows).
1200  */
1201 void beep(void *frontend, int mode)
1202 {
1203     if (mode != BELL_VISUAL)
1204         SysBeep(30);
1205     /*
1206      * XXX We should indicate the relevant window and/or use the
1207      * Notification Manager
1208      */
1209 }
1210
1211 int char_width(Context ctx, int uc)
1212 {
1213     /*
1214      * Until we support exciting character-set stuff, assume all chars are
1215      * single-width.
1216      */
1217     return 1;
1218 }
1219
1220 /*
1221  * Set icon string -- a no-op here (Windowshade?)
1222  */
1223 void set_icon(void *frontend, char *icon) {
1224     Session *s = frontend;
1225
1226 }
1227
1228 /*
1229  * Set the window title
1230  */
1231 void set_title(void *frontend, char *title) {
1232     Session *s = frontend;
1233     Str255 mactitle;
1234
1235     mactitle[0] = sprintf((char *)&mactitle[1], "%s", title);
1236     SetWTitle(s->window, mactitle);
1237 }
1238
1239 /*
1240  * set or clear the "raw mouse message" mode
1241  */
1242 void set_raw_mouse_mode(void *frontend, int activate)
1243 {
1244     Session *s = frontend;
1245
1246     s->raw_mouse = activate;
1247     /* FIXME: Should call mac_updatetermcursor as appropriate. */
1248 }
1249
1250 /*
1251  * Resize the window at the emulator's request
1252  */
1253 void request_resize(void *frontend, int w, int h) {
1254     Session *s = frontend;
1255
1256     s->term->cols = w;
1257     s->term->rows = h;
1258     mac_initfont(s);
1259 }
1260
1261 /*
1262  * Iconify (actually collapse) the window at the emulator's request.
1263  */
1264 void set_iconic(void *frontend, int iconic)
1265 {
1266     Session *s = frontend;
1267     UInt32 features;
1268
1269     if (mac_gestalts.apprvers >= 0x0100 &&
1270         GetWindowFeatures(s->window, &features) == noErr &&
1271         (features & kWindowCanCollapse))
1272         CollapseWindow(s->window, iconic);
1273 }
1274
1275 /*
1276  * Move the window in response to a server-side request.
1277  */
1278 void move_window(void *frontend, int x, int y)
1279 {
1280     Session *s = frontend;
1281
1282     MoveWindow(s->window, x, y, FALSE);
1283 }
1284
1285 /*
1286  * Move the window to the top or bottom of the z-order in response
1287  * to a server-side request.
1288  */
1289 void set_zorder(void *frontend, int top)
1290 {
1291     Session *s = frontend;
1292
1293     /* 
1294      * We also change the input focus to point to the topmost window,
1295      * since that's probably what the Human Interface Guidelines would
1296      * like us to do.
1297      */
1298     if (top)
1299         SelectWindow(s->window);
1300     else
1301         SendBehind(s->window, NULL);
1302 }
1303
1304 /*
1305  * Refresh the window in response to a server-side request.
1306  */
1307 void refresh_window(void *frontend)
1308 {
1309     Session *s = frontend;
1310
1311     term_invalidate(s->term);
1312 }
1313
1314 /*
1315  * Maximise or restore the window in response to a server-side
1316  * request.
1317  */
1318 void set_zoomed(void *frontend, int zoomed)
1319 {
1320     Session *s = frontend;
1321
1322     ZoomWindow(s->window, zoomed ? inZoomOut : inZoomIn, FALSE);
1323 }
1324
1325 /*
1326  * Report whether the window is iconic, for terminal reports.
1327  */
1328 int is_iconic(void *frontend)
1329 {
1330     Session *s = frontend;
1331     UInt32 features;
1332
1333     if (mac_gestalts.apprvers >= 0x0100 &&
1334         GetWindowFeatures(s->window, &features) == noErr &&
1335         (features & kWindowCanCollapse))
1336         return IsWindowCollapsed(s->window);
1337     return FALSE;
1338 }
1339
1340 /*
1341  * Report the window's position, for terminal reports.
1342  */
1343 void get_window_pos(void *frontend, int *x, int *y)
1344 {
1345     Session *s = frontend;
1346
1347     *x = s->window->portRect.left;
1348     *y = s->window->portRect.top;
1349 }
1350
1351 /*
1352  * Report the window's pixel size, for terminal reports.
1353  */
1354 void get_window_pixels(void *frontend, int *x, int *y)
1355 {
1356     Session *s = frontend;
1357
1358     *x = s->window->portRect.right - s->window->portRect.left;
1359     *y = s->window->portRect.bottom - s->window->portRect.top;
1360 }
1361
1362 /*
1363  * Return the window or icon title.
1364  */
1365 char *get_window_title(void *frontend, int icon)
1366 {
1367     Session *s = frontend;
1368
1369     /* Erm, we don't save this at the moment */
1370     return "";
1371 }
1372
1373 /*
1374  * real_palette_set(): This does the actual palette-changing work on behalf
1375  * of palette_set().  Does _not_ call ActivatePalette() in case the caller
1376  * is doing a batch of updates.
1377  */
1378 static void real_palette_set(Session *s, int n, int r, int g, int b)
1379 {
1380     RGBColor col;
1381
1382     if (!HAVE_COLOR_QD())
1383         return;
1384     col.red   = r * 0x0101;
1385     col.green = g * 0x0101;
1386     col.blue  = b * 0x0101;
1387     SetEntryColor(s->palette, n, &col);
1388 }
1389
1390 /*
1391  * Set the logical palette.  Called by the terminal emulator.
1392  */
1393 void palette_set(void *frontend, int n, int r, int g, int b) {
1394     Session *s = frontend;
1395     static const int first[21] = {
1396         0, 2, 4, 6, 8, 10, 12, 14,
1397         1, 3, 5, 7, 9, 11, 13, 15,
1398         16, 17, 18, 20, 21
1399     };
1400     
1401     if (!HAVE_COLOR_QD())
1402         return;
1403     real_palette_set(s, first[n], r, g, b);
1404     if (first[n] == 18)
1405         real_palette_set(s, first[n]+1, r, g, b);
1406     if (first[n] == DEFAULT_BG)
1407         mac_adjustwinbg(s);
1408     ActivatePalette(s->window);
1409 }
1410
1411 /*
1412  * Reset to the default palette
1413  */
1414 void palette_reset(void *frontend) {
1415     Session *s = frontend;
1416     /* This maps colour indices in cfg to those used in our palette. */
1417     static const int ww[] = {
1418         6, 7, 8, 9, 10, 11, 12, 13,
1419         14, 15, 16, 17, 18, 19, 20, 21,
1420         0, 1, 2, 3, 4, 5
1421     };
1422     int i;
1423
1424     if (!HAVE_COLOR_QD())
1425         return;
1426
1427     assert(lenof(ww) == NCOLOURS);
1428
1429     for (i = 0; i < NCOLOURS; i++) {
1430         real_palette_set(s, i,
1431                          s->cfg.colours[ww[i]][0],
1432                          s->cfg.colours[ww[i]][1],
1433                          s->cfg.colours[ww[i]][2]);
1434     }
1435     mac_adjustwinbg(s);
1436     ActivatePalette(s->window);
1437     /* Palette Manager will generate update events as required. */
1438 }
1439
1440 /*
1441  * Scroll the screen. (`lines' is +ve for scrolling forward, -ve
1442  * for backward.)
1443  */
1444 void do_scroll(void *frontend, int topline, int botline, int lines) {
1445     Session *s = frontend;
1446     Rect r;
1447     RgnHandle scrollrgn = NewRgn();
1448     RgnHandle movedupdate = NewRgn();
1449     RgnHandle update = NewRgn();
1450     Point g2l = { 0, 0 };
1451
1452     SetPort(s->window);
1453
1454     /*
1455      * Work out the part of the update region that will scrolled by
1456      * this operation.
1457      */
1458     if (lines > 0)
1459         SetRectRgn(scrollrgn, 0, (topline + lines) * s->font_height,
1460                    s->term->cols * s->font_width,
1461                    (botline + 1) * s->font_height);
1462     else
1463         SetRectRgn(scrollrgn, 0, topline * s->font_height,
1464                    s->term->cols * s->font_width,
1465                    (botline - lines + 1) * s->font_height);
1466     CopyRgn(((WindowPeek)s->window)->updateRgn, movedupdate);
1467     GlobalToLocal(&g2l);
1468     OffsetRgn(movedupdate, g2l.h, g2l.v); /* Convert to local co-ords. */
1469     SectRgn(scrollrgn, movedupdate, movedupdate); /* Clip scrolled section. */
1470     ValidRgn(movedupdate);
1471     OffsetRgn(movedupdate, 0, -lines * s->font_height); /* Scroll it. */
1472
1473     PenNormal();
1474     if (HAVE_COLOR_QD())
1475         PmBackColor(DEFAULT_BG);
1476     else
1477         BackColor(blackColor); /* XXX make configurable */
1478     SetRect(&r, 0, topline * s->font_height,
1479             s->term->cols * s->font_width, (botline + 1) * s->font_height);
1480     ScrollRect(&r, 0, - lines * s->font_height, update);
1481
1482     InvalRgn(update);
1483     InvalRgn(movedupdate);
1484
1485     DisposeRgn(scrollrgn);
1486     DisposeRgn(movedupdate);
1487     DisposeRgn(update);
1488 }
1489
1490 void logevent(void *frontend, char *str) {
1491
1492     /* XXX Do something */
1493 }
1494
1495 /* Dummy routine, only required in plink. */
1496 void ldisc_update(void *frontend, int echo, int edit)
1497 {
1498 }
1499
1500 /*
1501  * Mac PuTTY doesn't support printing yet.
1502  */
1503 printer_job *printer_start_job(char *printer)
1504 {
1505
1506     return NULL;
1507 }
1508
1509 void printer_job_data(printer_job *pj, void *data, int len)
1510 {
1511 }
1512
1513 void printer_finish_job(printer_job *pj)
1514 {
1515 }
1516
1517 void frontend_keypress(void *handle)
1518 {
1519     /*
1520      * Keypress termination in non-Close-On-Exit mode is not
1521      * currently supported in PuTTY proper, because the window
1522      * always has a perfectly good Close button anyway. So we do
1523      * nothing here.
1524      */
1525     return;
1526 }
1527
1528 /*
1529  * Ask whether to wipe a session log file before writing to it.
1530  * Returns 2 for wipe, 1 for append, 0 for cancel (don't log).
1531  */
1532 int askappend(void *frontend, char *filename)
1533 {
1534
1535     /* FIXME: not implemented yet. */
1536     return 2;
1537 }
1538
1539 /*
1540  * Emacs magic:
1541  * Local Variables:
1542  * c-file-style: "simon"
1543  * End:
1544  */
1545