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