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