1 /* $Id: macterm.c,v 1.63 2003/02/01 15:44:08 ben Exp $ */
3 * Copyright (c) 1999 Simon Tatham
4 * Copyright (c) 1999, 2002 Ben Harris
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
16 * The above copyright notice and this permission notice shall be
17 * included in all copies or substantial portions of the Software.
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
30 * macterm.c -- Macintosh terminal front-end
35 #include <ControlDefinitions.h>
40 #include <MacMemory.h>
41 #include <MacWindows.h>
42 #include <MixedMode.h>
44 #include <Quickdraw.h>
45 #include <QuickdrawText.h>
46 #include <Resources.h>
50 #include <TextCommon.h>
51 #include <ToolUtils.h>
52 #include <UnicodeConverter.h>
66 #define NCOLOURS (lenof(((Config *)0)->colours))
69 #define DEFAULT_FG_BOLD 17
71 #define DEFAULT_BG_BOLD 19
75 #define PTOCC(x) ((x) < 0 ? -(-(x - s->font_width - 1) / s->font_width) : \
77 #define PTOCR(y) ((y) < 0 ? -(-(y - s->font_height - 1) / s->font_height) : \
80 static void mac_initfont(Session *);
81 static pascal OSStatus uni_to_font_fallback(UniChar *, ByteCount, ByteCount *,
82 TextPtr, ByteCount, ByteCount *,
84 ConstUnicodeMappingPtr);
85 static void mac_initpalette(Session *);
86 static void mac_adjustwinbg(Session *);
87 static void mac_adjustsize(Session *, int, int);
88 static void mac_drawgrowicon(Session *s);
89 static pascal void mac_growtermdraghook(void);
90 static pascal void mac_scrolltracker(ControlHandle, short);
91 static pascal void do_text_for_device(short, short, GDHandle, long);
92 static void text_click(Session *, EventRecord *);
94 void pre_paint(Session *s);
95 void post_paint(Session *s);
98 static RoutineDescriptor mac_scrolltracker_upp =
99 BUILD_ROUTINE_DESCRIPTOR(uppControlActionProcInfo,
100 (ProcPtr)mac_scrolltracker);
101 static RoutineDescriptor do_text_for_device_upp =
102 BUILD_ROUTINE_DESCRIPTOR(uppDeviceLoopDrawingProcInfo,
103 (ProcPtr)do_text_for_device);
104 #else /* not TARGET_RT_MAC_CFM */
105 #define mac_scrolltracker_upp mac_scrolltracker
106 #define do_text_for_device_upp do_text_for_device
107 #endif /* not TARGET_RT_MAC_CFM */
109 void mac_startsession(Session *s)
117 * Select protocol. This is farmed out into a table in a
118 * separate file to enable an ssh-free variant.
121 for (i = 0; backends[i].backend != NULL; i++)
122 if (backends[i].protocol == s->cfg.protocol) {
123 s->back = backends[i].backend;
127 fatalbox("Unsupported protocol number found");
129 /* XXX: Own storage management? */
131 s->window = GetNewCWindow(wTerminal, NULL, (WindowPtr)-1);
133 s->window = GetNewWindow(wTerminal, NULL, (WindowPtr)-1);
134 SetWRefCon(s->window, (long)s);
135 s->scrollbar = GetNewControl(cVScroll, s->window);
136 s->term = term_init(&s->cfg, &s->ucsdata, s);
140 if (HAVE_COLOR_QD()) {
141 /* Set to FALSE to not get palette updates in the background. */
142 SetPalette(s->window, s->palette, TRUE);
143 ActivatePalette(s->window);
146 s->logctx = log_init(s, &s->cfg);
147 term_provide_logctx(s->term, s->logctx);
149 errmsg = s->back->init(s->term, &s->backhandle, &s->cfg, s->cfg.host,
150 s->cfg.port, &s->realhost, s->cfg.tcp_nodelay);
152 fatalbox("%s", errmsg);
153 s->back->provide_logctx(s->backhandle, s->logctx);
154 set_title(s, s->realhost);
156 term_provide_resize_fn(s->term, s->back->size, s->backhandle);
158 mac_adjustsize(s, s->cfg.height, s->cfg.width);
159 term_size(s->term, s->cfg.height, s->cfg.width, s->cfg.savelines);
161 s->ldisc = ldisc_create(&s->cfg, s->term, s->back, s->backhandle, s);
162 ldisc_send(s->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
164 ShowWindow(s->window);
168 s->next->prev = &s->next;
173 * Try to work out a horizontal scaling factor for the current font
174 * that will give a chracter width of wantwidth. Return it in numer
175 * and denom (suitable for passing to StdText()).
177 static void mac_workoutfontscale(Session *s, int wantwidth,
178 Point *numerp, Point *denomp)
180 Point numer, denom, tmpnumer, tmpdenom;
182 const char text = 'W';
185 numer.v = denom.v = 1; /* always */
186 numer.h = denom.h = 1;
187 for (i = 0; i < 3; i++) {
190 if (s->window->grafProcs != NULL)
191 gotwidth = InvokeQDTxMeasUPP(1, &text, &tmpnumer, &tmpdenom, &fi,
192 s->window->grafProcs->txMeasProc);
194 gotwidth = StdTxMeas(1, &text, &tmpnumer, &tmpdenom, &fi);
195 /* The result of StdTxMeas must be scaled by the factors it returns. */
196 gotwidth = FixRound(FixMul(gotwidth << 16,
197 FixRatio(tmpnumer.h, tmpdenom.h)));
198 if (gotwidth == wantwidth)
200 numer.h *= wantwidth;
207 static UnicodeToTextFallbackUPP uni_to_font_fallback_upp;
209 static void mac_initfont(Session *s) {
215 GetFNum(s->cfg.font.name, &s->fontnum);
216 TextFont(s->fontnum);
217 TextFace(s->cfg.font.face);
218 TextSize(s->cfg.font.size);
220 s->font_width = CharWidth('W'); /* Well, it's what NCSA uses. */
221 s->font_ascent = fi.ascent;
222 s->font_leading = fi.leading;
223 s->font_height = s->font_ascent + fi.descent + s->font_leading;
224 mac_workoutfontscale(s, s->font_width,
225 &s->font_stdnumer, &s->font_stddenom);
226 mac_workoutfontscale(s, s->font_width * 2,
227 &s->font_widenumer, &s->font_widedenom);
228 TextSize(s->cfg.font.size * 2);
229 mac_workoutfontscale(s, s->font_width * 2,
230 &s->font_bignumer, &s->font_bigdenom);
231 TextSize(s->cfg.font.size);
232 if (!s->cfg.bold_colour) {
234 s->font_boldadjust = s->font_width - CharWidth('W');
236 s->font_boldadjust = 0;
238 if (s->uni_to_font != NULL)
239 DisposeUnicodeToTextInfo(&s->uni_to_font);
240 if (mac_gestalts.encvvers != 0 &&
241 UpgradeScriptInfoToTextEncoding(kTextScriptDontCare,
242 kTextLanguageDontCare,
243 kTextRegionDontCare, s->cfg.font.name,
245 CreateUnicodeToTextInfoByEncoding(enc, &s->uni_to_font) == noErr) {
246 if (uni_to_font_fallback_upp == NULL)
247 uni_to_font_fallback_upp =
248 NewUnicodeToTextFallbackProc(&uni_to_font_fallback);
249 fbflags = kUnicodeFallbackCustomOnly;
250 if (mac_gestalts.uncvattr & kTECAddFallbackInterruptMask)
251 fbflags |= kUnicodeFallbackInterruptSafeMask;
252 if (SetFallbackUnicodeToText(s->uni_to_font,
253 uni_to_font_fallback_upp, fbflags, NULL) != noErr) {
254 DisposeUnicodeToTextInfo(&s->uni_to_font);
261 s->uni_to_font = NULL;
262 p2cstrcpy(cfontname, s->cfg.font.name);
264 charset_from_macenc(FontToScript(s->fontnum),
265 GetScriptManagerVariable(smRegionCode),
266 mac_gestalts.sysvers, cfontname);
269 mac_adjustsize(s, s->term->rows, s->term->cols);
272 static pascal OSStatus uni_to_font_fallback(UniChar *ucp,
273 ByteCount ilen, ByteCount *iusedp, TextPtr obuf, ByteCount olen,
274 ByteCount *ousedp, LogicalAddress *cookie, ConstUnicodeMappingPtr mapping)
278 return kTECOutputBufferFullStatus;
280 * What I'd _like_ to do here is to somehow generate the
281 * missing-character glyph that every font is required to have.
282 * Unfortunately (and somewhat surprisingly), I can't find any way
283 * to actually ask for it explicitly. Bah.
292 * Called every time round the event loop.
294 void mac_pollterm(void)
298 for (s = sesslist; s != NULL; s = s->next) {
300 term_update(s->term);
305 * To be called whenever the window size changes.
306 * rows and cols should be desired values.
307 * It's assumed the terminal emulator will be informed, and will set rows
310 static void mac_adjustsize(Session *s, int newrows, int newcols) {
311 int winwidth, winheight;
313 winwidth = newcols * s->font_width + 15;
314 winheight = newrows * s->font_height;
315 SizeWindow(s->window, winwidth, winheight, true);
316 HideControl(s->scrollbar);
317 MoveControl(s->scrollbar, winwidth - 15, -1);
318 SizeControl(s->scrollbar, 16, winheight - 13);
319 ShowControl(s->scrollbar);
323 static void mac_initpalette(Session *s) {
325 if (!HAVE_COLOR_QD())
328 * Most colours should be inhibited on 2bpp displays.
329 * Palette manager documentation suggests inhibiting all tolerant colours
330 * on greyscale displays.
332 #define PM_NORMAL ( pmTolerant | pmInhibitC2 | \
333 pmInhibitG2 | pmInhibitG4 | pmInhibitG8 )
334 #define PM_TOLERANCE 0x2000
335 s->palette = NewPalette(22, NULL, PM_NORMAL, PM_TOLERANCE);
336 if (s->palette == NULL)
337 fatalbox("Unable to create palette");
338 /* In 2bpp, these are the colours we want most. */
339 SetEntryUsage(s->palette, DEFAULT_BG,
340 PM_NORMAL &~ pmInhibitC2, PM_TOLERANCE);
341 SetEntryUsage(s->palette, DEFAULT_FG,
342 PM_NORMAL &~ pmInhibitC2, PM_TOLERANCE);
343 SetEntryUsage(s->palette, DEFAULT_FG_BOLD,
344 PM_NORMAL &~ pmInhibitC2, PM_TOLERANCE);
345 SetEntryUsage(s->palette, CURSOR_BG,
346 PM_NORMAL &~ pmInhibitC2, PM_TOLERANCE);
351 * Set the background colour of the window correctly. Should be
352 * called whenever the default background changes.
354 static void mac_adjustwinbg(Session *s) {
356 if (!HAVE_COLOR_QD())
359 if (mac_gestalts.windattr & gestaltWindowMgrPresent)
360 SetWindowContentColor(s->window,
361 &(*s->palette)->pmInfo[DEFAULT_BG].ciRGB);
365 if (s->wctab == NULL)
366 s->wctab = (WCTabHandle)NewHandle(sizeof(**s->wctab));
367 if (s->wctab == NULL)
368 return; /* do without */
369 (*s->wctab)->wCSeed = 0;
370 (*s->wctab)->wCReserved = 0;
371 (*s->wctab)->ctSize = 0;
372 (*s->wctab)->ctTable[0].value = wContentColor;
373 (*s->wctab)->ctTable[0].rgb = (*s->palette)->pmInfo[DEFAULT_BG].ciRGB;
374 SetWinColor(s->window, s->wctab);
379 * Set the cursor shape correctly
381 void mac_adjusttermcursor(WindowPtr window, Point mouse, RgnHandle cursrgn) {
383 ControlHandle control;
388 s = (Session *)GetWRefCon(window);
389 GlobalToLocal(&mouse);
390 part = FindControl(mouse, window, &control);
391 if (control == s->scrollbar) {
392 SetCursor(&qd.arrow);
393 RectRgn(cursrgn, &(*s->scrollbar)->contrlRect);
394 SectRgn(cursrgn, window->visRgn, cursrgn);
396 x = mouse.h / s->font_width;
397 y = mouse.v / s->font_height;
399 SetCursor(&qd.arrow);
401 SetCursor(*GetCursor(iBeamCursor));
402 /* Ask for shape changes if we leave this character cell. */
403 SetRectRgn(cursrgn, x * s->font_width, y * s->font_height,
404 (x + 1) * s->font_width, (y + 1) * s->font_height);
405 SectRgn(cursrgn, window->visRgn, cursrgn);
410 * Enable/disable menu items based on the active terminal window.
412 void mac_adjusttermmenus(WindowPtr window) {
417 s = (Session *)GetWRefCon(window);
418 menu = GetMenuHandle(mFile);
419 DisableItem(menu, iSave); /* XXX enable if modified */
420 EnableItem(menu, iSaveAs);
421 EnableItem(menu, iDuplicate);
422 menu = GetMenuHandle(mEdit);
424 DisableItem(menu, iUndo);
425 DisableItem(menu, iCut);
426 if (1/*s->term->selstate == SELECTED*/)
427 EnableItem(menu, iCopy);
429 DisableItem(menu, iCopy);
430 if (GetScrap(NULL, 'TEXT', &offset) == noTypeErr)
431 DisableItem(menu, iPaste);
433 EnableItem(menu, iPaste);
434 DisableItem(menu, iClear);
435 EnableItem(menu, iSelectAll);
438 void mac_menuterm(WindowPtr window, short menu, short item) {
441 s = (Session *)GetWRefCon(window);
449 term_do_paste(s->term);
455 void mac_clickterm(WindowPtr window, EventRecord *event) {
458 ControlHandle control;
461 s = (Session *)GetWRefCon(window);
463 mouse = event->where;
464 GlobalToLocal(&mouse);
465 part = FindControl(mouse, window, &control);
466 if (control == s->scrollbar) {
468 case kControlIndicatorPart:
469 if (TrackControl(control, mouse, NULL) == kControlIndicatorPart)
470 term_scroll(s->term, +1, GetControlValue(control));
472 case kControlUpButtonPart:
473 case kControlDownButtonPart:
474 case kControlPageUpPart:
475 case kControlPageDownPart:
476 TrackControl(control, mouse, &mac_scrolltracker_upp);
480 text_click(s, event);
484 static void text_click(Session *s, EventRecord *event) {
487 static UInt32 lastwhen = 0;
488 static Session *lastsess = NULL;
489 static int lastrow = -1, lastcol = -1;
490 static Mouse_Action lastact = MA_NOTHING;
493 localwhere = event->where;
494 GlobalToLocal(&localwhere);
496 col = PTOCC(localwhere.h);
497 row = PTOCR(localwhere.v);
498 if (event->when - lastwhen < GetDblTime() &&
499 row == lastrow && col == lastcol && s == lastsess)
500 lastact = (lastact == MA_CLICK ? MA_2CLK :
501 lastact == MA_2CLK ? MA_3CLK :
502 lastact == MA_3CLK ? MA_CLICK : MA_NOTHING);
505 term_mouse(s->term, MBT_LEFT,
506 event->modifiers & shiftKey ? MBT_EXTEND : MBT_SELECT,
507 lastact, col, row, event->modifiers & shiftKey,
508 event->modifiers & controlKey, event->modifiers & optionKey);
512 while (StillDown()) {
513 GetMouse(&localwhere);
514 col = PTOCC(localwhere.h);
515 row = PTOCR(localwhere.v);
516 term_mouse(s->term, MBT_LEFT,
517 event->modifiers & shiftKey ? MBT_EXTEND : MBT_SELECT,
518 MA_DRAG, col, row, event->modifiers & shiftKey,
519 event->modifiers & controlKey,
520 event->modifiers & optionKey);
521 if (row > s->term->rows - 1)
522 term_scroll(s->term, 0, row - (s->term->rows - 1));
524 term_scroll(s->term, 0, row);
526 term_mouse(s->term, MBT_LEFT,
527 event->modifiers & shiftKey ? MBT_EXTEND : MBT_SELECT,
528 MA_RELEASE, col, row, event->modifiers & shiftKey,
529 event->modifiers & controlKey, event->modifiers & optionKey);
530 lastwhen = TickCount();
533 void write_clip(void *cookie, wchar_t *data, int len, int must_deselect)
537 ByteCount iread, olen;
545 * See "Programming with the Text Encoding Conversion Manager"
546 * Appendix E for Unicode scrap conventions.
548 * XXX Maybe PICT scrap too.
550 if (ZeroScrap() != noErr)
552 PutScrap(len * sizeof(*data), 'utxt', data);
554 /* Replace LINE SEPARATORs with CR for TEXT output. */
555 for (i = 0; i < len; i++)
556 if (data[i] == 0x2028)
559 mactextbuf = smalloc(len); /* XXX DBCS */
560 if (s->uni_to_font != NULL) {
561 err = ConvertFromUnicodeToText(s->uni_to_font, len * sizeof(UniChar),
563 kUnicodeUseFallbacksMask,
565 len, &iread, &olen, mactextbuf);
566 if (err != noErr && err != kTECUsedFallbacksStatus)
568 } else if (s->font_charset != CS_NONE) {
570 olen = charset_from_unicode(&unitextptr, &len, mactextbuf, 1024,
571 s->font_charset, NULL, ".", 1);
574 PutScrap(olen, 'TEXT', mactextbuf);
577 stsz = offsetof(StScrpRec, scrpStyleTab) + sizeof(ScrpSTElement);
578 stsc = smalloc(stsz);
579 stsc->scrpNStyles = 1;
580 stsc->scrpStyleTab[0].scrpStartChar = 0;
581 stsc->scrpStyleTab[0].scrpHeight = s->font_height;
582 stsc->scrpStyleTab[0].scrpAscent = s->font_ascent;
583 stsc->scrpStyleTab[0].scrpFont = s->fontnum;
584 stsc->scrpStyleTab[0].scrpFace = 0;
585 stsc->scrpStyleTab[0].scrpSize = s->cfg.font.size;
586 stsc->scrpStyleTab[0].scrpColor.red = 0;
587 stsc->scrpStyleTab[0].scrpColor.green = 0;
588 stsc->scrpStyleTab[0].scrpColor.blue = 0;
589 PutScrap(stsz, 'styl', stsc);
593 void get_clip(void *frontend, wchar_t **p, int *lenp) {
594 Session *s = frontend;
595 static Handle h = NULL;
596 static wchar_t *data = NULL;
601 TextToUnicodeInfo scrap_to_uni;
602 ByteCount iread, olen;
616 if (GetScrap(NULL, 'utxt', &offset) > 0) {
619 *lenp = GetScrap(h, 'utxt', &offset) / sizeof(**p);
622 } else if (GetScrap(NULL, 'TEXT', &offset) > 0) {
623 texth = NewHandle(0);
624 textlen = GetScrap(texth, 'TEXT', &offset);
626 data = smalloc(textlen * 2);
627 /* XXX should use 'styl' scrap if it's there. */
628 if (mac_gestalts.encvvers != 0 &&
629 UpgradeScriptInfoToTextEncoding(smSystemScript,
630 kTextLanguageDontCare,
631 kTextRegionDontCare, NULL,
633 CreateTextToUnicodeInfoByEncoding(enc, &scrap_to_uni) ==
635 err = ConvertFromTextToUnicode(scrap_to_uni, textlen,
636 *texth, 0, 0, NULL, NULL, NULL,
638 &iread, &olen, data);
639 DisposeTextToUnicodeInfo(&scrap_to_uni);
642 *lenp = olen / sizeof(**p);
649 charset_from_macenc(GetScriptManagerVariable(smSysScript),
650 GetScriptManagerVariable(smRegionCode),
651 mac_gestalts.sysvers, NULL);
652 if (charset != CS_NONE) {
654 *lenp = charset_to_unicode(&tptr, &textlen, data,
655 textlen * 2, charset, NULL,
660 DisposeHandle(texth);
668 static pascal void mac_scrolltracker(ControlHandle control, short part) {
671 s = (Session *)GetWRefCon((*control)->contrlOwner);
673 case kControlUpButtonPart:
674 term_scroll(s->term, 0, -1);
676 case kControlDownButtonPart:
677 term_scroll(s->term, 0, +1);
679 case kControlPageUpPart:
680 term_scroll(s->term, 0, -(s->term->rows - 1));
682 case kControlPageDownPart:
683 term_scroll(s->term, 0, +(s->term->rows - 1));
688 void mac_keyterm(WindowPtr window, EventRecord *event) {
689 Session *s = (Session *)GetWRefCon(window);
690 Key_Sym keysym = PK_NULL;
691 unsigned int mods = 0, flags = PKF_NUMLOCK;
697 fprintf(stderr, "Got key event %08x\n", event->message);
700 /* No meta key yet -- that'll be rather fun. */
702 /* Keys that we handle locally */
703 if (event->modifiers & shiftKey) {
704 switch ((event->message & keyCodeMask) >> 8) {
705 case 0x74: /* shift-pageup */
706 term_scroll(s->term, 0, -(s->term->rows - 1));
708 case 0x79: /* shift-pagedown */
709 term_scroll(s->term, 0, +(s->term->rows - 1));
714 if (event->modifiers & shiftKey)
716 if (event->modifiers & controlKey)
718 if (event->what == autoKey)
721 /* Mac key events consist of a virtual key code and a character code. */
723 switch ((event->message & keyCodeMask) >> 8) {
724 case 0x24: keysym = PK_RETURN; break;
725 case 0x30: keysym = PK_TAB; break;
726 case 0x33: keysym = PK_BACKSPACE; break;
727 case 0x35: keysym = PK_ESCAPE; break;
729 case 0x7A: keysym = PK_F1; break;
730 case 0x78: keysym = PK_F2; break;
731 case 0x63: keysym = PK_F3; break;
732 case 0x76: keysym = PK_F4; break;
733 case 0x60: keysym = PK_F5; break;
734 case 0x61: keysym = PK_F6; break;
735 case 0x62: keysym = PK_F7; break;
736 case 0x64: keysym = PK_F8; break;
737 case 0x65: keysym = PK_F9; break;
738 case 0x6D: keysym = PK_F10; break;
739 case 0x67: keysym = PK_F11; break;
740 case 0x6F: keysym = PK_F12; break;
741 case 0x69: keysym = PK_F13; break;
742 case 0x6B: keysym = PK_F14; break;
743 case 0x71: keysym = PK_F15; break;
745 case 0x72: keysym = PK_INSERT; break;
746 case 0x73: keysym = PK_HOME; break;
747 case 0x74: keysym = PK_PAGEUP; break;
748 case 0x75: keysym = PK_DELETE; break;
749 case 0x77: keysym = PK_END; break;
750 case 0x79: keysym = PK_PAGEDOWN; break;
752 case 0x47: keysym = PK_PF1; break;
753 case 0x51: keysym = PK_PF2; break;
754 case 0x4B: keysym = PK_PF3; break;
755 case 0x43: keysym = PK_PF4; break;
756 case 0x4E: keysym = PK_KPMINUS; break;
757 case 0x45: keysym = PK_KPCOMMA; break;
758 case 0x41: keysym = PK_KPDECIMAL; break;
759 case 0x4C: keysym = PK_KPENTER; break;
760 case 0x52: keysym = PK_KP0; break;
761 case 0x53: keysym = PK_KP1; break;
762 case 0x54: keysym = PK_KP2; break;
763 case 0x55: keysym = PK_KP3; break;
764 case 0x56: keysym = PK_KP4; break;
765 case 0x57: keysym = PK_KP5; break;
766 case 0x58: keysym = PK_KP6; break;
767 case 0x59: keysym = PK_KP7; break;
768 case 0x5B: keysym = PK_KP8; break;
769 case 0x5C: keysym = PK_KP9; break;
771 case 0x7B: keysym = PK_LEFT; break;
772 case 0x7C: keysym = PK_RIGHT; break;
773 case 0x7D: keysym = PK_DOWN; break;
774 case 0x7E: keysym = PK_UP; break;
777 /* XXX Map from key script to Unicode. */
778 utxt[0] = event->message & charCodeMask;
779 term_key(s->term, keysym, utxt, 1, mods, flags);
782 void request_paste(void *frontend)
784 Session *s = frontend;
787 * In the Mac OS, pasting is synchronous: we can read the
788 * clipboard with no difficulty, so request_paste() can just go
791 term_do_paste(s->term);
802 void mac_growterm(WindowPtr window, EventRecord *event) {
805 int newrows, newcols;
807 DragGrayRgnUPP draghooksave;
811 s = (Session *)GetWRefCon(window);
813 draghooksave = LMGetDragHook();
814 growterm_state.oldmsg[0] = '\0';
815 growterm_state.zeromouse = event->where;
816 growterm_state.zeromouse.h -= s->term->cols * s->font_width;
817 growterm_state.zeromouse.v -= s->term->rows * s->font_height;
818 growterm_state.s = s;
821 BackColor(whiteColor);
822 ForeColor(blackColor);
823 TextFont(systemFont);
827 SetRect(&growterm_state.msgrect, 0, 0,
828 StringWidth("\p99999x99999") + 4, fi.ascent + fi.descent + 4);
829 SetPt(&growterm_state.msgorigin, 2, fi.ascent + 2);
830 LMSetDragHook(NewDragGrayRgnUPP(mac_growtermdraghook));
832 SetRect(&limits, s->font_width + 15, s->font_height, SHRT_MAX, SHRT_MAX);
833 grow_result = GrowWindow(window, event->where, &limits);
835 DisposeDragGrayRgnUPP(LMGetDragHook());
836 LMSetDragHook(draghooksave);
837 InvalRect(&growterm_state.msgrect);
841 if (grow_result != 0) {
842 newrows = HiWord(grow_result) / s->font_height;
843 newcols = (LoWord(grow_result) - 15) / s->font_width;
844 mac_adjustsize(s, newrows, newcols);
845 term_size(s->term, newrows, newcols, s->cfg.savelines);
849 static pascal void mac_growtermdraghook(void)
851 Session *s = growterm_state.s;
855 unsigned char pbuf[20];
856 int newrows, newcols;
859 newrows = (mouse.v - growterm_state.zeromouse.v) / s->font_height;
860 if (newrows < 1) newrows = 1;
861 newcols = (mouse.h - growterm_state.zeromouse.h) / s->font_width;
862 if (newcols < 1) newcols = 1;
863 sprintf(buf, "%dx%d", newcols, newrows);
864 if (strcmp(buf, growterm_state.oldmsg) == 0)
866 strcpy(growterm_state.oldmsg, buf);
867 c2pstrcpy(pbuf, buf);
870 SetPort(growterm_state.s->window);
871 EraseRect(&growterm_state.msgrect);
872 MoveTo(growterm_state.msgorigin.h, growterm_state.msgorigin.v);
877 void mac_closeterm(WindowPtr window)
879 Session *s = (Session *)GetWRefCon(window);
881 /* XXX warn on close */
882 HideWindow(s->window);
884 s->next->prev = s->prev;
885 ldisc_free(s->ldisc);
886 s->back->free(s->backhandle);
888 if (s->uni_to_font != NULL)
889 DisposeUnicodeToTextInfo(&s->uni_to_font);
891 DisposeWindow(s->window);
892 DisposePalette(s->palette);
896 void mac_activateterm(WindowPtr window, Boolean active) {
899 s = (Session *)GetWRefCon(window);
900 s->term->has_focus = active;
901 term_update(s->term);
903 ShowControl(s->scrollbar);
906 PmBackColor(DEFAULT_BG);/* HideControl clears behind the control */
908 BackColor(blackColor);
909 HideControl(s->scrollbar);
914 void mac_updateterm(WindowPtr window) {
917 s = (Session *)GetWRefCon(window);
921 term_paint(s->term, s,
922 PTOCC((*window->visRgn)->rgnBBox.left),
923 PTOCR((*window->visRgn)->rgnBBox.top),
924 PTOCC((*window->visRgn)->rgnBBox.right),
925 PTOCR((*window->visRgn)->rgnBBox.bottom), 1);
926 /* Restore default colours in case the Window Manager uses them */
927 if (HAVE_COLOR_QD()) {
928 PmForeColor(DEFAULT_FG);
929 PmBackColor(DEFAULT_BG);
931 ForeColor(whiteColor);
932 BackColor(blackColor);
934 if (FrontWindow() != window)
935 EraseRect(&(*s->scrollbar)->contrlRect);
936 UpdateControls(window, window->visRgn);
942 static void mac_drawgrowicon(Session *s) {
948 * Stop DrawGrowIcon giving us space for a horizontal scrollbar
949 * See Tech Note TB575 for details.
951 clip = s->window->portRect;
952 clip.left = clip.right - 15;
956 DrawGrowIcon(s->window);
961 struct do_text_args {
972 * Call from the terminal emulator to draw a bit of text
974 * x and y are text row and column (zero-based)
976 void do_text(Context ctx, int x, int y, char *text, int len,
977 unsigned long attr, int lattr) {
980 struct do_text_args a;
981 RgnHandle textrgn, saveclip;
982 char mactextbuf[1024];
983 UniChar unitextbuf[1024];
986 ByteCount iread, olen;
993 fontwidth = s->font_width;
994 if ((lattr & LATTR_MODE) != LATTR_NORM)
997 /* First check this text is relevant */
998 a.textrect.top = y * s->font_height;
999 a.textrect.bottom = (y + 1) * s->font_height;
1000 a.textrect.left = x * fontwidth;
1001 a.textrect.right = (x + len) * fontwidth;
1002 if (a.textrect.right > s->term->cols * s->font_width)
1003 a.textrect.right = s->term->cols * s->font_width;
1004 if (!RectInRgn(&a.textrect, s->window->visRgn))
1007 /* Unpack Unicode from the mad format we get passed */
1008 for (i = 0; i < len; i++)
1009 unitextbuf[i] = (unsigned char)text[i] | (attr & CSET_MASK);
1011 if (s->uni_to_font != NULL) {
1012 err = ConvertFromUnicodeToText(s->uni_to_font, len * sizeof(UniChar),
1013 unitextbuf, kUnicodeUseFallbacksMask,
1014 0, NULL, NULL, NULL,
1015 1024, &iread, &olen, mactextbuf);
1016 if (err != noErr && err != kTECUsedFallbacksStatus)
1018 } else if (s->font_charset != CS_NONE) {
1019 /* XXX this is bogus if wchar_t and UniChar are different sizes. */
1020 unitextptr = (wchar_t *)unitextbuf;
1021 olen = charset_from_unicode(&unitextptr, &len, mactextbuf, 1024,
1022 s->font_charset, NULL, ".", 1);
1027 a.text = mactextbuf;
1031 switch (lattr & LATTR_MODE) {
1033 TextSize(s->cfg.font.size);
1034 a.numer = s->font_stdnumer;
1035 a.denom = s->font_stddenom;
1038 TextSize(s->cfg.font.size);
1039 a.numer = s->font_widenumer;
1040 a.denom = s->font_widedenom;
1044 TextSize(s->cfg.font.size * 2);
1045 a.numer = s->font_bignumer;
1046 a.denom = s->font_bigdenom;
1050 TextFont(s->fontnum);
1051 style = s->cfg.font.face;
1052 if ((attr & ATTR_BOLD) && !s->cfg.bold_colour)
1054 if (attr & ATTR_UNDER)
1058 if (HAVE_COLOR_QD())
1060 SpaceExtra(s->font_boldadjust << 16);
1061 CharExtra(s->font_boldadjust << 16);
1066 saveclip = NewRgn();
1068 ClipRect(&a.textrect);
1070 RectRgn(textrgn, &a.textrect);
1071 if (HAVE_COLOR_QD())
1072 DeviceLoop(textrgn, &do_text_for_device_upp, (long)&a, 0);
1074 do_text_for_device(1, 0, NULL, (long)&a);
1076 DisposeRgn(saveclip);
1077 DisposeRgn(textrgn);
1078 /* Tell the window manager about it in case this isn't an update */
1079 ValidRect(&a.textrect);
1082 static pascal void do_text_for_device(short depth, short devflags,
1083 GDHandle device, long cookie) {
1084 struct do_text_args *a;
1085 int bgcolour, fgcolour, bright, reverse, tmp;
1087 a = (struct do_text_args *)cookie;
1089 bright = (a->attr & ATTR_BOLD) && a->s->cfg.bold_colour;
1090 reverse = a->attr & ATTR_REVERSE;
1092 if (depth == 1 && (a->attr & TATTR_ACTCURS))
1095 if (HAVE_COLOR_QD()) {
1097 fgcolour = ((a->attr & ATTR_FGMASK) >> ATTR_FGSHIFT);
1098 fgcolour = (fgcolour & 0xF) * 2 + (fgcolour & 0x10 ? 1 : 0);
1099 bgcolour = ((a->attr & ATTR_BGMASK) >> ATTR_BGSHIFT);
1100 bgcolour = (bgcolour & 0xF) * 2 + (bgcolour & 0x10 ? 1 : 0);
1103 * NB: bold reverse in 2bpp breaks with the usual PuTTY model and
1104 * boldens the background, because that's all we can do.
1106 fgcolour = bright ? DEFAULT_FG_BOLD : DEFAULT_FG;
1107 bgcolour = DEFAULT_BG;
1111 fgcolour = bgcolour;
1114 if (bright && depth > 2)
1116 if ((a->attr & TATTR_ACTCURS) && depth > 1) {
1117 fgcolour = CURSOR_FG;
1118 bgcolour = CURSOR_BG;
1120 PmForeColor(fgcolour);
1121 PmBackColor(bgcolour);
1122 } else { /* No Color Quickdraw */
1123 /* XXX This should be done with a _little_ more configurability */
1125 ForeColor(blackColor);
1126 BackColor(whiteColor);
1128 ForeColor(whiteColor);
1129 BackColor(blackColor);
1133 EraseRect(&a->textrect);
1134 switch (a->lattr & LATTR_MODE) {
1137 MoveTo(a->textrect.left, a->textrect.top + a->s->font_ascent);
1140 MoveTo(a->textrect.left, a->textrect.top + a->s->font_ascent * 2);
1143 MoveTo(a->textrect.left,
1144 a->textrect.top - a->s->font_height + a->s->font_ascent * 2);
1147 /* FIXME: Sort out bold width adjustments on Original QuickDraw. */
1148 if (a->s->window->grafProcs != NULL)
1149 InvokeQDTextUPP(a->len, a->text, a->numer, a->denom,
1150 a->s->window->grafProcs->textProc);
1152 StdText(a->len, a->text, a->numer, a->denom);
1154 if (a->attr & TATTR_PASCURS) {
1161 PmForeColor(CURSOR_BG);
1164 FrameRect(&a->textrect);
1168 void do_cursor(Context ctx, int x, int y, char *text, int len,
1169 unsigned long attr, int lattr)
1172 do_text(ctx, x, y, text, len, attr, lattr);
1176 * Call from the terminal emulator to get its graphics context.
1177 * Should probably be called start_redraw or something.
1179 void pre_paint(Session *s) {
1181 Rect myrect, tmprect;
1183 if (HAVE_COLOR_QD()) {
1184 s->term->attr_mask = 0;
1186 myrect = (*s->window->visRgn)->rgnBBox;
1187 LocalToGlobal((Point *)&myrect.top);
1188 LocalToGlobal((Point *)&myrect.bottom);
1189 for (gdh = GetDeviceList();
1191 gdh = GetNextDevice(gdh)) {
1192 if (TestDeviceAttribute(gdh, screenDevice) &&
1193 TestDeviceAttribute(gdh, screenActive) &&
1194 SectRect(&(*gdh)->gdRect, &myrect, &tmprect)) {
1195 switch ((*(*gdh)->gdPMap)->pixelSize) {
1197 if (s->cfg.bold_colour)
1198 s->term->attr_mask |= ~(ATTR_COLOURS |
1199 (s->cfg.bold_colour ? ATTR_BOLD : 0));
1202 s->term->attr_mask |= ~ATTR_COLOURS;
1205 s->term->attr_mask = ~0;
1206 return; /* No point checking more screens. */
1211 s->term->attr_mask = ~(ATTR_COLOURS |
1212 (s->cfg.bold_colour ? ATTR_BOLD : 0));
1215 Context get_ctx(void *frontend) {
1216 Session *s = frontend;
1222 void free_ctx(Context ctx) {
1227 * Presumably this does something in Windows
1229 void post_paint(Session *s) {
1234 * Set the scroll bar position
1236 * total is the line number of the bottom of the working screen
1237 * start is the line number of the top of the display
1238 * page is the length of the displayed page
1240 void set_sbar(void *frontend, int total, int start, int page) {
1241 Session *s = frontend;
1243 /* We don't redraw until we've set everything up, to avoid glitches */
1244 (*s->scrollbar)->contrlMin = 0;
1245 (*s->scrollbar)->contrlMax = total - page;
1246 SetControlValue(s->scrollbar, start);
1248 if (mac_gestalts.cntlattr & gestaltControlMgrPresent)
1249 SetControlViewSize(s->scrollbar, page);
1253 void sys_cursor(void *frontend, int x, int y)
1256 * I think his is meaningless under Mac OS.
1261 * This is still called when mode==BELL_VISUAL, even though the
1262 * visual bell is handled entirely within terminal.c, because we
1263 * may want to perform additional actions on any kind of bell (for
1264 * example, taskbar flashing in Windows).
1266 void beep(void *frontend, int mode)
1268 if (mode != BELL_VISUAL)
1271 * XXX We should indicate the relevant window and/or use the
1272 * Notification Manager
1276 int char_width(Context ctx, int uc)
1279 * Until we support exciting character-set stuff, assume all chars are
1286 * Set icon string -- a no-op here (Windowshade?)
1288 void set_icon(void *frontend, char *icon) {
1289 Session *s = frontend;
1294 * Set the window title
1296 void set_title(void *frontend, char *title) {
1297 Session *s = frontend;
1300 c2pstrcpy(mactitle, title);
1301 SetWTitle(s->window, mactitle);
1305 * set or clear the "raw mouse message" mode
1307 void set_raw_mouse_mode(void *frontend, int activate)
1309 Session *s = frontend;
1311 s->raw_mouse = activate;
1312 /* FIXME: Should call mac_updatetermcursor as appropriate. */
1316 * Resize the window at the emulator's request
1318 void request_resize(void *frontend, int w, int h) {
1319 Session *s = frontend;
1321 term_size(s->term, h, w, s->cfg.savelines);
1326 * Iconify (actually collapse) the window at the emulator's request.
1328 void set_iconic(void *frontend, int iconic)
1330 Session *s = frontend;
1333 if (mac_gestalts.apprvers >= 0x0100 &&
1334 GetWindowFeatures(s->window, &features) == noErr &&
1335 (features & kWindowCanCollapse))
1336 CollapseWindow(s->window, iconic);
1340 * Move the window in response to a server-side request.
1342 void move_window(void *frontend, int x, int y)
1344 Session *s = frontend;
1346 MoveWindow(s->window, x, y, FALSE);
1350 * Move the window to the top or bottom of the z-order in response
1351 * to a server-side request.
1353 void set_zorder(void *frontend, int top)
1355 Session *s = frontend;
1358 * We also change the input focus to point to the topmost window,
1359 * since that's probably what the Human Interface Guidelines would
1363 SelectWindow(s->window);
1365 SendBehind(s->window, NULL);
1369 * Refresh the window in response to a server-side request.
1371 void refresh_window(void *frontend)
1373 Session *s = frontend;
1375 term_invalidate(s->term);
1379 * Maximise or restore the window in response to a server-side
1382 void set_zoomed(void *frontend, int zoomed)
1384 Session *s = frontend;
1386 ZoomWindow(s->window, zoomed ? inZoomOut : inZoomIn, FALSE);
1390 * Report whether the window is iconic, for terminal reports.
1392 int is_iconic(void *frontend)
1394 Session *s = frontend;
1397 if (mac_gestalts.apprvers >= 0x0100 &&
1398 GetWindowFeatures(s->window, &features) == noErr &&
1399 (features & kWindowCanCollapse))
1400 return IsWindowCollapsed(s->window);
1405 * Report the window's position, for terminal reports.
1407 void get_window_pos(void *frontend, int *x, int *y)
1409 Session *s = frontend;
1411 *x = s->window->portRect.left;
1412 *y = s->window->portRect.top;
1416 * Report the window's pixel size, for terminal reports.
1418 void get_window_pixels(void *frontend, int *x, int *y)
1420 Session *s = frontend;
1422 *x = s->window->portRect.right - s->window->portRect.left;
1423 *y = s->window->portRect.bottom - s->window->portRect.top;
1427 * Return the window or icon title.
1429 char *get_window_title(void *frontend, int icon)
1431 Session *s = frontend;
1433 static char title[256];
1435 GetWTitle(s->window, ptitle);
1436 p2cstrcpy(title, ptitle);
1441 * real_palette_set(): This does the actual palette-changing work on behalf
1442 * of palette_set(). Does _not_ call ActivatePalette() in case the caller
1443 * is doing a batch of updates.
1445 static void real_palette_set(Session *s, int n, int r, int g, int b)
1449 if (!HAVE_COLOR_QD())
1451 col.red = r * 0x0101;
1452 col.green = g * 0x0101;
1453 col.blue = b * 0x0101;
1454 SetEntryColor(s->palette, n, &col);
1458 * Set the logical palette. Called by the terminal emulator.
1460 void palette_set(void *frontend, int n, int r, int g, int b) {
1461 Session *s = frontend;
1462 static const int first[21] = {
1463 0, 2, 4, 6, 8, 10, 12, 14,
1464 1, 3, 5, 7, 9, 11, 13, 15,
1468 if (!HAVE_COLOR_QD())
1470 real_palette_set(s, first[n], r, g, b);
1472 real_palette_set(s, first[n]+1, r, g, b);
1473 if (first[n] == DEFAULT_BG)
1475 ActivatePalette(s->window);
1479 * Reset to the default palette
1481 void palette_reset(void *frontend) {
1482 Session *s = frontend;
1483 /* This maps colour indices in cfg to those used in our palette. */
1484 static const int ww[] = {
1485 6, 7, 8, 9, 10, 11, 12, 13,
1486 14, 15, 16, 17, 18, 19, 20, 21,
1491 if (!HAVE_COLOR_QD())
1494 assert(lenof(ww) == NCOLOURS);
1496 for (i = 0; i < NCOLOURS; i++) {
1497 real_palette_set(s, i,
1498 s->cfg.colours[ww[i]][0],
1499 s->cfg.colours[ww[i]][1],
1500 s->cfg.colours[ww[i]][2]);
1503 ActivatePalette(s->window);
1504 /* Palette Manager will generate update events as required. */
1508 * Scroll the screen. (`lines' is +ve for scrolling forward, -ve
1511 void do_scroll(Context ctx, int topline, int botline, int lines) {
1514 RgnHandle scrollrgn = NewRgn();
1515 RgnHandle movedupdate = NewRgn();
1516 RgnHandle update = NewRgn();
1517 Point g2l = { 0, 0 };
1522 * Work out the part of the update region that will scrolled by
1526 SetRectRgn(scrollrgn, 0, (topline + lines) * s->font_height,
1527 s->term->cols * s->font_width,
1528 (botline + 1) * s->font_height);
1530 SetRectRgn(scrollrgn, 0, topline * s->font_height,
1531 s->term->cols * s->font_width,
1532 (botline - lines + 1) * s->font_height);
1533 CopyRgn(((WindowPeek)s->window)->updateRgn, movedupdate);
1534 GlobalToLocal(&g2l);
1535 OffsetRgn(movedupdate, g2l.h, g2l.v); /* Convert to local co-ords. */
1536 SectRgn(scrollrgn, movedupdate, movedupdate); /* Clip scrolled section. */
1537 ValidRgn(movedupdate);
1538 OffsetRgn(movedupdate, 0, -lines * s->font_height); /* Scroll it. */
1541 if (HAVE_COLOR_QD())
1542 PmBackColor(DEFAULT_BG);
1544 BackColor(blackColor); /* XXX make configurable */
1545 SetRect(&r, 0, topline * s->font_height,
1546 s->term->cols * s->font_width, (botline + 1) * s->font_height);
1547 ScrollRect(&r, 0, - lines * s->font_height, update);
1550 InvalRgn(movedupdate);
1552 DisposeRgn(scrollrgn);
1553 DisposeRgn(movedupdate);
1557 void logevent(void *frontend, char *str) {
1559 fprintf(stderr, "%s\n", str);
1562 /* Dummy routine, only required in plink. */
1563 void ldisc_update(void *frontend, int echo, int edit)
1568 * Mac PuTTY doesn't support printing yet.
1570 printer_job *printer_start_job(char *printer)
1576 void printer_job_data(printer_job *pj, void *data, int len)
1580 void printer_finish_job(printer_job *pj)
1584 void frontend_keypress(void *handle)
1587 * Keypress termination in non-Close-On-Exit mode is not
1588 * currently supported in PuTTY proper, because the window
1589 * always has a perfectly good Close button anyway. So we do
1596 * Ask whether to wipe a session log file before writing to it.
1597 * Returns 2 for wipe, 1 for append, 0 for cancel (don't log).
1599 int askappend(void *frontend, Filename filename)
1602 /* FIXME: not implemented yet. */
1609 * c-file-style: "simon"