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