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