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