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