1 /* $Id: macterm.c,v 1.37 2003/01/09 22:45:48 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>
39 #include <MacMemory.h>
40 #include <MacWindows.h>
41 #include <MixedMode.h>
43 #include <Quickdraw.h>
44 #include <QuickdrawText.h>
45 #include <Resources.h>
49 #include <StandardFile.h>
50 #include <TextCommon.h>
52 #include <ToolUtils.h>
53 #include <UnicodeConverter.h>
68 #define NCOLOURS (lenof(((Config *)0)->colours))
71 #define DEFAULT_FG_BOLD 17
73 #define DEFAULT_BG_BOLD 19
77 #define PTOCC(x) ((x) < 0 ? -(-(x - s->font_width - 1) / s->font_width) : \
79 #define PTOCR(y) ((y) < 0 ? -(-(y - s->font_height - 1) / s->font_height) : \
82 static void mac_initfont(Session *);
83 static pascal OSStatus uni_to_font_fallback(UniChar *, ByteCount, ByteCount *,
84 TextPtr, ByteCount, ByteCount *,
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 *);
97 void pre_paint(Session *s);
98 void post_paint(Session *s);
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 */
112 static void inbuf_putc(Session *s, int c) {
115 from_backend(s->term, 0, &ch, 1);
118 static void inbuf_putstr(Session *s, const char *c) {
120 from_backend(s->term, 0, (char *)c, strlen(c));
123 static void display_resource(Session *s, unsigned long type, short id) {
128 h = GetResource(type, id);
130 fatalbox("Can't get test resource");
131 len = GetResourceSizeOnDisk(h);
136 from_backend(s->term, 0, t, len);
141 void mac_opensession(void) {
143 StandardFileReply sfr;
144 static const OSType sftypes[] = { 'Sess', 0, 0, 0 };
148 s = smalloc(sizeof(*s));
149 memset(s, 0, sizeof(*s));
151 StandardGetFile(NULL, 1, sftypes, &sfr);
152 if (!sfr.sfGood) goto fail;
154 sesshandle = open_settings_r_fsp(&sfr.sfFile);
155 if (sesshandle == NULL) goto fail;
156 load_open_settings(sesshandle, TRUE, &s->cfg);
157 close_settings_r(sesshandle);
160 * Select protocol. This is farmed out into a table in a
161 * separate file to enable an ssh-free variant.
164 for (i = 0; backends[i].backend != NULL; i++)
165 if (backends[i].protocol == s->cfg.protocol) {
166 s->back = backends[i].backend;
169 if (s->back == NULL) {
170 fatalbox("Unsupported protocol number found");
180 void mac_startsession(Session *s)
186 /* XXX: Own storage management? */
188 s->window = GetNewCWindow(wTerminal, NULL, (WindowPtr)-1);
190 s->window = GetNewWindow(wTerminal, NULL, (WindowPtr)-1);
191 SetWRefCon(s->window, (long)s);
192 s->scrollbar = GetNewControl(cVScroll, s->window);
193 s->term = term_init(&s->cfg, s);
197 if (HAVE_COLOR_QD()) {
198 /* Set to FALSE to not get palette updates in the background. */
199 SetPalette(s->window, s->palette, TRUE);
200 ActivatePalette(s->window);
203 s->logctx = log_init(s);
204 term_provide_logctx(s->term, s->logctx);
206 errmsg = s->back->init(s->term, &s->backhandle, s->cfg.host, s->cfg.port,
207 &s->realhost, s->cfg.tcp_nodelay);
209 inbuf_putstr(s, errmsg);
210 s->back->provide_logctx(s->backhandle, s->logctx);
212 term_provide_resize_fn(s->term, s->back->size, s->backhandle);
214 mac_adjustsize(s, s->cfg.height, s->cfg.width);
215 term_size(s->term, s->cfg.height, s->cfg.width, s->cfg.savelines);
217 s->ldisc = ldisc_create(&s->cfg, s->term, s->back, s->backhandle, s);
218 ldisc_send(s->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
220 ShowWindow(s->window);
221 starttime = TickCount();
222 display_resource(s, 'pTST', 128);
223 sprintf(msg, "Elapsed ticks: %d\015\012", TickCount() - starttime);
224 inbuf_putstr(s, msg);
227 s->prev = s->next->prev;
228 s->next->prev = &s->next;
232 static UnicodeToTextFallbackUPP uni_to_font_fallback_upp;
234 static void mac_initfont(Session *s) {
241 macfont[0] = sprintf((char *)&macfont[1], "%s", s->cfg.font);
242 GetFNum(macfont, &s->fontnum);
243 TextFont(s->fontnum);
244 TextFace(s->cfg.fontisbold ? bold : 0);
245 TextSize(s->cfg.fontheight);
247 s->font_width = CharWidth('W'); /* Well, it's what NCSA uses. */
248 s->font_ascent = fi.ascent;
249 s->font_leading = fi.leading;
250 s->font_height = s->font_ascent + fi.descent + s->font_leading;
251 if (!s->cfg.bold_colour) {
253 s->font_boldadjust = s->font_width - CharWidth('W');
255 s->font_boldadjust = 0;
257 if (s->uni_to_font != NULL)
258 DisposeUnicodeToTextInfo(&s->uni_to_font);
259 if (mac_gestalts.encvvers != 0 &&
260 UpgradeScriptInfoToTextEncoding(kTextScriptDontCare,
261 kTextLanguageDontCare,
262 kTextRegionDontCare, macfont,
264 CreateUnicodeToTextInfoByEncoding(enc, &s->uni_to_font) == noErr) {
265 if (uni_to_font_fallback_upp == NULL)
266 uni_to_font_fallback_upp =
267 NewUnicodeToTextFallbackProc(&uni_to_font_fallback);
268 fbflags = kUnicodeFallbackCustomOnly;
269 if (mac_gestalts.uncvattr & kTECAddFallbackInterruptMask)
270 fbflags |= kUnicodeFallbackInterruptSafeMask;
271 if (SetFallbackUnicodeToText(s->uni_to_font,
272 uni_to_font_fallback_upp, fbflags, NULL) != noErr) {
273 DisposeUnicodeToTextInfo(&s->uni_to_font);
278 s->uni_to_font = NULL;
280 charset_from_macenc(FontToScript(s->fontnum),
281 GetScriptManagerVariable(smRegionCode),
282 mac_gestalts.sysvers, s->cfg.font);
285 mac_adjustsize(s, s->term->rows, s->term->cols);
288 static pascal OSStatus uni_to_font_fallback(UniChar *ucp,
289 ByteCount ilen, ByteCount *iusedp, TextPtr obuf, ByteCount olen,
290 ByteCount *ousedp, LogicalAddress *cookie, ConstUnicodeMappingPtr mapping)
294 return kTECOutputBufferFullStatus;
296 * What I'd _like_ to do here is to somehow generate the
297 * missing-character glyph that every font is required to have.
298 * Unfortunately (and somewhat surprisingly), I can't find any way
299 * to actually ask for it explicitly. Bah.
308 * Called every time round the event loop.
310 void mac_pollterm(void)
314 for (s = sesslist; s != NULL; s = s->next) {
316 term_update(s->term);
321 * To be called whenever the window size changes.
322 * rows and cols should be desired values.
323 * It's assumed the terminal emulator will be informed, and will set rows
326 static void mac_adjustsize(Session *s, int newrows, int newcols) {
327 int winwidth, winheight;
329 winwidth = newcols * s->font_width + 15;
330 winheight = newrows * s->font_height;
331 SizeWindow(s->window, winwidth, winheight, true);
332 HideControl(s->scrollbar);
333 MoveControl(s->scrollbar, winwidth - 15, -1);
334 SizeControl(s->scrollbar, 16, winheight - 13);
335 ShowControl(s->scrollbar);
339 static void mac_initpalette(Session *s) {
341 if (!HAVE_COLOR_QD())
344 * Most colours should be inhibited on 2bpp displays.
345 * Palette manager documentation suggests inhibiting all tolerant colours
346 * on greyscale displays.
348 #define PM_NORMAL ( pmTolerant | pmInhibitC2 | \
349 pmInhibitG2 | pmInhibitG4 | pmInhibitG8 )
350 #define PM_TOLERANCE 0x2000
351 s->palette = NewPalette(22, NULL, PM_NORMAL, PM_TOLERANCE);
352 if (s->palette == NULL)
353 fatalbox("Unable to create palette");
354 /* In 2bpp, these are the colours we want most. */
355 SetEntryUsage(s->palette, DEFAULT_BG,
356 PM_NORMAL &~ pmInhibitC2, PM_TOLERANCE);
357 SetEntryUsage(s->palette, DEFAULT_FG,
358 PM_NORMAL &~ pmInhibitC2, PM_TOLERANCE);
359 SetEntryUsage(s->palette, DEFAULT_FG_BOLD,
360 PM_NORMAL &~ pmInhibitC2, PM_TOLERANCE);
361 SetEntryUsage(s->palette, CURSOR_BG,
362 PM_NORMAL &~ pmInhibitC2, PM_TOLERANCE);
367 * Set the background colour of the window correctly. Should be
368 * called whenever the default background changes.
370 static void mac_adjustwinbg(Session *s) {
372 if (!HAVE_COLOR_QD())
375 if (mac_gestalts.windattr & gestaltWindowMgrPresent)
376 SetWindowContentColor(s->window,
377 &(*s->palette)->pmInfo[DEFAULT_BG].ciRGB);
381 if (s->wctab == NULL)
382 s->wctab = (WCTabHandle)NewHandle(sizeof(**s->wctab));
383 if (s->wctab == NULL)
384 return; /* do without */
385 (*s->wctab)->wCSeed = 0;
386 (*s->wctab)->wCReserved = 0;
387 (*s->wctab)->ctSize = 0;
388 (*s->wctab)->ctTable[0].value = wContentColor;
389 (*s->wctab)->ctTable[0].rgb = (*s->palette)->pmInfo[DEFAULT_BG].ciRGB;
390 SetWinColor(s->window, s->wctab);
395 * Set the cursor shape correctly
397 void mac_adjusttermcursor(WindowPtr window, Point mouse, RgnHandle cursrgn) {
399 ControlHandle control;
404 s = (Session *)GetWRefCon(window);
405 GlobalToLocal(&mouse);
406 part = FindControl(mouse, window, &control);
407 if (control == s->scrollbar) {
408 SetCursor(&qd.arrow);
409 RectRgn(cursrgn, &(*s->scrollbar)->contrlRect);
410 SectRgn(cursrgn, window->visRgn, cursrgn);
412 x = mouse.h / s->font_width;
413 y = mouse.v / s->font_height;
415 SetCursor(&qd.arrow);
417 SetCursor(*GetCursor(iBeamCursor));
418 /* Ask for shape changes if we leave this character cell. */
419 SetRectRgn(cursrgn, x * s->font_width, y * s->font_height,
420 (x + 1) * s->font_width, (y + 1) * s->font_height);
421 SectRgn(cursrgn, window->visRgn, cursrgn);
426 * Enable/disable menu items based on the active terminal window.
428 void mac_adjusttermmenus(WindowPtr window) {
433 s = (Session *)GetWRefCon(window);
434 menu = GetMenuHandle(mEdit);
436 DisableItem(menu, iUndo);
437 DisableItem(menu, iCut);
438 if (1/*s->term->selstate == SELECTED*/)
439 EnableItem(menu, iCopy);
441 DisableItem(menu, iCopy);
442 if (GetScrap(NULL, 'TEXT', &offset) == noTypeErr)
443 DisableItem(menu, iPaste);
445 EnableItem(menu, iPaste);
446 DisableItem(menu, iClear);
447 EnableItem(menu, iSelectAll);
450 void mac_menuterm(WindowPtr window, short menu, short item) {
453 s = (Session *)GetWRefCon(window);
461 term_do_paste(s->term);
467 void mac_clickterm(WindowPtr window, EventRecord *event) {
470 ControlHandle control;
473 s = (Session *)GetWRefCon(window);
475 mouse = event->where;
476 GlobalToLocal(&mouse);
477 part = FindControl(mouse, window, &control);
478 if (control == s->scrollbar) {
480 case kControlIndicatorPart:
481 if (TrackControl(control, mouse, NULL) == kControlIndicatorPart)
482 term_scroll(s->term, +1, GetControlValue(control));
484 case kControlUpButtonPart:
485 case kControlDownButtonPart:
486 case kControlPageUpPart:
487 case kControlPageDownPart:
488 TrackControl(control, mouse, &mac_scrolltracker_upp);
492 text_click(s, event);
496 static void text_click(Session *s, EventRecord *event) {
499 static UInt32 lastwhen = 0;
500 static Session *lastsess = NULL;
501 static int lastrow = -1, lastcol = -1;
502 static Mouse_Action lastact = MA_NOTHING;
505 localwhere = event->where;
506 GlobalToLocal(&localwhere);
508 col = PTOCC(localwhere.h);
509 row = PTOCR(localwhere.v);
510 if (event->when - lastwhen < GetDblTime() &&
511 row == lastrow && col == lastcol && s == lastsess)
512 lastact = (lastact == MA_CLICK ? MA_2CLK :
513 lastact == MA_2CLK ? MA_3CLK :
514 lastact == MA_3CLK ? MA_CLICK : MA_NOTHING);
517 /* Fake right button with shift key */
518 term_mouse(s->term, event->modifiers & shiftKey ? MBT_RIGHT : MBT_LEFT,
519 lastact, col, row, event->modifiers & shiftKey,
520 event->modifiers & controlKey, event->modifiers & optionKey);
524 while (StillDown()) {
525 GetMouse(&localwhere);
526 col = PTOCC(localwhere.h);
527 row = PTOCR(localwhere.v);
529 event->modifiers & shiftKey ? MBT_RIGHT : MBT_LEFT,
530 MA_DRAG, col, row, event->modifiers & shiftKey,
531 event->modifiers & controlKey,
532 event->modifiers & optionKey);
533 if (row > s->term->rows - 1)
534 term_scroll(s->term, 0, row - (s->term->rows - 1));
536 term_scroll(s->term, 0, row);
538 term_mouse(s->term, event->modifiers & shiftKey ? MBT_RIGHT : MBT_LEFT,
539 MA_RELEASE, col, row, event->modifiers & shiftKey,
540 event->modifiers & controlKey, event->modifiers & optionKey);
541 lastwhen = TickCount();
544 Mouse_Button translate_button(void *frontend, Mouse_Button button)
557 void write_clip(void *cookie, wchar_t *data, int len, int must_deselect) {
560 * See "Programming with the Text Encoding Conversion Manager"
561 * Appendix E for Unicode scrap conventions.
563 * XXX Need to support TEXT/styl scrap as well.
564 * See STScrpRec in TextEdit (Inside Macintosh: Text) for styl details.
565 * XXX Maybe PICT scrap too.
567 if (ZeroScrap() != noErr)
569 PutScrap(len * sizeof(*data), 'utxt', data);
572 void get_clip(void *frontend, wchar_t **p, int *lenp) {
573 Session *s = frontend;
574 static Handle h = NULL;
583 /* XXX Support TEXT-format scrap as well. */
584 if (GetScrap(NULL, 'utxt', &offset) > 0) {
586 *lenp = GetScrap(h, 'utxt', &offset) / sizeof(**p);
589 if (*p == NULL || *lenp <= 0)
590 fatalbox("Empty scrap");
597 static pascal void mac_scrolltracker(ControlHandle control, short part) {
600 s = (Session *)GetWRefCon((*control)->contrlOwner);
602 case kControlUpButtonPart:
603 term_scroll(s->term, 0, -1);
605 case kControlDownButtonPart:
606 term_scroll(s->term, 0, +1);
608 case kControlPageUpPart:
609 term_scroll(s->term, 0, -(s->term->rows - 1));
611 case kControlPageDownPart:
612 term_scroll(s->term, 0, +(s->term->rows - 1));
633 #define K_INSERT 0x7200
634 #define K_HOME 0x7300
635 #define K_PRIOR 0x7400
636 #define K_DELETE 0x7500
638 #define K_NEXT 0x7900
639 #define K_LEFT 0x7b00
640 #define K_RIGHT 0x7c00
641 #define K_DOWN 0x7d00
653 #define KP_CLEAR 0x4700
654 #define KP_EQUAL 0x5100
655 #define KP_SLASH 0x4b00
656 #define KP_STAR 0x4300
657 #define KP_PLUS 0x4500
658 #define KP_MINUS 0x4e00
659 #define KP_DOT 0x4100
660 #define KP_ENTER 0x4c00
662 void mac_keyterm(WindowPtr window, EventRecord *event) {
663 unsigned char buf[20];
667 s = (Session *)GetWRefCon(window);
668 len = mac_keytrans(s, event, buf);
669 ldisc_send(s->ldisc, (char *)buf, len, 1);
671 term_seen_key_event(s->term);
673 term_update(s->term);
676 static int mac_keytrans(Session *s, EventRecord *event,
677 unsigned char *output) {
678 unsigned char *p = output;
681 /* No meta key yet -- that'll be rather fun. */
683 /* Keys that we handle locally */
684 if (event->modifiers & shiftKey) {
685 switch (event->message & keyCodeMask) {
686 case K_PRIOR: /* shift-pageup */
687 term_scroll(s->term, 0, -(s->term->rows - 1));
689 case K_NEXT: /* shift-pagedown */
690 term_scroll(s->term, 0, +(s->term->rows - 1));
696 * Control-2 should return ^@ (0x00), Control-6 should return
697 * ^^ (0x1E), and Control-Minus should return ^_ (0x1F). Since
698 * the DOS keyboard handling did it, and we have nothing better
699 * to do with the key combo in question, we'll also map
700 * Control-Backquote to ^\ (0x1C).
703 if (event->modifiers & controlKey) {
704 switch (event->message & charCodeMask) {
721 * First, all the keys that do tilde codes. (ESC '[' nn '~',
722 * for integer decimal nn.)
724 * We also deal with the weird ones here. Linux VCs replace F1
725 * to F5 by ESC [ [ A to ESC [ [ E. rxvt doesn't do _that_, but
726 * does replace Home and End (1~ and 4~) by ESC [ H and ESC O w
730 switch (event->message & keyCodeMask) {
731 case K_F1: code = (event->modifiers & shiftKey ? 23 : 11); break;
732 case K_F2: code = (event->modifiers & shiftKey ? 24 : 12); break;
733 case K_F3: code = (event->modifiers & shiftKey ? 25 : 13); break;
734 case K_F4: code = (event->modifiers & shiftKey ? 26 : 14); break;
735 case K_F5: code = (event->modifiers & shiftKey ? 28 : 15); break;
736 case K_F6: code = (event->modifiers & shiftKey ? 29 : 17); break;
737 case K_F7: code = (event->modifiers & shiftKey ? 31 : 18); break;
738 case K_F8: code = (event->modifiers & shiftKey ? 32 : 19); break;
739 case K_F9: code = (event->modifiers & shiftKey ? 33 : 20); break;
740 case K_F10: code = (event->modifiers & shiftKey ? 34 : 21); break;
741 case K_F11: code = 23; break;
742 case K_F12: code = 24; break;
743 case K_HOME: code = 1; break;
744 case K_INSERT: code = 2; break;
745 case K_DELETE: code = 3; break;
746 case K_END: code = 4; break;
747 case K_PRIOR: code = 5; break;
748 case K_NEXT: code = 6; break;
750 if (s->cfg.funky_type == 1 && code >= 11 && code <= 15) {
751 p += sprintf((char *)p, "\x1B[[%c", code + 'A' - 11);
754 if (s->cfg.rxvt_homeend && (code == 1 || code == 4)) {
755 p += sprintf((char *)p, code == 1 ? "\x1B[H" : "\x1BOw");
759 p += sprintf((char *)p, "\x1B[%d~", code);
763 if (s->term->app_keypad_keys) {
764 switch (event->message & keyCodeMask) {
765 case KP_ENTER: p += sprintf((char *)p, "\x1BOM"); return p - output;
766 case KP_CLEAR: p += sprintf((char *)p, "\x1BOP"); return p - output;
767 case KP_EQUAL: p += sprintf((char *)p, "\x1BOQ"); return p - output;
768 case KP_SLASH: p += sprintf((char *)p, "\x1BOR"); return p - output;
769 case KP_STAR: p += sprintf((char *)p, "\x1BOS"); return p - output;
770 case KP_PLUS: p += sprintf((char *)p, "\x1BOl"); return p - output;
771 case KP_MINUS: p += sprintf((char *)p, "\x1BOm"); return p - output;
772 case KP_DOT: p += sprintf((char *)p, "\x1BOn"); return p - output;
773 case KP_0: p += sprintf((char *)p, "\x1BOp"); return p - output;
774 case KP_1: p += sprintf((char *)p, "\x1BOq"); return p - output;
775 case KP_2: p += sprintf((char *)p, "\x1BOr"); return p - output;
776 case KP_3: p += sprintf((char *)p, "\x1BOs"); return p - output;
777 case KP_4: p += sprintf((char *)p, "\x1BOt"); return p - output;
778 case KP_5: p += sprintf((char *)p, "\x1BOu"); return p - output;
779 case KP_6: p += sprintf((char *)p, "\x1BOv"); return p - output;
780 case KP_7: p += sprintf((char *)p, "\x1BOw"); return p - output;
781 case KP_8: p += sprintf((char *)p, "\x1BOx"); return p - output;
782 case KP_9: p += sprintf((char *)p, "\x1BOy"); return p - output;
786 switch (event->message & keyCodeMask) {
788 p += sprintf((char *)p,
789 s->term->app_cursor_keys ? "\x1BOA" : "\x1B[A");
792 p += sprintf((char *)p,
793 s->term->app_cursor_keys ? "\x1BOB" : "\x1B[B");
796 p += sprintf((char *)p,
797 s->term->app_cursor_keys ? "\x1BOC" : "\x1B[C");
800 p += sprintf((char *)p,
801 s->term->app_cursor_keys ? "\x1BOD" : "\x1B[D");
807 *p++ = (s->cfg.bksp_is_delete ? 0x7f : 0x08);
810 *p++ = event->message & charCodeMask;
815 void request_paste(void *frontend)
817 Session *s = frontend;
820 * In the Mac OS, pasting is synchronous: we can read the
821 * clipboard with no difficulty, so request_paste() can just go
824 term_do_paste(s->term);
835 void mac_growterm(WindowPtr window, EventRecord *event) {
838 int newrows, newcols;
840 DragGrayRgnUPP draghooksave;
844 s = (Session *)GetWRefCon(window);
846 draghooksave = LMGetDragHook();
847 growterm_state.oldmsg[0] = '\0';
848 growterm_state.zeromouse = event->where;
849 growterm_state.zeromouse.h -= s->term->cols * s->font_width;
850 growterm_state.zeromouse.v -= s->term->rows * s->font_height;
851 growterm_state.s = s;
854 BackColor(whiteColor);
855 ForeColor(blackColor);
856 TextFont(systemFont);
860 SetRect(&growterm_state.msgrect, 0, 0,
861 StringWidth("\p99999x99999") + 4, fi.ascent + fi.descent + 4);
862 SetPt(&growterm_state.msgorigin, 2, fi.ascent + 2);
863 LMSetDragHook(NewDragGrayRgnUPP(mac_growtermdraghook));
865 SetRect(&limits, s->font_width + 15, s->font_height, SHRT_MAX, SHRT_MAX);
866 grow_result = GrowWindow(window, event->where, &limits);
868 DisposeDragGrayRgnUPP(LMGetDragHook());
869 LMSetDragHook(draghooksave);
870 InvalRect(&growterm_state.msgrect);
874 if (grow_result != 0) {
875 newrows = HiWord(grow_result) / s->font_height;
876 newcols = (LoWord(grow_result) - 15) / s->font_width;
877 mac_adjustsize(s, newrows, newcols);
878 term_size(s->term, newrows, newcols, s->cfg.savelines);
882 static pascal void mac_growtermdraghook(void)
884 Session *s = growterm_state.s;
888 unsigned char pbuf[20];
889 int newrows, newcols;
892 newrows = (mouse.v - growterm_state.zeromouse.v) / s->font_height;
893 if (newrows < 1) newrows = 1;
894 newcols = (mouse.h - growterm_state.zeromouse.h) / s->font_width;
895 if (newcols < 1) newcols = 1;
896 sprintf(buf, "%dx%d", newcols, newrows);
897 if (strcmp(buf, growterm_state.oldmsg) == 0)
899 strcpy(growterm_state.oldmsg, buf);
900 c2pstrcpy(pbuf, buf);
903 SetPort(growterm_state.s->window);
904 EraseRect(&growterm_state.msgrect);
905 MoveTo(growterm_state.msgorigin.h, growterm_state.msgorigin.v);
910 void mac_activateterm(WindowPtr window, Boolean active) {
913 s = (Session *)GetWRefCon(window);
914 s->term->has_focus = active;
915 term_update(s->term);
917 ShowControl(s->scrollbar);
920 PmBackColor(DEFAULT_BG);/* HideControl clears behind the control */
922 BackColor(blackColor);
923 HideControl(s->scrollbar);
928 void mac_updateterm(WindowPtr window) {
931 s = (Session *)GetWRefCon(window);
935 term_paint(s->term, s,
936 PTOCC((*window->visRgn)->rgnBBox.left),
937 PTOCR((*window->visRgn)->rgnBBox.top),
938 PTOCC((*window->visRgn)->rgnBBox.right),
939 PTOCR((*window->visRgn)->rgnBBox.bottom), 1);
940 /* Restore default colours in case the Window Manager uses them */
941 if (HAVE_COLOR_QD()) {
942 PmForeColor(DEFAULT_FG);
943 PmBackColor(DEFAULT_BG);
945 ForeColor(whiteColor);
946 BackColor(blackColor);
948 if (FrontWindow() != window)
949 EraseRect(&(*s->scrollbar)->contrlRect);
950 UpdateControls(window, window->visRgn);
956 static void mac_drawgrowicon(Session *s) {
962 * Stop DrawGrowIcon giving us space for a horizontal scrollbar
963 * See Tech Note TB575 for details.
965 clip = s->window->portRect;
966 clip.left = clip.right - 15;
970 DrawGrowIcon(s->window);
975 struct do_text_args {
986 * Call from the terminal emulator to draw a bit of text
988 * x and y are text row and column (zero-based)
990 void do_text(Context ctx, int x, int y, char *text, int len,
991 unsigned long attr, int lattr) {
994 struct do_text_args a;
996 char mactextbuf[1024];
997 UniChar unitextbuf[1024];
1000 ByteCount iread, olen;
1003 assert(len <= 1024);
1007 /* First check this text is relevant */
1008 a.textrect.top = y * s->font_height;
1009 a.textrect.bottom = (y + 1) * s->font_height;
1010 a.textrect.left = x * s->font_width;
1011 a.textrect.right = (x + len) * s->font_width;
1012 if (!RectInRgn(&a.textrect, s->window->visRgn))
1015 /* Unpack Unicode from the mad format we get passed */
1016 for (i = 0; i < len; i++)
1017 unitextbuf[i] = (unsigned char)text[i] | (attr & CSET_MASK);
1019 if (s->uni_to_font != NULL) {
1020 err = ConvertFromUnicodeToText(s->uni_to_font, len * sizeof(UniChar),
1021 unitextbuf, kUnicodeUseFallbacksMask,
1022 0, NULL, NULL, NULL,
1023 1024, &iread, &olen, mactextbuf);
1024 if (err != noErr && err != kTECUsedFallbacksStatus)
1026 } else if (s->font_charset != CS_NONE) {
1027 /* XXX this is bogus if wchar_t and UniChar are different sizes. */
1028 unitextptr = (wchar_t *)unitextbuf;
1029 olen = charset_from_unicode(&unitextptr, &len, mactextbuf, 1024,
1030 s->font_charset, NULL, ".", 1);
1035 a.text = mactextbuf;
1039 a.numer.h = a.numer.v = a.denom.h = a.denom.v = 1;
1041 TextFont(s->fontnum);
1042 if (s->cfg.fontisbold || (attr & ATTR_BOLD) && !s->cfg.bold_colour)
1044 if (attr & ATTR_UNDER)
1047 TextSize(s->cfg.fontheight);
1049 if (HAVE_COLOR_QD())
1051 SpaceExtra(s->font_boldadjust << 16);
1052 CharExtra(s->font_boldadjust << 16);
1058 RectRgn(textrgn, &a.textrect);
1059 if (HAVE_COLOR_QD())
1060 DeviceLoop(textrgn, &do_text_for_device_upp, (long)&a, 0);
1062 do_text_for_device(1, 0, NULL, (long)&a);
1063 DisposeRgn(textrgn);
1064 /* Tell the window manager about it in case this isn't an update */
1065 ValidRect(&a.textrect);
1068 static pascal void do_text_for_device(short depth, short devflags,
1069 GDHandle device, long cookie) {
1070 struct do_text_args *a;
1071 int bgcolour, fgcolour, bright, reverse, tmp;
1073 a = (struct do_text_args *)cookie;
1075 bright = (a->attr & ATTR_BOLD) && a->s->cfg.bold_colour;
1076 reverse = a->attr & ATTR_REVERSE;
1078 if (depth == 1 && (a->attr & TATTR_ACTCURS))
1081 if (HAVE_COLOR_QD()) {
1083 fgcolour = ((a->attr & ATTR_FGMASK) >> ATTR_FGSHIFT) * 2;
1084 bgcolour = ((a->attr & ATTR_BGMASK) >> ATTR_BGSHIFT) * 2;
1087 * NB: bold reverse in 2bpp breaks with the usual PuTTY model and
1088 * boldens the background, because that's all we can do.
1090 fgcolour = bright ? DEFAULT_FG_BOLD : DEFAULT_FG;
1091 bgcolour = DEFAULT_BG;
1095 fgcolour = bgcolour;
1098 if (bright && depth > 2)
1100 if ((a->attr & TATTR_ACTCURS) && depth > 1) {
1101 fgcolour = CURSOR_FG;
1102 bgcolour = CURSOR_BG;
1104 PmForeColor(fgcolour);
1105 PmBackColor(bgcolour);
1106 } else { /* No Color Quickdraw */
1107 /* XXX This should be done with a _little_ more configurability */
1109 ForeColor(blackColor);
1110 BackColor(whiteColor);
1112 ForeColor(whiteColor);
1113 BackColor(blackColor);
1117 EraseRect(&a->textrect);
1118 MoveTo(a->textrect.left, a->textrect.top + a->s->font_ascent);
1119 /* FIXME: Sort out bold width adjustments on Original QuickDraw. */
1120 if (a->s->window->grafProcs != NULL)
1121 InvokeQDTextUPP(a->len, a->text, a->numer, a->denom,
1122 a->s->window->grafProcs->textProc);
1124 StdText(a->len, a->text, a->numer, a->denom);
1126 if (a->attr & TATTR_PASCURS) {
1133 PmForeColor(CURSOR_BG);
1136 FrameRect(&a->textrect);
1140 void do_cursor(Context ctx, int x, int y, char *text, int len,
1141 unsigned long attr, int lattr)
1144 do_text(ctx, x, y, text, len, attr, lattr);
1148 * Call from the terminal emulator to get its graphics context.
1149 * Should probably be called start_redraw or something.
1151 void pre_paint(Session *s) {
1153 Rect myrect, tmprect;
1155 if (HAVE_COLOR_QD()) {
1156 s->term->attr_mask = 0;
1158 myrect = (*s->window->visRgn)->rgnBBox;
1159 LocalToGlobal((Point *)&myrect.top);
1160 LocalToGlobal((Point *)&myrect.bottom);
1161 for (gdh = GetDeviceList();
1163 gdh = GetNextDevice(gdh)) {
1164 if (TestDeviceAttribute(gdh, screenDevice) &&
1165 TestDeviceAttribute(gdh, screenActive) &&
1166 SectRect(&(*gdh)->gdRect, &myrect, &tmprect)) {
1167 switch ((*(*gdh)->gdPMap)->pixelSize) {
1169 if (s->cfg.bold_colour)
1170 s->term->attr_mask |= ~(ATTR_COLOURS |
1171 (s->cfg.bold_colour ? ATTR_BOLD : 0));
1174 s->term->attr_mask |= ~ATTR_COLOURS;
1177 s->term->attr_mask = ~0;
1178 return; /* No point checking more screens. */
1183 s->term->attr_mask = ~(ATTR_COLOURS |
1184 (s->cfg.bold_colour ? ATTR_BOLD : 0));
1187 Context get_ctx(void *frontend) {
1188 Session *s = frontend;
1194 void free_ctx(Context ctx) {
1199 * Presumably this does something in Windows
1201 void post_paint(Session *s) {
1206 * Set the scroll bar position
1208 * total is the line number of the bottom of the working screen
1209 * start is the line number of the top of the display
1210 * page is the length of the displayed page
1212 void set_sbar(void *frontend, int total, int start, int page) {
1213 Session *s = frontend;
1215 /* We don't redraw until we've set everything up, to avoid glitches */
1216 (*s->scrollbar)->contrlMin = 0;
1217 (*s->scrollbar)->contrlMax = total - page;
1218 SetControlValue(s->scrollbar, start);
1220 if (mac_gestalts.cntlattr & gestaltControlMgrPresent)
1221 SetControlViewSize(s->scrollbar, page);
1225 void sys_cursor(void *frontend, int x, int y)
1228 * I think his is meaningless under Mac OS.
1233 * This is still called when mode==BELL_VISUAL, even though the
1234 * visual bell is handled entirely within terminal.c, because we
1235 * may want to perform additional actions on any kind of bell (for
1236 * example, taskbar flashing in Windows).
1238 void beep(void *frontend, int mode)
1240 if (mode != BELL_VISUAL)
1243 * XXX We should indicate the relevant window and/or use the
1244 * Notification Manager
1248 int char_width(Context ctx, int uc)
1251 * Until we support exciting character-set stuff, assume all chars are
1258 * Set icon string -- a no-op here (Windowshade?)
1260 void set_icon(void *frontend, char *icon) {
1261 Session *s = frontend;
1266 * Set the window title
1268 void set_title(void *frontend, char *title) {
1269 Session *s = frontend;
1272 mactitle[0] = sprintf((char *)&mactitle[1], "%s", title);
1273 SetWTitle(s->window, mactitle);
1277 * set or clear the "raw mouse message" mode
1279 void set_raw_mouse_mode(void *frontend, int activate)
1281 Session *s = frontend;
1283 s->raw_mouse = activate;
1284 /* FIXME: Should call mac_updatetermcursor as appropriate. */
1288 * Resize the window at the emulator's request
1290 void request_resize(void *frontend, int w, int h) {
1291 Session *s = frontend;
1299 * Iconify (actually collapse) the window at the emulator's request.
1301 void set_iconic(void *frontend, int iconic)
1303 Session *s = frontend;
1306 if (mac_gestalts.apprvers >= 0x0100 &&
1307 GetWindowFeatures(s->window, &features) == noErr &&
1308 (features & kWindowCanCollapse))
1309 CollapseWindow(s->window, iconic);
1313 * Move the window in response to a server-side request.
1315 void move_window(void *frontend, int x, int y)
1317 Session *s = frontend;
1319 MoveWindow(s->window, x, y, FALSE);
1323 * Move the window to the top or bottom of the z-order in response
1324 * to a server-side request.
1326 void set_zorder(void *frontend, int top)
1328 Session *s = frontend;
1331 * We also change the input focus to point to the topmost window,
1332 * since that's probably what the Human Interface Guidelines would
1336 SelectWindow(s->window);
1338 SendBehind(s->window, NULL);
1342 * Refresh the window in response to a server-side request.
1344 void refresh_window(void *frontend)
1346 Session *s = frontend;
1348 term_invalidate(s->term);
1352 * Maximise or restore the window in response to a server-side
1355 void set_zoomed(void *frontend, int zoomed)
1357 Session *s = frontend;
1359 ZoomWindow(s->window, zoomed ? inZoomOut : inZoomIn, FALSE);
1363 * Report whether the window is iconic, for terminal reports.
1365 int is_iconic(void *frontend)
1367 Session *s = frontend;
1370 if (mac_gestalts.apprvers >= 0x0100 &&
1371 GetWindowFeatures(s->window, &features) == noErr &&
1372 (features & kWindowCanCollapse))
1373 return IsWindowCollapsed(s->window);
1378 * Report the window's position, for terminal reports.
1380 void get_window_pos(void *frontend, int *x, int *y)
1382 Session *s = frontend;
1384 *x = s->window->portRect.left;
1385 *y = s->window->portRect.top;
1389 * Report the window's pixel size, for terminal reports.
1391 void get_window_pixels(void *frontend, int *x, int *y)
1393 Session *s = frontend;
1395 *x = s->window->portRect.right - s->window->portRect.left;
1396 *y = s->window->portRect.bottom - s->window->portRect.top;
1400 * Return the window or icon title.
1402 char *get_window_title(void *frontend, int icon)
1404 Session *s = frontend;
1406 /* Erm, we don't save this at the moment */
1411 * real_palette_set(): This does the actual palette-changing work on behalf
1412 * of palette_set(). Does _not_ call ActivatePalette() in case the caller
1413 * is doing a batch of updates.
1415 static void real_palette_set(Session *s, int n, int r, int g, int b)
1419 if (!HAVE_COLOR_QD())
1421 col.red = r * 0x0101;
1422 col.green = g * 0x0101;
1423 col.blue = b * 0x0101;
1424 SetEntryColor(s->palette, n, &col);
1428 * Set the logical palette. Called by the terminal emulator.
1430 void palette_set(void *frontend, int n, int r, int g, int b) {
1431 Session *s = frontend;
1432 static const int first[21] = {
1433 0, 2, 4, 6, 8, 10, 12, 14,
1434 1, 3, 5, 7, 9, 11, 13, 15,
1438 if (!HAVE_COLOR_QD())
1440 real_palette_set(s, first[n], r, g, b);
1442 real_palette_set(s, first[n]+1, r, g, b);
1443 if (first[n] == DEFAULT_BG)
1445 ActivatePalette(s->window);
1449 * Reset to the default palette
1451 void palette_reset(void *frontend) {
1452 Session *s = frontend;
1453 /* This maps colour indices in cfg to those used in our palette. */
1454 static const int ww[] = {
1455 6, 7, 8, 9, 10, 11, 12, 13,
1456 14, 15, 16, 17, 18, 19, 20, 21,
1461 if (!HAVE_COLOR_QD())
1464 assert(lenof(ww) == NCOLOURS);
1466 for (i = 0; i < NCOLOURS; i++) {
1467 real_palette_set(s, i,
1468 s->cfg.colours[ww[i]][0],
1469 s->cfg.colours[ww[i]][1],
1470 s->cfg.colours[ww[i]][2]);
1473 ActivatePalette(s->window);
1474 /* Palette Manager will generate update events as required. */
1478 * Scroll the screen. (`lines' is +ve for scrolling forward, -ve
1481 void do_scroll(void *frontend, int topline, int botline, int lines) {
1482 Session *s = frontend;
1484 RgnHandle scrollrgn = NewRgn();
1485 RgnHandle movedupdate = NewRgn();
1486 RgnHandle update = NewRgn();
1487 Point g2l = { 0, 0 };
1492 * Work out the part of the update region that will scrolled by
1496 SetRectRgn(scrollrgn, 0, (topline + lines) * s->font_height,
1497 s->term->cols * s->font_width,
1498 (botline + 1) * s->font_height);
1500 SetRectRgn(scrollrgn, 0, topline * s->font_height,
1501 s->term->cols * s->font_width,
1502 (botline - lines + 1) * s->font_height);
1503 CopyRgn(((WindowPeek)s->window)->updateRgn, movedupdate);
1504 GlobalToLocal(&g2l);
1505 OffsetRgn(movedupdate, g2l.h, g2l.v); /* Convert to local co-ords. */
1506 SectRgn(scrollrgn, movedupdate, movedupdate); /* Clip scrolled section. */
1507 ValidRgn(movedupdate);
1508 OffsetRgn(movedupdate, 0, -lines * s->font_height); /* Scroll it. */
1511 if (HAVE_COLOR_QD())
1512 PmBackColor(DEFAULT_BG);
1514 BackColor(blackColor); /* XXX make configurable */
1515 SetRect(&r, 0, topline * s->font_height,
1516 s->term->cols * s->font_width, (botline + 1) * s->font_height);
1517 ScrollRect(&r, 0, - lines * s->font_height, update);
1520 InvalRgn(movedupdate);
1522 DisposeRgn(scrollrgn);
1523 DisposeRgn(movedupdate);
1527 void logevent(void *frontend, char *str) {
1529 fprintf(stderr, "%s\n", str);
1532 /* Dummy routine, only required in plink. */
1533 void ldisc_update(void *frontend, int echo, int edit)
1538 * Mac PuTTY doesn't support printing yet.
1540 printer_job *printer_start_job(char *printer)
1546 void printer_job_data(printer_job *pj, void *data, int len)
1550 void printer_finish_job(printer_job *pj)
1554 void frontend_keypress(void *handle)
1557 * Keypress termination in non-Close-On-Exit mode is not
1558 * currently supported in PuTTY proper, because the window
1559 * always has a perfectly good Close button anyway. So we do
1566 * Ask whether to wipe a session log file before writing to it.
1567 * Returns 2 for wipe, 1 for append, 0 for cancel (don't log).
1569 int askappend(void *frontend, char *filename)
1572 /* FIXME: not implemented yet. */
1579 * c-file-style: "simon"