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