1 /* $Id: macterm.c,v 1.52 2003/01/18 20:09:21 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 int mac_keytrans(Session *, EventRecord *, unsigned char *);
93 static void text_click(Session *, EventRecord *);
95 void pre_paint(Session *s);
96 void post_paint(Session *s);
99 static RoutineDescriptor mac_scrolltracker_upp =
100 BUILD_ROUTINE_DESCRIPTOR(uppControlActionProcInfo,
101 (ProcPtr)mac_scrolltracker);
102 static RoutineDescriptor do_text_for_device_upp =
103 BUILD_ROUTINE_DESCRIPTOR(uppDeviceLoopDrawingProcInfo,
104 (ProcPtr)do_text_for_device);
105 #else /* not TARGET_RT_MAC_CFM */
106 #define mac_scrolltracker_upp mac_scrolltracker
107 #define do_text_for_device_upp do_text_for_device
108 #endif /* not TARGET_RT_MAC_CFM */
110 void mac_startsession(Session *s)
115 /* XXX: Own storage management? */
117 s->window = GetNewCWindow(wTerminal, NULL, (WindowPtr)-1);
119 s->window = GetNewWindow(wTerminal, NULL, (WindowPtr)-1);
120 SetWRefCon(s->window, (long)s);
121 s->scrollbar = GetNewControl(cVScroll, s->window);
122 s->term = term_init(&s->cfg, &s->ucsdata, s);
126 if (HAVE_COLOR_QD()) {
127 /* Set to FALSE to not get palette updates in the background. */
128 SetPalette(s->window, s->palette, TRUE);
129 ActivatePalette(s->window);
132 s->logctx = log_init(s, &s->cfg);
133 term_provide_logctx(s->term, s->logctx);
135 errmsg = s->back->init(s->term, &s->backhandle, &s->cfg, s->cfg.host,
136 s->cfg.port, &s->realhost, s->cfg.tcp_nodelay);
138 fatalbox("%s", errmsg);
139 s->back->provide_logctx(s->backhandle, s->logctx);
140 set_title(s, s->realhost);
142 term_provide_resize_fn(s->term, s->back->size, s->backhandle);
144 mac_adjustsize(s, s->cfg.height, s->cfg.width);
145 term_size(s->term, s->cfg.height, s->cfg.width, s->cfg.savelines);
147 s->ldisc = ldisc_create(&s->cfg, s->term, s->back, s->backhandle, s);
148 ldisc_send(s->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
150 ShowWindow(s->window);
154 s->next->prev = &s->next;
159 * Try to work out a horizontal scaling factor for the current font
160 * that will give a chracter width of wantwidth. Return it in numer
161 * and denom (suitable for passing to StdText()).
163 static void mac_workoutfontscale(Session *s, int wantwidth,
164 Point *numerp, Point *denomp)
166 Point numer, denom, tmpnumer, tmpdenom;
168 const char text = 'W';
171 numer.v = denom.v = 1; /* always */
172 numer.h = denom.h = 1;
173 for (i = 0; i < 3; i++) {
176 if (s->window->grafProcs != NULL)
177 gotwidth = InvokeQDTxMeasUPP(1, &text, &tmpnumer, &tmpdenom, &fi,
178 s->window->grafProcs->txMeasProc);
180 gotwidth = StdTxMeas(1, &text, &tmpnumer, &tmpdenom, &fi);
181 /* The result of StdTxMeas must be scaled by the factors it returns. */
182 gotwidth = FixRound(FixMul(gotwidth << 16,
183 FixRatio(tmpnumer.h, tmpdenom.h)));
184 if (gotwidth == wantwidth)
186 numer.h *= wantwidth;
193 static UnicodeToTextFallbackUPP uni_to_font_fallback_upp;
195 static void mac_initfont(Session *s) {
202 c2pstrcpy(macfont, s->cfg.font);
203 GetFNum(macfont, &s->fontnum);
204 TextFont(s->fontnum);
205 TextFace(s->cfg.fontisbold ? bold : 0);
206 TextSize(s->cfg.fontheight);
208 s->font_width = CharWidth('W'); /* Well, it's what NCSA uses. */
209 s->font_ascent = fi.ascent;
210 s->font_leading = fi.leading;
211 s->font_height = s->font_ascent + fi.descent + s->font_leading;
212 mac_workoutfontscale(s, s->font_width,
213 &s->font_stdnumer, &s->font_stddenom);
214 mac_workoutfontscale(s, s->font_width * 2,
215 &s->font_widenumer, &s->font_widedenom);
216 TextSize(s->cfg.fontheight * 2);
217 mac_workoutfontscale(s, s->font_width * 2,
218 &s->font_bignumer, &s->font_bigdenom);
219 TextSize(s->cfg.fontheight);
220 if (!s->cfg.bold_colour) {
222 s->font_boldadjust = s->font_width - CharWidth('W');
224 s->font_boldadjust = 0;
226 if (s->uni_to_font != NULL)
227 DisposeUnicodeToTextInfo(&s->uni_to_font);
228 if (mac_gestalts.encvvers != 0 &&
229 UpgradeScriptInfoToTextEncoding(kTextScriptDontCare,
230 kTextLanguageDontCare,
231 kTextRegionDontCare, macfont,
233 CreateUnicodeToTextInfoByEncoding(enc, &s->uni_to_font) == noErr) {
234 if (uni_to_font_fallback_upp == NULL)
235 uni_to_font_fallback_upp =
236 NewUnicodeToTextFallbackProc(&uni_to_font_fallback);
237 fbflags = kUnicodeFallbackCustomOnly;
238 if (mac_gestalts.uncvattr & kTECAddFallbackInterruptMask)
239 fbflags |= kUnicodeFallbackInterruptSafeMask;
240 if (SetFallbackUnicodeToText(s->uni_to_font,
241 uni_to_font_fallback_upp, fbflags, NULL) != noErr) {
242 DisposeUnicodeToTextInfo(&s->uni_to_font);
247 s->uni_to_font = NULL;
249 charset_from_macenc(FontToScript(s->fontnum),
250 GetScriptManagerVariable(smRegionCode),
251 mac_gestalts.sysvers, s->cfg.font);
254 mac_adjustsize(s, s->term->rows, s->term->cols);
257 static pascal OSStatus uni_to_font_fallback(UniChar *ucp,
258 ByteCount ilen, ByteCount *iusedp, TextPtr obuf, ByteCount olen,
259 ByteCount *ousedp, LogicalAddress *cookie, ConstUnicodeMappingPtr mapping)
263 return kTECOutputBufferFullStatus;
265 * What I'd _like_ to do here is to somehow generate the
266 * missing-character glyph that every font is required to have.
267 * Unfortunately (and somewhat surprisingly), I can't find any way
268 * to actually ask for it explicitly. Bah.
277 * Called every time round the event loop.
279 void mac_pollterm(void)
283 for (s = sesslist; s != NULL; s = s->next) {
285 term_update(s->term);
290 * To be called whenever the window size changes.
291 * rows and cols should be desired values.
292 * It's assumed the terminal emulator will be informed, and will set rows
295 static void mac_adjustsize(Session *s, int newrows, int newcols) {
296 int winwidth, winheight;
298 winwidth = newcols * s->font_width + 15;
299 winheight = newrows * s->font_height;
300 SizeWindow(s->window, winwidth, winheight, true);
301 HideControl(s->scrollbar);
302 MoveControl(s->scrollbar, winwidth - 15, -1);
303 SizeControl(s->scrollbar, 16, winheight - 13);
304 ShowControl(s->scrollbar);
308 static void mac_initpalette(Session *s) {
310 if (!HAVE_COLOR_QD())
313 * Most colours should be inhibited on 2bpp displays.
314 * Palette manager documentation suggests inhibiting all tolerant colours
315 * on greyscale displays.
317 #define PM_NORMAL ( pmTolerant | pmInhibitC2 | \
318 pmInhibitG2 | pmInhibitG4 | pmInhibitG8 )
319 #define PM_TOLERANCE 0x2000
320 s->palette = NewPalette(22, NULL, PM_NORMAL, PM_TOLERANCE);
321 if (s->palette == NULL)
322 fatalbox("Unable to create palette");
323 /* In 2bpp, these are the colours we want most. */
324 SetEntryUsage(s->palette, DEFAULT_BG,
325 PM_NORMAL &~ pmInhibitC2, PM_TOLERANCE);
326 SetEntryUsage(s->palette, DEFAULT_FG,
327 PM_NORMAL &~ pmInhibitC2, PM_TOLERANCE);
328 SetEntryUsage(s->palette, DEFAULT_FG_BOLD,
329 PM_NORMAL &~ pmInhibitC2, PM_TOLERANCE);
330 SetEntryUsage(s->palette, CURSOR_BG,
331 PM_NORMAL &~ pmInhibitC2, PM_TOLERANCE);
336 * Set the background colour of the window correctly. Should be
337 * called whenever the default background changes.
339 static void mac_adjustwinbg(Session *s) {
341 if (!HAVE_COLOR_QD())
344 if (mac_gestalts.windattr & gestaltWindowMgrPresent)
345 SetWindowContentColor(s->window,
346 &(*s->palette)->pmInfo[DEFAULT_BG].ciRGB);
350 if (s->wctab == NULL)
351 s->wctab = (WCTabHandle)NewHandle(sizeof(**s->wctab));
352 if (s->wctab == NULL)
353 return; /* do without */
354 (*s->wctab)->wCSeed = 0;
355 (*s->wctab)->wCReserved = 0;
356 (*s->wctab)->ctSize = 0;
357 (*s->wctab)->ctTable[0].value = wContentColor;
358 (*s->wctab)->ctTable[0].rgb = (*s->palette)->pmInfo[DEFAULT_BG].ciRGB;
359 SetWinColor(s->window, s->wctab);
364 * Set the cursor shape correctly
366 void mac_adjusttermcursor(WindowPtr window, Point mouse, RgnHandle cursrgn) {
368 ControlHandle control;
373 s = (Session *)GetWRefCon(window);
374 GlobalToLocal(&mouse);
375 part = FindControl(mouse, window, &control);
376 if (control == s->scrollbar) {
377 SetCursor(&qd.arrow);
378 RectRgn(cursrgn, &(*s->scrollbar)->contrlRect);
379 SectRgn(cursrgn, window->visRgn, cursrgn);
381 x = mouse.h / s->font_width;
382 y = mouse.v / s->font_height;
384 SetCursor(&qd.arrow);
386 SetCursor(*GetCursor(iBeamCursor));
387 /* Ask for shape changes if we leave this character cell. */
388 SetRectRgn(cursrgn, x * s->font_width, y * s->font_height,
389 (x + 1) * s->font_width, (y + 1) * s->font_height);
390 SectRgn(cursrgn, window->visRgn, cursrgn);
395 * Enable/disable menu items based on the active terminal window.
397 void mac_adjusttermmenus(WindowPtr window) {
402 s = (Session *)GetWRefCon(window);
403 menu = GetMenuHandle(mFile);
404 DisableItem(menu, iSave); /* XXX enable if modified */
405 EnableItem(menu, iSaveAs);
406 menu = GetMenuHandle(mEdit);
408 DisableItem(menu, iUndo);
409 DisableItem(menu, iCut);
410 if (1/*s->term->selstate == SELECTED*/)
411 EnableItem(menu, iCopy);
413 DisableItem(menu, iCopy);
414 if (GetScrap(NULL, 'TEXT', &offset) == noTypeErr)
415 DisableItem(menu, iPaste);
417 EnableItem(menu, iPaste);
418 DisableItem(menu, iClear);
419 EnableItem(menu, iSelectAll);
422 void mac_menuterm(WindowPtr window, short menu, short item) {
425 s = (Session *)GetWRefCon(window);
433 term_do_paste(s->term);
439 void mac_clickterm(WindowPtr window, EventRecord *event) {
442 ControlHandle control;
445 s = (Session *)GetWRefCon(window);
447 mouse = event->where;
448 GlobalToLocal(&mouse);
449 part = FindControl(mouse, window, &control);
450 if (control == s->scrollbar) {
452 case kControlIndicatorPart:
453 if (TrackControl(control, mouse, NULL) == kControlIndicatorPart)
454 term_scroll(s->term, +1, GetControlValue(control));
456 case kControlUpButtonPart:
457 case kControlDownButtonPart:
458 case kControlPageUpPart:
459 case kControlPageDownPart:
460 TrackControl(control, mouse, &mac_scrolltracker_upp);
464 text_click(s, event);
468 static void text_click(Session *s, EventRecord *event) {
471 static UInt32 lastwhen = 0;
472 static Session *lastsess = NULL;
473 static int lastrow = -1, lastcol = -1;
474 static Mouse_Action lastact = MA_NOTHING;
477 localwhere = event->where;
478 GlobalToLocal(&localwhere);
480 col = PTOCC(localwhere.h);
481 row = PTOCR(localwhere.v);
482 if (event->when - lastwhen < GetDblTime() &&
483 row == lastrow && col == lastcol && s == lastsess)
484 lastact = (lastact == MA_CLICK ? MA_2CLK :
485 lastact == MA_2CLK ? MA_3CLK :
486 lastact == MA_3CLK ? MA_CLICK : MA_NOTHING);
489 /* Fake right button with shift key */
490 term_mouse(s->term, event->modifiers & shiftKey ? MBT_RIGHT : MBT_LEFT,
491 lastact, col, row, event->modifiers & shiftKey,
492 event->modifiers & controlKey, event->modifiers & optionKey);
496 while (StillDown()) {
497 GetMouse(&localwhere);
498 col = PTOCC(localwhere.h);
499 row = PTOCR(localwhere.v);
501 event->modifiers & shiftKey ? MBT_RIGHT : MBT_LEFT,
502 MA_DRAG, col, row, event->modifiers & shiftKey,
503 event->modifiers & controlKey,
504 event->modifiers & optionKey);
505 if (row > s->term->rows - 1)
506 term_scroll(s->term, 0, row - (s->term->rows - 1));
508 term_scroll(s->term, 0, row);
510 term_mouse(s->term, event->modifiers & shiftKey ? MBT_RIGHT : MBT_LEFT,
511 MA_RELEASE, col, row, event->modifiers & shiftKey,
512 event->modifiers & controlKey, event->modifiers & optionKey);
513 lastwhen = TickCount();
516 Mouse_Button translate_button(void *frontend, Mouse_Button button)
529 void write_clip(void *cookie, wchar_t *data, int len, int must_deselect) {
532 * See "Programming with the Text Encoding Conversion Manager"
533 * Appendix E for Unicode scrap conventions.
535 * XXX Need to support TEXT/styl scrap as well.
536 * See STScrpRec in TextEdit (Inside Macintosh: Text) for styl details.
537 * XXX Maybe PICT scrap too.
539 if (ZeroScrap() != noErr)
541 PutScrap(len * sizeof(*data), 'utxt', data);
544 void get_clip(void *frontend, wchar_t **p, int *lenp) {
545 Session *s = frontend;
546 static Handle h = NULL;
555 /* XXX Support TEXT-format scrap as well. */
556 if (GetScrap(NULL, 'utxt', &offset) > 0) {
558 *lenp = GetScrap(h, 'utxt', &offset) / sizeof(**p);
561 if (*p == NULL || *lenp <= 0)
562 fatalbox("Empty scrap");
569 static pascal void mac_scrolltracker(ControlHandle control, short part) {
572 s = (Session *)GetWRefCon((*control)->contrlOwner);
574 case kControlUpButtonPart:
575 term_scroll(s->term, 0, -1);
577 case kControlDownButtonPart:
578 term_scroll(s->term, 0, +1);
580 case kControlPageUpPart:
581 term_scroll(s->term, 0, -(s->term->rows - 1));
583 case kControlPageDownPart:
584 term_scroll(s->term, 0, +(s->term->rows - 1));
605 #define K_INSERT 0x7200
606 #define K_HOME 0x7300
607 #define K_PRIOR 0x7400
608 #define K_DELETE 0x7500
610 #define K_NEXT 0x7900
611 #define K_LEFT 0x7b00
612 #define K_RIGHT 0x7c00
613 #define K_DOWN 0x7d00
625 #define KP_CLEAR 0x4700
626 #define KP_EQUAL 0x5100
627 #define KP_SLASH 0x4b00
628 #define KP_STAR 0x4300
629 #define KP_PLUS 0x4500
630 #define KP_MINUS 0x4e00
631 #define KP_DOT 0x4100
632 #define KP_ENTER 0x4c00
634 void mac_keyterm(WindowPtr window, EventRecord *event) {
635 unsigned char buf[20];
639 s = (Session *)GetWRefCon(window);
640 len = mac_keytrans(s, event, buf);
641 ldisc_send(s->ldisc, (char *)buf, len, 1);
643 term_seen_key_event(s->term);
645 term_update(s->term);
648 static int mac_keytrans(Session *s, EventRecord *event,
649 unsigned char *output) {
650 unsigned char *p = output;
653 /* No meta key yet -- that'll be rather fun. */
655 /* Keys that we handle locally */
656 if (event->modifiers & shiftKey) {
657 switch (event->message & keyCodeMask) {
658 case K_PRIOR: /* shift-pageup */
659 term_scroll(s->term, 0, -(s->term->rows - 1));
661 case K_NEXT: /* shift-pagedown */
662 term_scroll(s->term, 0, +(s->term->rows - 1));
668 * Control-2 should return ^@ (0x00), Control-6 should return
669 * ^^ (0x1E), and Control-Minus should return ^_ (0x1F). Since
670 * the DOS keyboard handling did it, and we have nothing better
671 * to do with the key combo in question, we'll also map
672 * Control-Backquote to ^\ (0x1C).
675 if (event->modifiers & controlKey) {
676 switch (event->message & charCodeMask) {
693 * First, all the keys that do tilde codes. (ESC '[' nn '~',
694 * for integer decimal nn.)
696 * We also deal with the weird ones here. Linux VCs replace F1
697 * to F5 by ESC [ [ A to ESC [ [ E. rxvt doesn't do _that_, but
698 * does replace Home and End (1~ and 4~) by ESC [ H and ESC O w
702 switch (event->message & keyCodeMask) {
703 case K_F1: code = (event->modifiers & shiftKey ? 23 : 11); break;
704 case K_F2: code = (event->modifiers & shiftKey ? 24 : 12); break;
705 case K_F3: code = (event->modifiers & shiftKey ? 25 : 13); break;
706 case K_F4: code = (event->modifiers & shiftKey ? 26 : 14); break;
707 case K_F5: code = (event->modifiers & shiftKey ? 28 : 15); break;
708 case K_F6: code = (event->modifiers & shiftKey ? 29 : 17); break;
709 case K_F7: code = (event->modifiers & shiftKey ? 31 : 18); break;
710 case K_F8: code = (event->modifiers & shiftKey ? 32 : 19); break;
711 case K_F9: code = (event->modifiers & shiftKey ? 33 : 20); break;
712 case K_F10: code = (event->modifiers & shiftKey ? 34 : 21); break;
713 case K_F11: code = 23; break;
714 case K_F12: code = 24; break;
715 case K_HOME: code = 1; break;
716 case K_INSERT: code = 2; break;
717 case K_DELETE: code = 3; break;
718 case K_END: code = 4; break;
719 case K_PRIOR: code = 5; break;
720 case K_NEXT: code = 6; break;
722 if (s->cfg.funky_type == 1 && code >= 11 && code <= 15) {
723 p += sprintf((char *)p, "\x1B[[%c", code + 'A' - 11);
726 if (s->cfg.rxvt_homeend && (code == 1 || code == 4)) {
727 p += sprintf((char *)p, code == 1 ? "\x1B[H" : "\x1BOw");
731 p += sprintf((char *)p, "\x1B[%d~", code);
735 if (s->term->app_keypad_keys) {
736 switch (event->message & keyCodeMask) {
737 case KP_ENTER: p += sprintf((char *)p, "\x1BOM"); return p - output;
738 case KP_CLEAR: p += sprintf((char *)p, "\x1BOP"); return p - output;
739 case KP_EQUAL: p += sprintf((char *)p, "\x1BOQ"); return p - output;
740 case KP_SLASH: p += sprintf((char *)p, "\x1BOR"); return p - output;
741 case KP_STAR: p += sprintf((char *)p, "\x1BOS"); return p - output;
742 case KP_PLUS: p += sprintf((char *)p, "\x1BOl"); return p - output;
743 case KP_MINUS: p += sprintf((char *)p, "\x1BOm"); return p - output;
744 case KP_DOT: p += sprintf((char *)p, "\x1BOn"); return p - output;
745 case KP_0: p += sprintf((char *)p, "\x1BOp"); return p - output;
746 case KP_1: p += sprintf((char *)p, "\x1BOq"); return p - output;
747 case KP_2: p += sprintf((char *)p, "\x1BOr"); return p - output;
748 case KP_3: p += sprintf((char *)p, "\x1BOs"); return p - output;
749 case KP_4: p += sprintf((char *)p, "\x1BOt"); return p - output;
750 case KP_5: p += sprintf((char *)p, "\x1BOu"); return p - output;
751 case KP_6: p += sprintf((char *)p, "\x1BOv"); return p - output;
752 case KP_7: p += sprintf((char *)p, "\x1BOw"); return p - output;
753 case KP_8: p += sprintf((char *)p, "\x1BOx"); return p - output;
754 case KP_9: p += sprintf((char *)p, "\x1BOy"); return p - output;
758 switch (event->message & keyCodeMask) {
760 p += sprintf((char *)p,
761 s->term->app_cursor_keys ? "\x1BOA" : "\x1B[A");
764 p += sprintf((char *)p,
765 s->term->app_cursor_keys ? "\x1BOB" : "\x1B[B");
768 p += sprintf((char *)p,
769 s->term->app_cursor_keys ? "\x1BOC" : "\x1B[C");
772 p += sprintf((char *)p,
773 s->term->app_cursor_keys ? "\x1BOD" : "\x1B[D");
779 *p++ = (s->cfg.bksp_is_delete ? 0x7f : 0x08);
782 *p++ = event->message & charCodeMask;
787 void request_paste(void *frontend)
789 Session *s = frontend;
792 * In the Mac OS, pasting is synchronous: we can read the
793 * clipboard with no difficulty, so request_paste() can just go
796 term_do_paste(s->term);
807 void mac_growterm(WindowPtr window, EventRecord *event) {
810 int newrows, newcols;
812 DragGrayRgnUPP draghooksave;
816 s = (Session *)GetWRefCon(window);
818 draghooksave = LMGetDragHook();
819 growterm_state.oldmsg[0] = '\0';
820 growterm_state.zeromouse = event->where;
821 growterm_state.zeromouse.h -= s->term->cols * s->font_width;
822 growterm_state.zeromouse.v -= s->term->rows * s->font_height;
823 growterm_state.s = s;
826 BackColor(whiteColor);
827 ForeColor(blackColor);
828 TextFont(systemFont);
832 SetRect(&growterm_state.msgrect, 0, 0,
833 StringWidth("\p99999x99999") + 4, fi.ascent + fi.descent + 4);
834 SetPt(&growterm_state.msgorigin, 2, fi.ascent + 2);
835 LMSetDragHook(NewDragGrayRgnUPP(mac_growtermdraghook));
837 SetRect(&limits, s->font_width + 15, s->font_height, SHRT_MAX, SHRT_MAX);
838 grow_result = GrowWindow(window, event->where, &limits);
840 DisposeDragGrayRgnUPP(LMGetDragHook());
841 LMSetDragHook(draghooksave);
842 InvalRect(&growterm_state.msgrect);
846 if (grow_result != 0) {
847 newrows = HiWord(grow_result) / s->font_height;
848 newcols = (LoWord(grow_result) - 15) / s->font_width;
849 mac_adjustsize(s, newrows, newcols);
850 term_size(s->term, newrows, newcols, s->cfg.savelines);
854 static pascal void mac_growtermdraghook(void)
856 Session *s = growterm_state.s;
860 unsigned char pbuf[20];
861 int newrows, newcols;
864 newrows = (mouse.v - growterm_state.zeromouse.v) / s->font_height;
865 if (newrows < 1) newrows = 1;
866 newcols = (mouse.h - growterm_state.zeromouse.h) / s->font_width;
867 if (newcols < 1) newcols = 1;
868 sprintf(buf, "%dx%d", newcols, newrows);
869 if (strcmp(buf, growterm_state.oldmsg) == 0)
871 strcpy(growterm_state.oldmsg, buf);
872 c2pstrcpy(pbuf, buf);
875 SetPort(growterm_state.s->window);
876 EraseRect(&growterm_state.msgrect);
877 MoveTo(growterm_state.msgorigin.h, growterm_state.msgorigin.v);
882 void mac_closeterm(WindowPtr window)
884 Session *s = (Session *)GetWRefCon(window);
886 /* XXX warn on close */
887 HideWindow(s->window);
889 s->next->prev = s->prev;
890 ldisc_free(s->ldisc);
891 s->back->free(s->backhandle);
893 if (s->uni_to_font != NULL)
894 DisposeUnicodeToTextInfo(&s->uni_to_font);
896 DisposeWindow(s->window);
897 DisposePalette(s->palette);
901 void mac_activateterm(WindowPtr window, Boolean active) {
904 s = (Session *)GetWRefCon(window);
905 s->term->has_focus = active;
906 term_update(s->term);
908 ShowControl(s->scrollbar);
911 PmBackColor(DEFAULT_BG);/* HideControl clears behind the control */
913 BackColor(blackColor);
914 HideControl(s->scrollbar);
919 void mac_updateterm(WindowPtr window) {
922 s = (Session *)GetWRefCon(window);
926 term_paint(s->term, s,
927 PTOCC((*window->visRgn)->rgnBBox.left),
928 PTOCR((*window->visRgn)->rgnBBox.top),
929 PTOCC((*window->visRgn)->rgnBBox.right),
930 PTOCR((*window->visRgn)->rgnBBox.bottom), 1);
931 /* Restore default colours in case the Window Manager uses them */
932 if (HAVE_COLOR_QD()) {
933 PmForeColor(DEFAULT_FG);
934 PmBackColor(DEFAULT_BG);
936 ForeColor(whiteColor);
937 BackColor(blackColor);
939 if (FrontWindow() != window)
940 EraseRect(&(*s->scrollbar)->contrlRect);
941 UpdateControls(window, window->visRgn);
947 static void mac_drawgrowicon(Session *s) {
953 * Stop DrawGrowIcon giving us space for a horizontal scrollbar
954 * See Tech Note TB575 for details.
956 clip = s->window->portRect;
957 clip.left = clip.right - 15;
961 DrawGrowIcon(s->window);
966 struct do_text_args {
977 * Call from the terminal emulator to draw a bit of text
979 * x and y are text row and column (zero-based)
981 void do_text(Context ctx, int x, int y, char *text, int len,
982 unsigned long attr, int lattr) {
985 struct do_text_args a;
986 RgnHandle textrgn, saveclip;
987 char mactextbuf[1024];
988 UniChar unitextbuf[1024];
991 ByteCount iread, olen;
998 fontwidth = s->font_width;
999 if ((lattr & LATTR_MODE) != LATTR_NORM)
1002 /* First check this text is relevant */
1003 a.textrect.top = y * s->font_height;
1004 a.textrect.bottom = (y + 1) * s->font_height;
1005 a.textrect.left = x * fontwidth;
1006 a.textrect.right = (x + len) * fontwidth;
1007 if (a.textrect.right > s->term->cols * s->font_width)
1008 a.textrect.right = s->term->cols * s->font_width;
1009 if (!RectInRgn(&a.textrect, s->window->visRgn))
1012 /* Unpack Unicode from the mad format we get passed */
1013 for (i = 0; i < len; i++)
1014 unitextbuf[i] = (unsigned char)text[i] | (attr & CSET_MASK);
1016 if (s->uni_to_font != NULL) {
1017 err = ConvertFromUnicodeToText(s->uni_to_font, len * sizeof(UniChar),
1018 unitextbuf, kUnicodeUseFallbacksMask,
1019 0, NULL, NULL, NULL,
1020 1024, &iread, &olen, mactextbuf);
1021 if (err != noErr && err != kTECUsedFallbacksStatus)
1023 } else if (s->font_charset != CS_NONE) {
1024 /* XXX this is bogus if wchar_t and UniChar are different sizes. */
1025 unitextptr = (wchar_t *)unitextbuf;
1026 olen = charset_from_unicode(&unitextptr, &len, mactextbuf, 1024,
1027 s->font_charset, NULL, ".", 1);
1032 a.text = mactextbuf;
1036 switch (lattr & LATTR_MODE) {
1038 TextSize(s->cfg.fontheight);
1039 a.numer = s->font_stdnumer;
1040 a.denom = s->font_stddenom;
1043 TextSize(s->cfg.fontheight);
1044 a.numer = s->font_widenumer;
1045 a.denom = s->font_widedenom;
1049 TextSize(s->cfg.fontheight * 2);
1050 a.numer = s->font_bignumer;
1051 a.denom = s->font_bigdenom;
1055 TextFont(s->fontnum);
1056 if (s->cfg.fontisbold || (attr & ATTR_BOLD) && !s->cfg.bold_colour)
1058 if (attr & ATTR_UNDER)
1062 if (HAVE_COLOR_QD())
1064 SpaceExtra(s->font_boldadjust << 16);
1065 CharExtra(s->font_boldadjust << 16);
1070 saveclip = NewRgn();
1072 ClipRect(&a.textrect);
1074 RectRgn(textrgn, &a.textrect);
1075 if (HAVE_COLOR_QD())
1076 DeviceLoop(textrgn, &do_text_for_device_upp, (long)&a, 0);
1078 do_text_for_device(1, 0, NULL, (long)&a);
1080 DisposeRgn(saveclip);
1081 DisposeRgn(textrgn);
1082 /* Tell the window manager about it in case this isn't an update */
1083 ValidRect(&a.textrect);
1086 static pascal void do_text_for_device(short depth, short devflags,
1087 GDHandle device, long cookie) {
1088 struct do_text_args *a;
1089 int bgcolour, fgcolour, bright, reverse, tmp;
1091 a = (struct do_text_args *)cookie;
1093 bright = (a->attr & ATTR_BOLD) && a->s->cfg.bold_colour;
1094 reverse = a->attr & ATTR_REVERSE;
1096 if (depth == 1 && (a->attr & TATTR_ACTCURS))
1099 if (HAVE_COLOR_QD()) {
1101 fgcolour = ((a->attr & ATTR_FGMASK) >> ATTR_FGSHIFT) * 2;
1102 bgcolour = ((a->attr & ATTR_BGMASK) >> ATTR_BGSHIFT) * 2;
1105 * NB: bold reverse in 2bpp breaks with the usual PuTTY model and
1106 * boldens the background, because that's all we can do.
1108 fgcolour = bright ? DEFAULT_FG_BOLD : DEFAULT_FG;
1109 bgcolour = DEFAULT_BG;
1113 fgcolour = bgcolour;
1116 if (bright && depth > 2)
1118 if ((a->attr & TATTR_ACTCURS) && depth > 1) {
1119 fgcolour = CURSOR_FG;
1120 bgcolour = CURSOR_BG;
1122 PmForeColor(fgcolour);
1123 PmBackColor(bgcolour);
1124 } else { /* No Color Quickdraw */
1125 /* XXX This should be done with a _little_ more configurability */
1127 ForeColor(blackColor);
1128 BackColor(whiteColor);
1130 ForeColor(whiteColor);
1131 BackColor(blackColor);
1135 EraseRect(&a->textrect);
1136 switch (a->lattr & LATTR_MODE) {
1139 MoveTo(a->textrect.left, a->textrect.top + a->s->font_ascent);
1142 MoveTo(a->textrect.left, a->textrect.top + a->s->font_ascent * 2);
1145 MoveTo(a->textrect.left,
1146 a->textrect.top - a->s->font_height + a->s->font_ascent * 2);
1149 /* FIXME: Sort out bold width adjustments on Original QuickDraw. */
1150 if (a->s->window->grafProcs != NULL)
1151 InvokeQDTextUPP(a->len, a->text, a->numer, a->denom,
1152 a->s->window->grafProcs->textProc);
1154 StdText(a->len, a->text, a->numer, a->denom);
1156 if (a->attr & TATTR_PASCURS) {
1163 PmForeColor(CURSOR_BG);
1166 FrameRect(&a->textrect);
1170 void do_cursor(Context ctx, int x, int y, char *text, int len,
1171 unsigned long attr, int lattr)
1174 do_text(ctx, x, y, text, len, attr, lattr);
1178 * Call from the terminal emulator to get its graphics context.
1179 * Should probably be called start_redraw or something.
1181 void pre_paint(Session *s) {
1183 Rect myrect, tmprect;
1185 if (HAVE_COLOR_QD()) {
1186 s->term->attr_mask = 0;
1188 myrect = (*s->window->visRgn)->rgnBBox;
1189 LocalToGlobal((Point *)&myrect.top);
1190 LocalToGlobal((Point *)&myrect.bottom);
1191 for (gdh = GetDeviceList();
1193 gdh = GetNextDevice(gdh)) {
1194 if (TestDeviceAttribute(gdh, screenDevice) &&
1195 TestDeviceAttribute(gdh, screenActive) &&
1196 SectRect(&(*gdh)->gdRect, &myrect, &tmprect)) {
1197 switch ((*(*gdh)->gdPMap)->pixelSize) {
1199 if (s->cfg.bold_colour)
1200 s->term->attr_mask |= ~(ATTR_COLOURS |
1201 (s->cfg.bold_colour ? ATTR_BOLD : 0));
1204 s->term->attr_mask |= ~ATTR_COLOURS;
1207 s->term->attr_mask = ~0;
1208 return; /* No point checking more screens. */
1213 s->term->attr_mask = ~(ATTR_COLOURS |
1214 (s->cfg.bold_colour ? ATTR_BOLD : 0));
1217 Context get_ctx(void *frontend) {
1218 Session *s = frontend;
1224 void free_ctx(Context ctx) {
1229 * Presumably this does something in Windows
1231 void post_paint(Session *s) {
1236 * Set the scroll bar position
1238 * total is the line number of the bottom of the working screen
1239 * start is the line number of the top of the display
1240 * page is the length of the displayed page
1242 void set_sbar(void *frontend, int total, int start, int page) {
1243 Session *s = frontend;
1245 /* We don't redraw until we've set everything up, to avoid glitches */
1246 (*s->scrollbar)->contrlMin = 0;
1247 (*s->scrollbar)->contrlMax = total - page;
1248 SetControlValue(s->scrollbar, start);
1250 if (mac_gestalts.cntlattr & gestaltControlMgrPresent)
1251 SetControlViewSize(s->scrollbar, page);
1255 void sys_cursor(void *frontend, int x, int y)
1258 * I think his is meaningless under Mac OS.
1263 * This is still called when mode==BELL_VISUAL, even though the
1264 * visual bell is handled entirely within terminal.c, because we
1265 * may want to perform additional actions on any kind of bell (for
1266 * example, taskbar flashing in Windows).
1268 void beep(void *frontend, int mode)
1270 if (mode != BELL_VISUAL)
1273 * XXX We should indicate the relevant window and/or use the
1274 * Notification Manager
1278 int char_width(Context ctx, int uc)
1281 * Until we support exciting character-set stuff, assume all chars are
1288 * Set icon string -- a no-op here (Windowshade?)
1290 void set_icon(void *frontend, char *icon) {
1291 Session *s = frontend;
1296 * Set the window title
1298 void set_title(void *frontend, char *title) {
1299 Session *s = frontend;
1302 c2pstrcpy(mactitle, title);
1303 SetWTitle(s->window, mactitle);
1307 * set or clear the "raw mouse message" mode
1309 void set_raw_mouse_mode(void *frontend, int activate)
1311 Session *s = frontend;
1313 s->raw_mouse = activate;
1314 /* FIXME: Should call mac_updatetermcursor as appropriate. */
1318 * Resize the window at the emulator's request
1320 void request_resize(void *frontend, int w, int h) {
1321 Session *s = frontend;
1323 term_size(s->term, h, w, s->cfg.savelines);
1328 * Iconify (actually collapse) the window at the emulator's request.
1330 void set_iconic(void *frontend, int iconic)
1332 Session *s = frontend;
1335 if (mac_gestalts.apprvers >= 0x0100 &&
1336 GetWindowFeatures(s->window, &features) == noErr &&
1337 (features & kWindowCanCollapse))
1338 CollapseWindow(s->window, iconic);
1342 * Move the window in response to a server-side request.
1344 void move_window(void *frontend, int x, int y)
1346 Session *s = frontend;
1348 MoveWindow(s->window, x, y, FALSE);
1352 * Move the window to the top or bottom of the z-order in response
1353 * to a server-side request.
1355 void set_zorder(void *frontend, int top)
1357 Session *s = frontend;
1360 * We also change the input focus to point to the topmost window,
1361 * since that's probably what the Human Interface Guidelines would
1365 SelectWindow(s->window);
1367 SendBehind(s->window, NULL);
1371 * Refresh the window in response to a server-side request.
1373 void refresh_window(void *frontend)
1375 Session *s = frontend;
1377 term_invalidate(s->term);
1381 * Maximise or restore the window in response to a server-side
1384 void set_zoomed(void *frontend, int zoomed)
1386 Session *s = frontend;
1388 ZoomWindow(s->window, zoomed ? inZoomOut : inZoomIn, FALSE);
1392 * Report whether the window is iconic, for terminal reports.
1394 int is_iconic(void *frontend)
1396 Session *s = frontend;
1399 if (mac_gestalts.apprvers >= 0x0100 &&
1400 GetWindowFeatures(s->window, &features) == noErr &&
1401 (features & kWindowCanCollapse))
1402 return IsWindowCollapsed(s->window);
1407 * Report the window's position, for terminal reports.
1409 void get_window_pos(void *frontend, int *x, int *y)
1411 Session *s = frontend;
1413 *x = s->window->portRect.left;
1414 *y = s->window->portRect.top;
1418 * Report the window's pixel size, for terminal reports.
1420 void get_window_pixels(void *frontend, int *x, int *y)
1422 Session *s = frontend;
1424 *x = s->window->portRect.right - s->window->portRect.left;
1425 *y = s->window->portRect.bottom - s->window->portRect.top;
1429 * Return the window or icon title.
1431 char *get_window_title(void *frontend, int icon)
1433 Session *s = frontend;
1435 static char title[256];
1437 GetWTitle(s->window, ptitle);
1438 p2cstrcpy(title, ptitle);
1443 * real_palette_set(): This does the actual palette-changing work on behalf
1444 * of palette_set(). Does _not_ call ActivatePalette() in case the caller
1445 * is doing a batch of updates.
1447 static void real_palette_set(Session *s, int n, int r, int g, int b)
1451 if (!HAVE_COLOR_QD())
1453 col.red = r * 0x0101;
1454 col.green = g * 0x0101;
1455 col.blue = b * 0x0101;
1456 SetEntryColor(s->palette, n, &col);
1460 * Set the logical palette. Called by the terminal emulator.
1462 void palette_set(void *frontend, int n, int r, int g, int b) {
1463 Session *s = frontend;
1464 static const int first[21] = {
1465 0, 2, 4, 6, 8, 10, 12, 14,
1466 1, 3, 5, 7, 9, 11, 13, 15,
1470 if (!HAVE_COLOR_QD())
1472 real_palette_set(s, first[n], r, g, b);
1474 real_palette_set(s, first[n]+1, r, g, b);
1475 if (first[n] == DEFAULT_BG)
1477 ActivatePalette(s->window);
1481 * Reset to the default palette
1483 void palette_reset(void *frontend) {
1484 Session *s = frontend;
1485 /* This maps colour indices in cfg to those used in our palette. */
1486 static const int ww[] = {
1487 6, 7, 8, 9, 10, 11, 12, 13,
1488 14, 15, 16, 17, 18, 19, 20, 21,
1493 if (!HAVE_COLOR_QD())
1496 assert(lenof(ww) == NCOLOURS);
1498 for (i = 0; i < NCOLOURS; i++) {
1499 real_palette_set(s, i,
1500 s->cfg.colours[ww[i]][0],
1501 s->cfg.colours[ww[i]][1],
1502 s->cfg.colours[ww[i]][2]);
1505 ActivatePalette(s->window);
1506 /* Palette Manager will generate update events as required. */
1510 * Scroll the screen. (`lines' is +ve for scrolling forward, -ve
1513 void do_scroll(void *frontend, int topline, int botline, int lines) {
1514 Session *s = frontend;
1516 RgnHandle scrollrgn = NewRgn();
1517 RgnHandle movedupdate = NewRgn();
1518 RgnHandle update = NewRgn();
1519 Point g2l = { 0, 0 };
1524 * Work out the part of the update region that will scrolled by
1528 SetRectRgn(scrollrgn, 0, (topline + lines) * s->font_height,
1529 s->term->cols * s->font_width,
1530 (botline + 1) * s->font_height);
1532 SetRectRgn(scrollrgn, 0, topline * s->font_height,
1533 s->term->cols * s->font_width,
1534 (botline - lines + 1) * s->font_height);
1535 CopyRgn(((WindowPeek)s->window)->updateRgn, movedupdate);
1536 GlobalToLocal(&g2l);
1537 OffsetRgn(movedupdate, g2l.h, g2l.v); /* Convert to local co-ords. */
1538 SectRgn(scrollrgn, movedupdate, movedupdate); /* Clip scrolled section. */
1539 ValidRgn(movedupdate);
1540 OffsetRgn(movedupdate, 0, -lines * s->font_height); /* Scroll it. */
1543 if (HAVE_COLOR_QD())
1544 PmBackColor(DEFAULT_BG);
1546 BackColor(blackColor); /* XXX make configurable */
1547 SetRect(&r, 0, topline * s->font_height,
1548 s->term->cols * s->font_width, (botline + 1) * s->font_height);
1549 ScrollRect(&r, 0, - lines * s->font_height, update);
1552 InvalRgn(movedupdate);
1554 DisposeRgn(scrollrgn);
1555 DisposeRgn(movedupdate);
1559 void logevent(void *frontend, char *str) {
1561 fprintf(stderr, "%s\n", str);
1564 /* Dummy routine, only required in plink. */
1565 void ldisc_update(void *frontend, int echo, int edit)
1570 * Mac PuTTY doesn't support printing yet.
1572 printer_job *printer_start_job(char *printer)
1578 void printer_job_data(printer_job *pj, void *data, int len)
1582 void printer_finish_job(printer_job *pj)
1586 void frontend_keypress(void *handle)
1589 * Keypress termination in non-Close-On-Exit mode is not
1590 * currently supported in PuTTY proper, because the window
1591 * always has a perfectly good Close button anyway. So we do
1598 * Ask whether to wipe a session log file before writing to it.
1599 * Returns 2 for wipe, 1 for append, 0 for cancel (don't log).
1601 int askappend(void *frontend, char *filename)
1604 /* FIXME: not implemented yet. */
1611 * c-file-style: "simon"