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