]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - mac/macterm.c
a80b113a7804048ce1f2d6e3de223a892fb91b7c
[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     }
989 }
990
991 #if !TARGET_API_MAC_CARBON
992 static pascal void mac_growtermdraghook(void)
993 {
994     Session *s = growterm_state.s;
995     GrafPtr portsave;
996     Point mouse;
997     char buf[20];
998     unsigned char pbuf[20];
999     int newrows, newcols;
1000     
1001     GetMouse(&mouse);
1002     newrows = (mouse.v - growterm_state.zeromouse.v) / s->font_height;
1003     if (newrows < 1) newrows = 1;
1004     newcols = (mouse.h - growterm_state.zeromouse.h) / s->font_width;
1005     if (newcols < 1) newcols = 1;
1006     sprintf(buf, "%dx%d", newcols, newrows);
1007     if (strcmp(buf, growterm_state.oldmsg) == 0)
1008         return;
1009     strcpy(growterm_state.oldmsg, buf);
1010     c2pstrcpy(pbuf, buf);
1011
1012     GetPort(&portsave);
1013     SetPort(growterm_state.s->window);
1014     EraseRect(&growterm_state.msgrect);
1015     MoveTo(growterm_state.msgorigin.h, growterm_state.msgorigin.v);
1016     DrawString(pbuf);
1017     SetPort(portsave);
1018 }
1019 #endif
1020
1021 void mac_closeterm(WindowPtr window)
1022 {
1023     Session *s = mac_windowsession(window);
1024
1025     /* XXX warn on close */
1026     HideWindow(s->window);
1027     *s->prev = s->next;
1028     s->next->prev = s->prev;
1029     ldisc_free(s->ldisc);
1030     s->back->free(s->backhandle);
1031     log_free(s->logctx);
1032     if (s->uni_to_font != NULL)
1033         DisposeUnicodeToTextInfo(&s->uni_to_font);
1034     term_free(s->term);
1035     mac_freeeventlog(s);
1036     sfree((WinInfo *)GetWRefCon(s->window));
1037     DisposeWindow(s->window);
1038     DisposePalette(s->palette);
1039     sfree(s);
1040 }
1041
1042 static void mac_activateterm(WindowPtr window, EventRecord *event)
1043 {
1044     Session *s;
1045     Boolean active = (event->modifiers & activeFlag) != 0;
1046
1047     s = mac_windowsession(window);
1048     term_set_focus(s->term, active);
1049     term_update(s->term);
1050     if (active && s->cfg.scrollbar)
1051         ShowControl(s->scrollbar);
1052     else {
1053         if (HAVE_COLOR_QD())
1054             PmBackColor(DEFAULT_BG);/* HideControl clears behind the control */
1055         else
1056             BackColor(blackColor);
1057         HideControl(s->scrollbar);
1058     }
1059     mac_drawgrowicon(s);
1060 }
1061
1062 static void mac_updateterm(WindowPtr window)
1063 {
1064     Session *s;
1065     Rect bbox;
1066 #if TARGET_API_MAC_CARBON
1067     RgnHandle visrgn;
1068 #endif
1069
1070     s = mac_windowsession(window);
1071     SetPort((GrafPtr)GetWindowPort(window));
1072     BeginUpdate(window);
1073     pre_paint(s);
1074 #if TARGET_API_MAC_CARBON
1075     visrgn = NewRgn();
1076     GetPortVisibleRegion(GetWindowPort(window), visrgn);
1077     GetRegionBounds(visrgn, &bbox);
1078 #else
1079     bbox = (*window->visRgn)->rgnBBox;
1080 #endif
1081     term_paint(s->term, s, PTOCC(bbox.left), PTOCR(bbox.top),
1082                PTOCC(bbox.right), PTOCR(bbox.bottom), 1);
1083     /* Restore default colours in case the Window Manager uses them */
1084     if (HAVE_COLOR_QD()) {
1085         PmForeColor(DEFAULT_FG);
1086         PmBackColor(DEFAULT_BG);
1087     } else {
1088         ForeColor(whiteColor);
1089         BackColor(blackColor);
1090     }
1091     if (FrontWindow() != window)
1092 #if TARGET_API_MAC_CARBON
1093         EraseRect(GetControlBounds(s->scrollbar, &bbox));
1094     UpdateControls(window, visrgn);
1095     DisposeRgn(visrgn);
1096 #else
1097         EraseRect(&(*s->scrollbar)->contrlRect);
1098     UpdateControls(window, window->visRgn);
1099 #endif
1100     mac_drawgrowicon(s);
1101     post_paint(s);
1102     EndUpdate(window);
1103 }
1104
1105 static void mac_drawgrowicon(Session *s)
1106 {
1107     Rect clip;
1108     RgnHandle savergn;
1109
1110     SetPort((GrafPtr)GetWindowPort(s->window));
1111     /*
1112      * Stop DrawGrowIcon giving us space for a horizontal scrollbar
1113      * See Tech Note TB575 for details.
1114      */
1115 #if TARGET_API_MAC_CARBON
1116     GetPortBounds(GetWindowPort(s->window), &clip);
1117 #else
1118     clip = s->window->portRect;
1119 #endif
1120     clip.left = clip.right - 15;
1121     savergn = NewRgn();
1122     GetClip(savergn);
1123     ClipRect(&clip);
1124     DrawGrowIcon(s->window);
1125     SetClip(savergn);
1126     DisposeRgn(savergn);
1127 }    
1128
1129 struct do_text_args {
1130     Session *s;
1131     Rect textrect;
1132     char *text;
1133     int len;
1134     unsigned long attr;
1135     int lattr;
1136     Point numer, denom;
1137 };
1138
1139 /*
1140  * Call from the terminal emulator to draw a bit of text
1141  *
1142  * x and y are text row and column (zero-based)
1143  */
1144 void do_text(Context ctx, int x, int y, wchar_t *text, int len,
1145              unsigned long attr, int lattr)
1146 {
1147     Session *s = ctx;
1148     int style;
1149     struct do_text_args a;
1150     RgnHandle textrgn, saveclip;
1151 #if TARGET_API_MAC_CARBON
1152     RgnHandle visrgn;
1153 #endif
1154     char mactextbuf[1024];
1155     wchar_t *unitextptr;
1156     int fontwidth;
1157     ByteCount iread, olen;
1158     OSStatus err;
1159     static DeviceLoopDrawingUPP do_text_for_device_upp = NULL;
1160
1161     assert(len <= 1024);
1162
1163     /* SGT, 2004-10-14: I don't know how to support combining characters
1164      * on the Mac. Hopefully the first person to fail this assertion will
1165      * know how to do it better than me... */
1166     assert(!(attr & TATTR_COMBINING));
1167
1168     SetPort((GrafPtr)GetWindowPort(s->window));
1169
1170     fontwidth = s->font_width;
1171     if ((lattr & LATTR_MODE) != LATTR_NORM)
1172         fontwidth *= 2;
1173
1174     /* First check this text is relevant */
1175     a.textrect.top = y * s->font_height;
1176     a.textrect.bottom = (y + 1) * s->font_height;
1177     a.textrect.left = x * fontwidth;
1178     a.textrect.right = (x + len) * fontwidth;
1179     if (a.textrect.right > s->term->cols * s->font_width)
1180         a.textrect.right = s->term->cols * s->font_width;
1181 #if TARGET_API_MAC_CARBON
1182     visrgn = NewRgn();
1183     GetPortVisibleRegion(GetWindowPort(s->window), visrgn);
1184     if (!RectInRgn(&a.textrect, visrgn)) {
1185         DisposeRgn(visrgn);
1186         return;
1187     }
1188     DisposeRgn(visrgn);
1189 #else
1190     if (!RectInRgn(&a.textrect, s->window->visRgn))
1191         return;
1192 #endif
1193
1194     if (s->uni_to_font != NULL) {
1195         err = ConvertFromUnicodeToText(s->uni_to_font, len * sizeof(UniChar),
1196                                        text, kUnicodeUseFallbacksMask,
1197                                        0, NULL, NULL, NULL,
1198                                        1024, &iread, &olen, mactextbuf);
1199         if (err != noErr && err != kTECUsedFallbacksStatus)
1200             olen = 0;
1201     } else  if (s->font_charset != CS_NONE) {
1202         /* XXX this is bogus if wchar_t and UniChar are different sizes. */
1203         unitextptr = (wchar_t *)text;
1204         olen = charset_from_unicode(&unitextptr, &len, mactextbuf, 1024,
1205                                     s->font_charset, NULL, ".", 1);
1206     } else
1207         olen = 0;
1208
1209     a.s = s;
1210     a.text = mactextbuf;
1211     a.len = olen;
1212     a.attr = attr;
1213     a.lattr = lattr;
1214     switch (lattr & LATTR_MODE) {
1215       case LATTR_NORM:
1216         TextSize(s->cfg.font.size);
1217         a.numer = s->font_stdnumer;
1218         a.denom = s->font_stddenom;
1219         break;
1220       case LATTR_WIDE:
1221         TextSize(s->cfg.font.size);
1222         a.numer = s->font_widenumer;
1223         a.denom = s->font_widedenom;
1224         break;
1225       case LATTR_TOP:
1226       case LATTR_BOT:
1227         TextSize(s->cfg.font.size * 2);
1228         a.numer = s->font_bignumer;
1229         a.denom = s->font_bigdenom;
1230         break;
1231     }
1232     SetPort((GrafPtr)GetWindowPort(s->window));
1233     TextFont(s->fontnum);
1234     style = s->cfg.font.face;
1235     if ((attr & ATTR_BOLD) && !s->cfg.bold_colour)
1236         style |= bold;
1237     if (attr & ATTR_UNDER)
1238         style |= underline;
1239     TextFace(style);
1240     TextMode(srcOr);
1241     if (HAVE_COLOR_QD())
1242         if (style & bold) {
1243             SpaceExtra(s->font_boldadjust << 16);
1244             CharExtra(s->font_boldadjust << 16);
1245         } else {
1246             SpaceExtra(0);
1247             CharExtra(0);
1248         }
1249     saveclip = NewRgn();
1250     GetClip(saveclip);
1251     ClipRect(&a.textrect);
1252     textrgn = NewRgn();
1253     RectRgn(textrgn, &a.textrect);
1254     if (HAVE_COLOR_QD()) {
1255         if (do_text_for_device_upp == NULL)
1256             do_text_for_device_upp =
1257                 NewDeviceLoopDrawingUPP(&do_text_for_device);
1258         DeviceLoop(textrgn, do_text_for_device_upp, (long)&a, 0);
1259     } else
1260         do_text_for_device(1, 0, NULL, (long)&a);
1261     SetClip(saveclip);
1262     DisposeRgn(saveclip);
1263     DisposeRgn(textrgn);
1264     /* Tell the window manager about it in case this isn't an update */
1265 #if TARGET_API_MAC_CARBON
1266     ValidWindowRect(s->window, &a.textrect);
1267 #else
1268     ValidRect(&a.textrect);
1269 #endif
1270 }
1271
1272 static pascal void do_text_for_device(short depth, short devflags,
1273                                       GDHandle device, long cookie)
1274 {
1275     struct do_text_args *a = (struct do_text_args *)cookie;
1276     int bgcolour, fgcolour, bright, reverse, tmp;
1277 #if TARGET_API_MAC_CARBON
1278     CQDProcsPtr gp = GetPortGrafProcs(GetWindowPort(a->s->window));
1279 #else
1280     QDProcsPtr gp = a->s->window->grafProcs;
1281 #endif
1282
1283     bright = (a->attr & ATTR_BOLD) && a->s->cfg.bold_colour;
1284     reverse = a->attr & ATTR_REVERSE;
1285
1286     if (depth == 1 && (a->attr & TATTR_ACTCURS))
1287         reverse = !reverse;
1288
1289     if (HAVE_COLOR_QD()) {
1290         if (depth > 2) {
1291             fgcolour = ((a->attr & ATTR_FGMASK) >> ATTR_FGSHIFT);
1292             bgcolour = ((a->attr & ATTR_BGMASK) >> ATTR_BGSHIFT);
1293         } else {
1294             /*
1295              * NB: bold reverse in 2bpp breaks with the usual PuTTY model and
1296              * boldens the background, because that's all we can do.
1297              */
1298             fgcolour = bright ? DEFAULT_FG_BOLD : DEFAULT_FG;
1299             bgcolour = DEFAULT_BG;
1300         }
1301         if (reverse) {
1302             tmp = fgcolour;
1303             fgcolour = bgcolour;
1304             bgcolour = tmp;
1305         }
1306         if (bright && depth > 2)
1307             if (fgcolour < 16) fgcolour |=8;
1308             else if (fgcolour >= 256) fgcolour |=1;
1309         if ((a->attr & TATTR_ACTCURS) && depth > 1) {
1310             fgcolour = CURSOR_FG;
1311             bgcolour = CURSOR_BG;
1312         }
1313         PmForeColor(fgcolour);
1314         PmBackColor(bgcolour);
1315     } else { /* No Color Quickdraw */
1316         /* XXX This should be done with a _little_ more configurability */
1317         if (reverse) {
1318             ForeColor(blackColor);
1319             BackColor(whiteColor);
1320         } else {
1321             ForeColor(whiteColor);
1322             BackColor(blackColor);
1323         }
1324     }
1325
1326     EraseRect(&a->textrect);
1327     switch (a->lattr & LATTR_MODE) {
1328       case LATTR_NORM:
1329       case LATTR_WIDE:
1330         MoveTo(a->textrect.left, a->textrect.top + a->s->font_ascent);
1331         break;
1332       case LATTR_TOP:
1333         MoveTo(a->textrect.left, a->textrect.top + a->s->font_ascent * 2);
1334         break;
1335       case LATTR_BOT:
1336         MoveTo(a->textrect.left,
1337                a->textrect.top - a->s->font_height + a->s->font_ascent * 2);
1338         break;
1339     }
1340     /* FIXME: Sort out bold width adjustments on Original QuickDraw. */
1341     if (gp != NULL)
1342         InvokeQDTextUPP(a->len, a->text, a->numer, a->denom, gp->textProc);
1343     else
1344         StdText(a->len, a->text, a->numer, a->denom);
1345
1346     if (a->attr & TATTR_PASCURS) {
1347         PenNormal();
1348         switch (depth) {
1349           case 1:
1350             PenMode(patXor);
1351             break;
1352           default:
1353             PmForeColor(CURSOR_BG);
1354             break;
1355         }
1356         FrameRect(&a->textrect);
1357     }
1358 }
1359
1360 void do_cursor(Context ctx, int x, int y, wchar_t *text, int len,
1361              unsigned long attr, int lattr)
1362 {
1363
1364     do_text(ctx, x, y, text, len, attr, lattr);
1365 }
1366
1367 /*
1368  * Call from the terminal emulator to get its graphics context.
1369  * Should probably be called start_redraw or something.
1370  */
1371 void pre_paint(Session *s)
1372 {
1373     GDHandle gdh;
1374     Rect myrect, tmprect;
1375 #if TARGET_API_MAC_CARBON
1376     RgnHandle visrgn;
1377 #endif
1378
1379     if (HAVE_COLOR_QD()) {
1380         s->term->attr_mask = 0;
1381         SetPort((GrafPtr)GetWindowPort(s->window));
1382 #if TARGET_API_MAC_CARBON
1383         visrgn = NewRgn();
1384         GetPortVisibleRegion(GetWindowPort(s->window), visrgn);
1385         GetRegionBounds(visrgn, &myrect);
1386         DisposeRgn(visrgn);
1387 #else
1388         myrect = (*s->window->visRgn)->rgnBBox;
1389 #endif
1390         LocalToGlobal((Point *)&myrect.top);
1391         LocalToGlobal((Point *)&myrect.bottom);
1392         for (gdh = GetDeviceList();
1393              gdh != NULL;
1394              gdh = GetNextDevice(gdh)) {
1395             if (TestDeviceAttribute(gdh, screenDevice) &&
1396                 TestDeviceAttribute(gdh, screenActive) &&
1397                 SectRect(&(*gdh)->gdRect, &myrect, &tmprect)) {
1398                 switch ((*(*gdh)->gdPMap)->pixelSize) {
1399                   case 1:
1400                     if (s->cfg.bold_colour)
1401                         s->term->attr_mask |= ~(ATTR_COLOURS |
1402                             (s->cfg.bold_colour ? ATTR_BOLD : 0));
1403                     break;
1404                   case 2:
1405                     s->term->attr_mask |= ~ATTR_COLOURS;
1406                     break;
1407                   default:
1408                     s->term->attr_mask = ~0;
1409                     return; /* No point checking more screens. */
1410                 }
1411             }
1412         }
1413     } else
1414         s->term->attr_mask = ~(ATTR_COLOURS |
1415                                 (s->cfg.bold_colour ? ATTR_BOLD : 0));
1416 }
1417
1418 Context get_ctx(void *frontend)
1419 {
1420     Session *s = frontend;
1421
1422     pre_paint(s);
1423     return s;
1424 }
1425
1426 void free_ctx(Context ctx)
1427 {
1428
1429 }
1430
1431 /*
1432  * Presumably this does something in Windows
1433  */
1434 void post_paint(Session *s)
1435 {
1436
1437 }
1438
1439 /*
1440  * Set the scroll bar position
1441  *
1442  * total is the line number of the bottom of the working screen
1443  * start is the line number of the top of the display
1444  * page is the length of the displayed page
1445  */
1446 void set_sbar(void *frontend, int total, int start, int page)
1447 {
1448     Session *s = frontend;
1449
1450     /* We don't redraw until we've set everything up, to avoid glitches */
1451     SetControlMinimum(s->scrollbar, 0);
1452     SetControlMaximum(s->scrollbar, total - page);
1453     SetControlValue(s->scrollbar, start);
1454 #if !TARGET_CPU_68K
1455     if (mac_gestalts.cntlattr & gestaltControlMgrPresent)
1456         SetControlViewSize(s->scrollbar, page);
1457 #endif
1458 }
1459
1460 void sys_cursor(void *frontend, int x, int y)
1461 {
1462     /*
1463      * I think his is meaningless under Mac OS.
1464      */
1465 }
1466
1467 /*
1468  * This is still called when mode==BELL_VISUAL, even though the
1469  * visual bell is handled entirely within terminal.c, because we
1470  * may want to perform additional actions on any kind of bell (for
1471  * example, taskbar flashing in Windows).
1472  */
1473 void beep(void *frontend, int mode)
1474 {
1475     if (mode != BELL_VISUAL)
1476         SysBeep(30);
1477     /*
1478      * XXX We should indicate the relevant window and/or use the
1479      * Notification Manager
1480      */
1481 }
1482
1483 int char_width(Context ctx, int uc)
1484 {
1485     /*
1486      * Until we support exciting character-set stuff, assume all chars are
1487      * single-width.
1488      */
1489     return 1;
1490 }
1491
1492 /*
1493  * Set icon string -- a no-op here (Windowshade?)
1494  */
1495 void set_icon(void *frontend, char *icon) {
1496     Session *s = frontend;
1497
1498 }
1499
1500 /*
1501  * Set the window title
1502  */
1503 void set_title(void *frontend, char *title)
1504 {
1505     Session *s = frontend;
1506     Str255 mactitle;
1507
1508     c2pstrcpy(mactitle, title);
1509     SetWTitle(s->window, mactitle);
1510 }
1511
1512 /*
1513  * set or clear the "raw mouse message" mode
1514  */
1515 void set_raw_mouse_mode(void *frontend, int activate)
1516 {
1517     Session *s = frontend;
1518
1519     s->raw_mouse = activate;
1520     /* FIXME: Should call mac_updatetermcursor as appropriate. */
1521 }
1522
1523 /*
1524  * Resize the window at the emulator's request
1525  */
1526 void request_resize(void *frontend, int w, int h)
1527 {
1528     Session *s = frontend;
1529     RgnHandle grayrgn;
1530     Rect graybox;
1531     int wlim, hlim;
1532
1533     /* Arbitrarily clip to the size of the desktop. */
1534     grayrgn = GetGrayRgn();
1535 #if TARGET_API_MAC_CARBON
1536     GetRegionBounds(grayrgn, &graybox);
1537 #else
1538     graybox = (*grayrgn)->rgnBBox;
1539 #endif
1540     wlim = (graybox.right - graybox.left) / s->font_width;
1541     hlim = (graybox.bottom - graybox.top) / s->font_height;
1542     if (w > wlim) w = wlim;
1543     if (h > hlim) h = hlim;
1544     term_size(s->term, h, w, s->cfg.savelines);
1545     mac_initfont(s);
1546 }
1547
1548 /*
1549  * Iconify (actually collapse) the window at the emulator's request.
1550  */
1551 void set_iconic(void *frontend, int iconic)
1552 {
1553     Session *s = frontend;
1554     UInt32 features;
1555
1556     if (mac_gestalts.apprvers >= 0x0100 &&
1557         GetWindowFeatures(s->window, &features) == noErr &&
1558         (features & kWindowCanCollapse))
1559         CollapseWindow(s->window, iconic);
1560 }
1561
1562 /*
1563  * Move the window in response to a server-side request.
1564  */
1565 void move_window(void *frontend, int x, int y)
1566 {
1567     Session *s = frontend;
1568
1569     MoveWindow(s->window, x, y, FALSE);
1570 }
1571
1572 /*
1573  * Move the window to the top or bottom of the z-order in response
1574  * to a server-side request.
1575  */
1576 void set_zorder(void *frontend, int top)
1577 {
1578     Session *s = frontend;
1579
1580     /* 
1581      * We also change the input focus to point to the topmost window,
1582      * since that's probably what the Human Interface Guidelines would
1583      * like us to do.
1584      */
1585     if (top)
1586         SelectWindow(s->window);
1587     else
1588         SendBehind(s->window, NULL);
1589 }
1590
1591 /*
1592  * Refresh the window in response to a server-side request.
1593  */
1594 void refresh_window(void *frontend)
1595 {
1596     Session *s = frontend;
1597
1598     term_invalidate(s->term);
1599 }
1600
1601 /*
1602  * Maximise or restore the window in response to a server-side
1603  * request.
1604  */
1605 void set_zoomed(void *frontend, int zoomed)
1606 {
1607     Session *s = frontend;
1608
1609     ZoomWindow(s->window, zoomed ? inZoomOut : inZoomIn, FALSE);
1610 }
1611
1612 /*
1613  * Report whether the window is iconic, for terminal reports.
1614  */
1615 int is_iconic(void *frontend)
1616 {
1617     Session *s = frontend;
1618     UInt32 features;
1619
1620     if (mac_gestalts.apprvers >= 0x0100 &&
1621         GetWindowFeatures(s->window, &features) == noErr &&
1622         (features & kWindowCanCollapse))
1623         return IsWindowCollapsed(s->window);
1624     return FALSE;
1625 }
1626
1627 /*
1628  * Report the window's position, for terminal reports.
1629  */
1630 void get_window_pos(void *frontend, int *x, int *y)
1631 {
1632     Session *s = frontend;
1633     Rect rect;
1634
1635 #if TARGET_API_MAC_CARBON
1636     GetPortBounds(GetWindowPort(s->window), &rect);
1637 #else
1638     rect = s->window->portRect;
1639 #endif
1640     *x = rect.left;
1641     *y = rect.top;
1642 }
1643
1644 /*
1645  * Report the window's pixel size, for terminal reports.
1646  */
1647 void get_window_pixels(void *frontend, int *x, int *y)
1648 {
1649     Session *s = frontend;
1650     Rect rect;
1651
1652 #if TARGET_API_MAC_CARBON
1653     GetPortBounds(GetWindowPort(s->window), &rect);
1654 #else
1655     rect = s->window->portRect;
1656 #endif
1657     *x = rect.right - rect.left;
1658     *y = rect.bottom - rect.top;
1659 }
1660
1661 /*
1662  * Return the window or icon title.
1663  */
1664 char *get_window_title(void *frontend, int icon)
1665 {
1666     Session *s = frontend;
1667     Str255 ptitle;
1668     static char title[256];
1669
1670     GetWTitle(s->window, ptitle);
1671     p2cstrcpy(title, ptitle);
1672     return title;
1673 }
1674
1675 /*
1676  * real_palette_set(): This does the actual palette-changing work on behalf
1677  * of palette_set().  Does _not_ call ActivatePalette() in case the caller
1678  * is doing a batch of updates.
1679  */
1680 static void real_palette_set(Session *s, int n, int r, int g, int b)
1681 {
1682     RGBColor col;
1683
1684     if (!HAVE_COLOR_QD())
1685         return;
1686     col.red   = r * 0x0101;
1687     col.green = g * 0x0101;
1688     col.blue  = b * 0x0101;
1689     SetEntryColor(s->palette, n, &col);
1690 }
1691
1692 /*
1693  * Set the logical palette.  Called by the terminal emulator.
1694  */
1695 void palette_set(void *frontend, int n, int r, int g, int b)
1696 {
1697     Session *s = frontend;
1698     
1699     if (!HAVE_COLOR_QD())
1700         return;
1701     real_palette_set(s, n, r, g, b);
1702     if (n == DEFAULT_BG)
1703         mac_adjustwinbg(s);
1704
1705     ActivatePalette(s->window);
1706 }
1707
1708 /*
1709  * Reset to the default palette
1710  */
1711 void palette_reset(void *frontend)
1712 {
1713     Session *s = frontend;
1714     /* This maps colour indices in cfg to those used in our palette. */
1715     static const int ww[] = {
1716         256, 257, 258, 259, 260, 261,
1717         0, 8, 1, 9, 2, 10, 3, 11,
1718         4, 12, 5, 13, 6, 14, 7, 15
1719     };
1720
1721     int i;
1722
1723     if (!HAVE_COLOR_QD())
1724         return;
1725
1726     for (i = 0; i < 22; i++) {
1727         int w = ww[i];
1728         real_palette_set(s,w,
1729                          s->cfg.colours[i][0],
1730                          s->cfg.colours[i][1],
1731                          s->cfg.colours[i][2]);
1732     }
1733     for (i = 0; i < 240; i++) {
1734         if (i < 216) {
1735             int r = i / 36, g = (i / 6) % 6, b = i % 6;
1736             real_palette_set(s,i+16,
1737                              r * 0x33,
1738                              g * 0x33,
1739                              b * 0x33);
1740         } else {
1741             int shade = i - 216;
1742             shade = (shade + 1) * 0xFF / (240 - 216 + 1);
1743             real_palette_set(s,i+16,shade,shade,shade);
1744         }
1745     }
1746
1747
1748     mac_adjustwinbg(s);
1749     ActivatePalette(s->window);
1750     /* Palette Manager will generate update events as required. */
1751 }
1752
1753 /*
1754  * Scroll the screen. (`lines' is +ve for scrolling forward, -ve
1755  * for backward.)
1756  */
1757 void do_scroll(Context ctx, int topline, int botline, int lines)
1758 {
1759     Session *s = ctx;
1760     Rect r;
1761     RgnHandle scrollrgn = NewRgn();
1762     RgnHandle movedupdate = NewRgn();
1763     RgnHandle update = NewRgn();
1764     Point g2l = { 0, 0 };
1765
1766     SetPort((GrafPtr)GetWindowPort(s->window));
1767
1768     /*
1769      * Work out the part of the update region that will scrolled by
1770      * this operation.
1771      */
1772     if (lines > 0)
1773         SetRectRgn(scrollrgn, 0, (topline + lines) * s->font_height,
1774                    s->term->cols * s->font_width,
1775                    (botline + 1) * s->font_height);
1776     else
1777         SetRectRgn(scrollrgn, 0, topline * s->font_height,
1778                    s->term->cols * s->font_width,
1779                    (botline - lines + 1) * s->font_height);
1780 #if TARGET_API_MAC_CARBON
1781     GetWindowRegion(s->window, kWindowUpdateRgn, movedupdate);
1782 #else
1783     GetWindowUpdateRgn(s->window, movedupdate);
1784 #endif
1785     GlobalToLocal(&g2l);
1786     OffsetRgn(movedupdate, g2l.h, g2l.v); /* Convert to local co-ords. */
1787     SectRgn(scrollrgn, movedupdate, movedupdate); /* Clip scrolled section. */
1788 #if TARGET_API_MAC_CARBON
1789     ValidWindowRgn(s->window, movedupdate);
1790 #else
1791     ValidRgn(movedupdate);
1792 #endif
1793     OffsetRgn(movedupdate, 0, -lines * s->font_height); /* Scroll it. */
1794
1795     PenNormal();
1796     if (HAVE_COLOR_QD())
1797         PmBackColor(DEFAULT_BG);
1798     else
1799         BackColor(blackColor); /* XXX make configurable */
1800     SetRect(&r, 0, topline * s->font_height,
1801             s->term->cols * s->font_width, (botline + 1) * s->font_height);
1802     ScrollRect(&r, 0, - lines * s->font_height, update);
1803
1804 #if TARGET_API_MAC_CARBON
1805     InvalWindowRgn(s->window, update);
1806     InvalWindowRgn(s->window, movedupdate);
1807 #else
1808     InvalRgn(update);
1809     InvalRgn(movedupdate);
1810 #endif
1811
1812     DisposeRgn(scrollrgn);
1813     DisposeRgn(movedupdate);
1814     DisposeRgn(update);
1815 }
1816
1817 /* Dummy routine, only required in plink. */
1818 void ldisc_update(void *frontend, int echo, int edit)
1819 {
1820 }
1821
1822 /*
1823  * Mac PuTTY doesn't support printing yet.
1824  */
1825 printer_job *printer_start_job(char *printer)
1826 {
1827
1828     return NULL;
1829 }
1830
1831 void printer_job_data(printer_job *pj, void *data, int len)
1832 {
1833 }
1834
1835 void printer_finish_job(printer_job *pj)
1836 {
1837 }
1838
1839 void frontend_keypress(void *handle)
1840 {
1841     /*
1842      * Keypress termination in non-Close-On-Exit mode is not
1843      * currently supported in PuTTY proper, because the window
1844      * always has a perfectly good Close button anyway. So we do
1845      * nothing here.
1846      */
1847     return;
1848 }
1849
1850 /*
1851  * Ask whether to wipe a session log file before writing to it.
1852  * Returns 2 for wipe, 1 for append, 0 for cancel (don't log).
1853  */
1854 int askappend(void *frontend, Filename filename)
1855 {
1856
1857     /* FIXME: not implemented yet. */
1858     return 2;
1859 }
1860
1861 int from_backend(void *frontend, int is_stderr, const char *data, int len)
1862 {
1863     Session *s = frontend;
1864
1865     return term_data(s->term, is_stderr, data, len);
1866 }
1867
1868 /*
1869  * Emacs magic:
1870  * Local Variables:
1871  * c-file-style: "simon"
1872  * End:
1873  */
1874