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