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