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