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