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