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