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