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