3 * Copyright (c) 1999, 2003 Ben Harris
6 * Permission is hereby granted, free of charge, to any person
7 * obtaining a copy of this software and associated documentation
8 * files (the "Software"), to deal in the Software without
9 * restriction, including without limitation the rights to use,
10 * copy, modify, merge, publish, distribute, sublicense, and/or
11 * sell copies of the Software, and to permit persons to whom the
12 * Software is furnished to do so, subject to the following
15 * The above copyright notice and this permission notice shall be
16 * included in all copies or substantial portions of the Software.
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR
22 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
23 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
24 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 * mac.c -- miscellaneous Mac-specific routines
32 #include <AEDataModel.h>
33 #include <AppleEvents.h>
35 #include <Quickdraw.h>
37 #include <MacWindows.h>
40 #include <Appearance.h>
41 #include <CodeFragments.h>
47 #include <Navigation.h>
48 #include <Resources.h>
50 #include <TextCommon.h>
51 #include <ToolUtils.h>
52 #include <UnicodeConverter.h>
57 #include <stdlib.h> /* putty.h needs size_t */
58 #include <stdio.h> /* for vsprintf */
60 #define PUTTY_DO_GLOBALS
71 static int borednow = FALSE;
72 struct mac_gestalts mac_gestalts;
74 static long timing_next_time;
76 static void mac_startup(void);
77 static void mac_eventloop(void);
78 #pragma noreturn (mac_eventloop)
79 static void mac_event(EventRecord *);
80 static void mac_contentclick(WindowPtr, EventRecord *);
81 static void mac_growwindow(WindowPtr, EventRecord *);
82 static void mac_activatewindow(WindowPtr, EventRecord *);
83 static void mac_suspendresume(EventRecord *);
84 static void mac_activateabout(WindowPtr, EventRecord *);
85 static void mac_updatewindow(WindowPtr);
86 static void mac_updatelicence(WindowPtr);
87 static void mac_keypress(EventRecord *);
88 static int mac_windowtype(WindowPtr);
89 static void mac_menucommand(long);
90 static void mac_openlicence(void);
91 static void mac_adjustcursor(RgnHandle);
92 static void mac_adjustmenus(void);
93 static void mac_closewindow(WindowPtr);
94 static void mac_zoomwindow(WindowPtr, short);
95 #pragma noreturn (cleanup_exit)
102 struct mac_windows windows;
104 int main (int argc, char **argv) {
110 #pragma noreturn (main)
112 static void mac_startup(void) {
116 #if !TARGET_API_MAC_CARBON
117 /* Init Memory Manager */
120 InitGraf(&qd.thePort);
121 /* Init Font Manager */
123 /* Init Window Manager */
125 /* Init Menu Manager */
129 /* Init Dialog Manager */
134 /* Get base system version (only used if there's no better selector) */
135 if (Gestalt(gestaltSystemVersion, &mac_gestalts.sysvers) != noErr ||
136 (mac_gestalts.sysvers &= 0xffff) < 0x700)
137 fatalbox("PuTTY requires System 7 or newer");
138 /* Find out if we've got Color Quickdraw */
139 if (Gestalt(gestaltQuickdrawVersion, &mac_gestalts.qdvers) != noErr)
140 mac_gestalts.qdvers = gestaltOriginalQD;
141 /* ... and the Appearance Manager? */
142 if (Gestalt(gestaltAppearanceVersion, &mac_gestalts.apprvers) != noErr)
143 if (Gestalt(gestaltAppearanceAttr, NULL) == noErr)
144 mac_gestalts.apprvers = 0x0100;
146 mac_gestalts.apprvers = 0;
147 #if TARGET_RT_MAC_CFM
148 /* Paranoia: Did we manage to pull in AppearanceLib? */
149 if (&RegisterAppearanceClient == kUnresolvedCFragSymbolAddress)
150 mac_gestalts.apprvers = 0;
153 mac_gestalts.cntlattr = 0;
154 mac_gestalts.windattr = 0;
156 /* Mac OS 8.5 Control Manager (proportional scrollbars)? */
157 if (Gestalt(gestaltControlMgrAttr, &mac_gestalts.cntlattr) != noErr ||
158 &SetControlViewSize == kUnresolvedCFragSymbolAddress)
159 mac_gestalts.cntlattr = 0;
160 /* Mac OS 8.5 Window Manager? */
161 if (Gestalt(gestaltWindowMgrAttr, &mac_gestalts.windattr) != noErr ||
162 &SetWindowContentColor == kUnresolvedCFragSymbolAddress)
163 mac_gestalts.windattr = 0;
164 /* Mac OS 8.5 Menu Manager? */
165 if (Gestalt(gestaltMenuMgrAttr, &mac_gestalts.menuattr) != noErr)
166 mac_gestalts.menuattr = 0;
168 /* Text Encoding Conversion Manager? */
170 #if TARGET_RT_MAC_CFM
171 &TECGetInfo == kUnresolvedCFragSymbolAddress ||
173 InitializeUnicodeConverter(NULL) != noErr ||
175 TECGetInfo(&ti) != noErr)
176 mac_gestalts.encvvers = 0;
178 mac_gestalts.encvvers = (*ti)->tecVersion;
179 mac_gestalts.uncvattr = (*ti)->tecUnicodeConverterFeatures;
180 DisposeHandle((Handle)ti);
182 /* Navigation Services? */
183 if (NavServicesAvailable())
184 mac_gestalts.navsvers = NavLibraryVersion();
186 mac_gestalts.navsvers = 0;
190 /* We've been tested with the Appearance Manager */
191 if (mac_gestalts.apprvers != 0)
192 RegisterAppearanceClient();
194 menuBar = GetNewMBar(128);
196 fatalbox("Unable to create menu bar.");
198 AppendResMenu(GetMenuHandle(mApple), 'DRVR');
199 if (mac_gestalts.menuattr & gestaltMenuMgrAquaLayoutMask) {
200 DeleteMenuItem(GetMenuHandle(mFile), iQuit);
201 /* Also delete the separator above the Quit item. */
202 DeleteMenuItem(GetMenuHandle(mFile), iQuit - 1);
207 windows.about = NULL;
208 windows.licence = NULL;
210 default_protocol = be_default_protocol;
211 /* Find the appropriate default port. */
213 Backend *b = backend_from_proto(default_protocol);
214 default_port = 0; /* illegal */
216 default_port = b->default_port;
218 flags = FLAG_INTERACTIVE;
220 #if !TARGET_API_MAC_CARBON
225 /* Set the default directory for loading and saving settings. */
226 /* XXX Should we create it? */
227 if (get_session_dir(FALSE, &vol, &dirid) == noErr) {
228 LMSetSFSaveDisk(-vol);
229 LMSetCurDirStore(dirid);
234 /* Install Apple Event handlers. */
235 AEInstallEventHandler(kCoreEventClass, kAEOpenApplication,
236 NewAEEventHandlerUPP(&mac_aevt_oapp), 0, FALSE);
237 AEInstallEventHandler(kCoreEventClass, kAEOpenDocuments,
238 NewAEEventHandlerUPP(&mac_aevt_odoc), 0, FALSE);
239 AEInstallEventHandler(kCoreEventClass, kAEPrintDocuments,
240 NewAEEventHandlerUPP(&mac_aevt_pdoc), 0, FALSE);
241 AEInstallEventHandler(kCoreEventClass, kAEQuitApplication,
242 NewAEEventHandlerUPP(&mac_aevt_quit), 0, FALSE);
245 void timer_change_notify(long next)
247 timing_next_time = next;
250 static void mac_eventloop(void) {
260 ticksleft=timing_next_time-GETTICKCOUNT();
261 if (sleeptime > ticksleft && ticksleft >=0)
263 gotevent = WaitNextEvent(everyEvent, &event, sleeptime, cursrgn);
264 if (timing_next_time <= GETTICKCOUNT()) {
265 if (run_timers(timing_next_time, &next)) {
266 timer_change_notify(next);
271 * XXX For now, limit sleep time to 1/10 s to work around
272 * wake-before-sleep race in MacTCP code.
275 mac_adjustcursor(cursrgn);
277 /* Ensure we get a null event when the real ones run out. */
285 if (mac_gestalts.apprvers >= 0x100 && mac_frontwindow() != NULL)
286 IdleControls(mac_frontwindow());
291 static void mac_event(EventRecord *event) {
295 switch (event->what) {
297 part = FindWindow(event->where, &window);
301 mac_menucommand(MenuSelect(event->where));
303 #if !TARGET_API_MAC_CARBON
305 SystemClick(event, window);
309 if (window != FrontWindow())
310 /* XXX: check for movable modal dboxes? */
311 SelectWindow(window);
313 mac_contentclick(window, event);
316 if (TrackGoAway(window, event->where))
317 mac_closewindow(window);
320 /* XXX: moveable modal check? */
321 #if TARGET_API_MAC_CARBON
325 GetQDGlobalsScreenBits(&screenBits);
326 DragWindow(window, event->where, &screenBits.bounds);
329 DragWindow(window, event->where, &qd.screenBits.bounds);
333 mac_growwindow(window, event);
337 if (TrackBox(window, event->where, part))
338 mac_zoomwindow(window, part);
347 mac_activatewindow((WindowPtr)event->message, event);
350 mac_updatewindow((WindowPtr)event->message);
352 #if !TARGET_API_MAC_CARBON
354 if (HiWord(event->message) != noErr) {
357 SetPt(&pt, 120, 120);
358 DIBadMount(pt, event->message);
363 switch ((event->message & osEvtMessageMask) >> 24) {
364 case suspendResumeMessage:
365 mac_suspendresume(event);
369 case kHighLevelEvent:
370 AEProcessAppleEvent(event); /* errors? */
375 static void mac_contentclick(WindowPtr window, EventRecord *event)
378 if (mac_wininfo(window)->click != NULL)
379 (*mac_wininfo(window)->click)(window, event);
382 static void mac_growwindow(WindowPtr window, EventRecord *event)
385 if (mac_wininfo(window)->grow != NULL)
386 (*mac_wininfo(window)->grow)(window, event);
389 static void mac_activatewindow(WindowPtr window, EventRecord *event)
393 if (mac_wininfo(window)->activate != NULL)
394 (*mac_wininfo(window)->activate)(window, event);
397 static void mac_updatewindow(WindowPtr window)
400 if (mac_wininfo(window)->update != NULL)
401 (*mac_wininfo(window)->update)(window);
405 * Work out what kind of window we're dealing with.
407 static int mac_windowtype(WindowPtr window)
410 #if !TARGET_API_MAC_CARBON
411 if (GetWindowKind(window) < 0)
414 return ((WinInfo *)GetWRefCon(window))->wtype;
420 static void mac_keypress(EventRecord *event) {
423 window = mac_frontwindow();
425 * Check for a command-key combination, but ignore it if it counts
426 * as a meta-key combination and we're in a terminal window.
428 if (event->what == keyDown && (event->modifiers & cmdKey) /*&&
429 !((event->modifiers & cfg.meta_modifiers) == cfg.meta_modifiers &&
430 mac_windowtype(window) == wTerminal)*/) {
432 mac_menucommand(MenuKey(event->message & charCodeMask));
434 if (window != NULL && mac_wininfo(window)->key != NULL)
435 (*mac_wininfo(window)->key)(window, event);
439 static void mac_menucommand(long result) {
442 #if !TARGET_API_MAC_CARBON
446 menu = HiWord(result);
447 item = LoWord(result);
448 window = mac_frontwindow();
449 /* Things which do the same whatever window we're in. */
456 #if !TARGET_API_MAC_CARBON
458 GetMenuItemText(GetMenuHandle(mApple), item, da);
476 mac_closewindow(window);
493 /* If we get here, handling is up to window-specific code. */
494 if (window != NULL && mac_wininfo(window)->menu != NULL)
495 (*mac_wininfo(window)->menu)(window, menu, item);
501 static void mac_closewindow(WindowPtr window) {
503 switch (mac_windowtype(window)) {
504 #if !TARGET_API_MAC_CARBON
506 CloseDeskAcc(GetWindowKind(window));
510 if (mac_wininfo(window)->close != NULL)
511 (*mac_wininfo(window)->close)(window);
516 static void mac_suspendresume(EventRecord *event)
519 EventRecord fakeevent;
522 * We're called either before we're suspended or after we're
523 * resumed, so we're the front application at this point.
525 front = FrontWindow();
527 fakeevent.what = activateEvt;
528 fakeevent.message = (UInt32)front;
529 fakeevent.when = event->when;
530 fakeevent.where = event->where;
531 fakeevent.modifiers =
532 (event->message & resumeFlag) ? activeFlag : 0;
533 mac_activatewindow(front, &fakeevent);
537 static void mac_zoomwindow(WindowPtr window, short part) {
539 /* FIXME: do something */
543 * Make the menus look right before the user gets to see them.
545 #if TARGET_API_MAC_CARBON
546 #define EnableItem EnableMenuItem
547 #define DisableItem DisableMenuItem
549 static void mac_adjustmenus(void) {
553 window = mac_frontwindow();
554 menu = GetMenuHandle(mApple);
556 EnableItem(menu, iAbout);
558 menu = GetMenuHandle(mFile);
560 EnableItem(menu, iNew);
562 EnableItem(menu, iClose);
564 DisableItem(menu, iClose);
565 EnableItem(menu, iQuit);
567 if (window != NULL && mac_wininfo(window)->adjustmenus != NULL)
568 (*mac_wininfo(window)->adjustmenus)(window);
570 DisableItem(menu, iChange);
571 DisableItem(menu, iSave);
572 DisableItem(menu, iSaveAs);
573 DisableItem(menu, iDuplicate);
574 menu = GetMenuHandle(mEdit);
575 DisableItem(menu, 0);
576 menu = GetMenuHandle(mWindow);
577 DisableItem(menu, 0); /* Until we get more than 1 item on it. */
583 * Make sure the right cursor's being displayed.
585 static void mac_adjustcursor(RgnHandle cursrgn) {
587 WindowPtr window, front;
589 #if TARGET_API_MAC_CARBON
595 LocalToGlobal(&mouse);
596 part = FindWindow(mouse, &window);
597 front = FrontWindow();
598 if (part != inContent || window == NULL || window != front) {
599 /* Cursor isn't in the front window, so switch to arrow */
600 #if TARGET_API_MAC_CARBON
601 GetQDGlobalsArrow(&arrow);
604 SetCursor(&qd.arrow);
606 SetRectRgn(cursrgn, SHRT_MIN, SHRT_MIN, SHRT_MAX, SHRT_MAX);
608 #if TARGET_API_MAC_CARBON
610 GetPortVisibleRegion(GetWindowPort(front), visrgn);
611 DiffRgn(cursrgn, visrgn, cursrgn);
614 DiffRgn(cursrgn, front->visRgn, cursrgn);
618 if (mac_wininfo(window)->adjustcursor != NULL)
619 (*mac_wininfo(window)->adjustcursor)(window, mouse, cursrgn);
621 #if TARGET_API_MAC_CARBON
622 GetQDGlobalsArrow(&arrow);
624 GetPortVisibleRegion(GetWindowPort(window), cursrgn);
626 SetCursor(&qd.arrow);
627 CopyRgn(window->visRgn, cursrgn);
633 pascal OSErr mac_aevt_quit(const AppleEvent *req, AppleEvent *reply,
639 if (AEGetAttributePtr(req, keyMissedKeywordAttr, typeWildCard,
640 &type, NULL, 0, &size) == noErr)
641 return errAEParamMissed;
647 void cleanup_exit(int status)
650 #if !TARGET_RT_MAC_CFM
651 if (mac_gestalts.encvvers != 0)
652 TerminateUnicodeConverter();
658 /* This should only kill the current session, not the whole application. */
659 void connection_fatal(void *frontend, char *fmt, ...) {
662 Session *s = frontend;
665 /* We'd like stuff to be a Pascal string */
666 stuff[0] = vsprintf((char *)(&stuff[1]), fmt, ap);
668 ParamText(stuff, NULL, NULL, NULL);
669 StopAlert(128, NULL);
671 s->session_closed = TRUE;
673 if (s->cfg.close_on_exit == FORCE_ON)
674 mac_closewindow(s->window);
677 /* Null SSH agent client -- never finds an agent. */
679 int agent_exists(void)
685 int agent_query(void *in, int inlen, void **out, int *outlen,
686 void (*callback)(void *, void *, int), void *callback_ctx)
694 /* Temporary null routines for testing. */
696 int verify_ssh_host_key(void *frontend, char *host, int port, char *keytype,
697 char *keystr, char *fingerprint,
698 void (*callback)(void *ctx, int result), void *ctx)
703 Session *s = frontend;
706 c2pstrcpy(pappname, appname);
707 c2pstrcpy(pkeytype, keytype);
708 c2pstrcpy(pfingerprint, fingerprint);
711 * The alert shouldn't be modal, it should be movable modal, or
712 * a sheet in Aqua. Also, PuTTY might be in the background, in
713 * which case we should use the Notification Manager to wake up
714 * the user. In any case, we shouldn't hold up processing of
715 * other connections' data just because this one's waiting for
719 /* Verify the key against the cache */
721 ret = verify_host_key(host, port, keytype, keystr);
723 if (ret == 0) { /* success - key matched OK */
725 } else if (ret == 2) { /* key was different */
726 ParamText(pappname, pkeytype, pfingerprint, NULL);
727 alertret=CautionAlert(wWrong, NULL);
731 } else if (alertret == 9) {
732 /* Connect Just Once */
736 store_host_key(host, port, keytype, keystr);
739 } else /* ret == 1 */ { /* key was absent */
740 ParamText(pkeytype, pfingerprint, pappname, NULL);
741 alertret=CautionAlert(wAbsent, NULL);
745 } else if (alertret == 8) {
746 /* Connect Just Once */
750 store_host_key(host, port, keytype, keystr);
756 int askalg(void *frontend, const char *algtype, const char *algname,
757 void (*callback)(void *ctx, int result), void *ctx)
762 void old_keyfile_warning(void)
767 FontSpec platform_default_fontspec(char const *name)
772 if (!strcmp(name, "Font")) {
773 smfs = GetScriptVariable(smSystemScript, smScriptMonoFondSize);
775 smfs = GetScriptVariable(smRoman, smScriptMonoFondSize);
777 GetFontName(HiWord(smfs), ret.name);
778 if (ret.name[0] == 0)
779 memcpy(ret.name, "\pMonaco", 7);
780 ret.size = LoWord(smfs);
782 memcpy(ret.name, "\pMonaco", 7);
793 Filename platform_default_filename(const char *name)
796 if (!strcmp(name, "LogFileName"))
797 FSMakeFSSpec(0, 0, "\pputty.log", &ret.fss);
799 memset(&ret, 0, sizeof(ret));
803 char *platform_default_s(char const *name)
808 int platform_default_i(char const *name, int def)
811 /* Non-raw cut and paste of line-drawing chars works badly on the
812 * current Unix stub implementation of the Unicode functions.
813 * So I'm going to temporarily set the default to raw mode so
814 * that the failure mode isn't quite so drastically horrid.
815 * When Unicode comes in, this can all be put right. */
816 if (!strcmp(name, "RawCNP"))
821 void platform_get_x11_auth(char *display, int *proto,
822 unsigned char *data, int *datalen)
824 /* SGT: I have no idea whether Mac X servers need anything here. */
827 void update_specials_menu(void *frontend)
829 Session *s = frontend;
832 front = mac_frontwindow();
833 if (front != NULL && mac_windowsession(front) == s)
837 void notify_remote_exit(void *frontend)
839 Session *s = frontend;
842 if (!s->session_closed &&
843 (exitcode = s->back->exitcode(s->backhandle)) >=0) {
844 s->session_closed = TRUE;
845 if (s->cfg.close_on_exit == FORCE_ON ||
846 (s->cfg.close_on_exit == AUTO && exitcode == 0)) {
847 mac_closewindow(s->window);
851 /* The session's dead */
854 ldisc_free(s->ldisc);
859 s->back->free(s->backhandle);
860 s->backhandle = NULL;
862 update_specials_menu(s);
867 sprintf(title, "%.70s (inactive)", appname);
875 * c-file-style: "simon"