1 /* $Id: mac.c,v 1.44 2003/02/04 00:33:11 ben Exp $ */
3 * Copyright (c) 1999 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>
34 #include <Quickdraw.h>
36 #include <MacWindows.h>
39 #include <Appearance.h>
40 #include <CodeFragments.h>
46 #include <Navigation.h>
47 #include <Resources.h>
49 #include <TextCommon.h>
50 #include <ToolUtils.h>
51 #include <UnicodeConverter.h>
56 #include <stdlib.h> /* putty.h needs size_t */
57 #include <stdio.h> /* for vsprintf */
59 #define PUTTY_DO_GLOBALS
66 #if !TARGET_API_MAC_CARBON
73 static int borednow = FALSE;
74 struct mac_gestalts mac_gestalts;
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_activateabout(WindowPtr, EventRecord *);
84 static void mac_updatewindow(WindowPtr);
85 static void mac_updatelicence(WindowPtr);
86 static void mac_keypress(EventRecord *);
87 static int mac_windowtype(WindowPtr);
88 static void mac_menucommand(long);
89 static void mac_openabout(void);
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;
165 /* Text Encoding Conversion Manager? */
167 #if TARGET_RT_MAC_CFM
168 &TECGetInfo == kUnresolvedCFragSymbolAddress ||
170 InitializeUnicodeConverter(NULL) != noErr ||
172 TECGetInfo(&ti) != noErr)
173 mac_gestalts.encvvers = 0;
175 mac_gestalts.encvvers = (*ti)->tecVersion;
176 mac_gestalts.uncvattr = (*ti)->tecUnicodeConverterFeatures;
177 DisposeHandle((Handle)ti);
179 /* Navigation Services? */
180 if (NavServicesAvailable())
181 mac_gestalts.navsvers = NavLibraryVersion();
183 mac_gestalts.navsvers = 0;
187 /* We've been tested with the Appearance Manager */
188 if (mac_gestalts.apprvers != 0)
189 RegisterAppearanceClient();
191 menuBar = GetNewMBar(128);
193 fatalbox("Unable to create menu bar.");
195 AppendResMenu(GetMenuHandle(mApple), 'DRVR');
199 windows.about = NULL;
200 windows.licence = NULL;
202 default_protocol = be_default_protocol;
203 /* Find the appropriate default port. */
206 default_port = 0; /* illegal */
207 for (i = 0; backends[i].backend != NULL; i++)
208 if (backends[i].protocol == default_protocol) {
209 default_port = backends[i].backend->default_port;
213 flags = FLAG_INTERACTIVE;
215 #if !TARGET_API_MAC_CARBON
220 /* Set the default directory for loading and saving settings. */
221 /* XXX Should we create it? */
222 if (get_session_dir(FALSE, &vol, &dirid) == noErr) {
223 LMSetSFSaveDisk(-vol);
224 LMSetCurDirStore(dirid);
229 /* Install Apple Event handlers. */
230 AEInstallEventHandler(kCoreEventClass, kAEOpenApplication,
231 NewAEEventHandlerUPP(&mac_aevt_oapp), 0, FALSE);
232 AEInstallEventHandler(kCoreEventClass, kAEOpenDocuments,
233 NewAEEventHandlerUPP(&mac_aevt_odoc), 0, FALSE);
234 AEInstallEventHandler(kCoreEventClass, kAEPrintDocuments,
235 NewAEEventHandlerUPP(&mac_aevt_pdoc), 0, FALSE);
236 AEInstallEventHandler(kCoreEventClass, kAEQuitApplication,
237 NewAEEventHandlerUPP(&mac_aevt_quit), 0, FALSE);
240 static void mac_eventloop(void) {
247 mac_adjustcursor(cursrgn);
248 gotevent = WaitNextEvent(everyEvent, &event, LONG_MAX, cursrgn);
249 mac_adjustcursor(cursrgn);
260 static void mac_event(EventRecord *event) {
264 switch (event->what) {
266 part = FindWindow(event->where, &window);
270 mac_menucommand(MenuSelect(event->where));
272 #if !TARGET_API_MAC_CARBON
274 SystemClick(event, window);
278 if (window != FrontWindow())
279 /* XXX: check for movable modal dboxes? */
280 SelectWindow(window);
282 mac_contentclick(window, event);
285 if (TrackGoAway(window, event->where))
286 mac_closewindow(window);
289 /* XXX: moveable modal check? */
290 #if TARGET_API_MAC_CARBON
294 GetQDGlobalsScreenBits(&screenBits);
295 DragWindow(window, event->where, &screenBits.bounds);
298 DragWindow(window, event->where, &qd.screenBits.bounds);
302 mac_growwindow(window, event);
306 if (TrackBox(window, event->where, part))
307 mac_zoomwindow(window, part);
316 mac_activatewindow((WindowPtr)event->message, event);
319 mac_updatewindow((WindowPtr)event->message);
321 #if !TARGET_API_MAC_CARBON
323 if (HiWord(event->message) != noErr) {
326 SetPt(&pt, 120, 120);
327 DIBadMount(pt, event->message);
331 case kHighLevelEvent:
332 AEProcessAppleEvent(event); /* errors? */
337 static void mac_contentclick(WindowPtr window, EventRecord *event) {
341 switch (mac_windowtype(window)) {
343 mac_clickterm(window, event);
346 dialog = GetDialogFromWindow(window);
347 if (DialogSelect(event, &dialog, &item))
355 mac_clickdlg(window, event);
360 static void mac_growwindow(WindowPtr window, EventRecord *event) {
362 switch (mac_windowtype(window)) {
364 mac_growterm(window, event);
368 static void mac_activatewindow(WindowPtr window, EventRecord *event) {
371 active = (event->modifiers & activeFlag) != 0;
373 switch (mac_windowtype(window)) {
375 mac_activateterm(window, active);
378 mac_activatedlg(window, event);
381 mac_activateabout(window, event);
386 static void mac_activateabout(WindowPtr window, EventRecord *event) {
388 DialogItemType itemtype;
394 dialog = GetDialogFromWindow(window);
395 active = (event->modifiers & activeFlag) != 0;
396 GetDialogItem(dialog, wiAboutLicence, &itemtype, &itemhandle, &itemrect);
397 HiliteControl((ControlHandle)itemhandle, active ? 0 : 255);
398 DialogSelect(event, &dialog, &item);
401 static void mac_updatewindow(WindowPtr window)
403 #if TARGET_API_MAC_CARBON
407 switch (mac_windowtype(window)) {
409 mac_updateterm(window);
414 #if TARGET_API_MAC_CARBON
416 GetPortVisibleRegion(GetWindowPort(window), rgn);
417 UpdateDialog(GetDialogFromWindow(window), rgn);
420 UpdateDialog(window, window->visRgn);
425 mac_updatelicence(window);
430 static void mac_updatelicence(WindowPtr window)
437 SetPort((GrafPtr)GetWindowPort(window));
439 fondsize = GetScriptVariable(smRoman, smScriptSmallFondSize);
440 TextFont(HiWord(fondsize));
441 TextSize(LoWord(fondsize));
442 h = Get1Resource('TEXT', wLicence);
443 len = GetResourceSizeOnDisk(h);
444 #if TARGET_API_MAC_CARBON
445 GetPortBounds(GetWindowPort(window), &textrect);
447 textrect = window->portRect;
451 TETextBox(*h, len, &textrect, teFlushDefault);
458 * Work out what kind of window we're dealing with.
459 * Concept shamelessly nicked from SurfWriter.
461 static int mac_windowtype(WindowPtr window) {
467 kind = GetWindowKind(window);
470 if (GetWVariant(window) == zoomDocProc)
472 refcon = GetWRefCon(window);
482 static void mac_keypress(EventRecord *event) {
485 window = FrontWindow();
487 * Check for a command-key combination, but ignore it if it counts
488 * as a meta-key combination and we're in a terminal window.
490 if (event->what == keyDown && (event->modifiers & cmdKey) /*&&
491 !((event->modifiers & cfg.meta_modifiers) == cfg.meta_modifiers &&
492 mac_windowtype(window) == wTerminal)*/) {
494 mac_menucommand(MenuKey(event->message & charCodeMask));
496 switch (mac_windowtype(window)) {
498 mac_keyterm(window, event);
504 static void mac_menucommand(long result) {
507 #if !TARGET_API_MAC_CARBON
511 menu = HiWord(result);
512 item = LoWord(result);
513 window = FrontWindow();
514 /* Things which do the same whatever window we're in. */
521 #if !TARGET_API_MAC_CARBON
523 GetMenuItemText(GetMenuHandle(mApple), item, da);
538 mac_closewindow(window);
555 /* If we get here, handling is up to window-specific code. */
556 switch (mac_windowtype(window)) {
558 mac_menuterm(window, menu, item);
565 static void mac_openabout(void) {
566 DialogItemType itemtype;
573 SelectWindow(windows.about);
576 GetDialogWindow(GetNewDialog(wAbout, NULL, (WindowPtr)-1));
577 vers = (VersRecHndl)Get1Resource('vers', 1);
578 if (vers != NULL && *vers != NULL) {
579 longvers = (*vers)->shortVersion + (*vers)->shortVersion[0] + 1;
580 GetDialogItem(GetDialogFromWindow(windows.about), wiAboutVersion,
581 &itemtype, &item, &box);
582 assert(itemtype & kStaticTextDialogItem);
583 SetDialogItemText(item, longvers);
585 ShowWindow(windows.about);
589 static void mac_openlicence(void) {
592 SelectWindow(windows.licence);
594 windows.licence = GetNewWindow(wLicence, NULL, (WindowPtr)-1);
595 ShowWindow(windows.licence);
599 static void mac_closewindow(WindowPtr window) {
601 switch (mac_windowtype(window)) {
602 #if !TARGET_API_MAC_CARBON
604 CloseDeskAcc(((WindowPeek)window)->windowKind);
608 mac_closeterm(window);
611 windows.about = NULL;
612 DisposeDialog(GetDialogFromWindow(window));
615 windows.licence = NULL;
616 DisposeWindow(window);
621 static void mac_zoomwindow(WindowPtr window, short part) {
623 /* FIXME: do something */
627 * Make the menus look right before the user gets to see them.
629 #if TARGET_API_MAC_CARBON
630 #define EnableItem EnableMenuItem
631 #define DisableItem DisableMenuItem
633 static void mac_adjustmenus(void) {
637 window = FrontWindow();
638 menu = GetMenuHandle(mApple);
640 EnableItem(menu, iAbout);
642 menu = GetMenuHandle(mFile);
644 EnableItem(menu, iNew);
646 EnableItem(menu, iClose);
648 DisableItem(menu, iClose);
649 EnableItem(menu, iQuit);
651 switch (mac_windowtype(window)) {
653 DisableItem(menu, iSave); /* XXX enable if modified */
654 EnableItem(menu, iSaveAs);
655 EnableItem(menu, iDuplicate);
656 menu = GetMenuHandle(mEdit);
657 DisableItem(menu, 0);
660 mac_adjusttermmenus(window);
663 DisableItem(menu, iSave);
664 DisableItem(menu, iSaveAs);
665 DisableItem(menu, iDuplicate);
666 menu = GetMenuHandle(mEdit);
667 DisableItem(menu, 0);
674 * Make sure the right cursor's being displayed.
676 static void mac_adjustcursor(RgnHandle cursrgn) {
678 WindowPtr window, front;
680 #if TARGET_API_MAC_CARBON
686 LocalToGlobal(&mouse);
687 part = FindWindow(mouse, &window);
688 front = FrontWindow();
689 if (part != inContent || window == NULL || window != front) {
690 /* Cursor isn't in the front window, so switch to arrow */
691 #if TARGET_API_MAC_CARBON
692 GetQDGlobalsArrow(&arrow);
695 SetCursor(&qd.arrow);
697 SetRectRgn(cursrgn, SHRT_MIN, SHRT_MIN, SHRT_MAX, SHRT_MAX);
699 #if TARGET_API_MAC_CARBON
701 GetPortVisibleRegion(GetWindowPort(front), visrgn);
702 DiffRgn(cursrgn, visrgn, cursrgn);
705 DiffRgn(cursrgn, front->visRgn, cursrgn);
709 switch (mac_windowtype(window)) {
711 mac_adjusttermcursor(window, mouse, cursrgn);
714 #if TARGET_API_MAC_CARBON
715 GetQDGlobalsArrow(&arrow);
717 GetPortVisibleRegion(GetWindowPort(window), cursrgn);
719 SetCursor(&qd.arrow);
720 CopyRgn(window->visRgn, cursrgn);
727 pascal OSErr mac_aevt_quit(const AppleEvent *req, AppleEvent *reply,
733 if (AEGetAttributePtr(req, keyMissedKeywordAttr, typeWildCard,
734 &type, NULL, 0, &size) == noErr)
735 return errAEParamMissed;
741 void cleanup_exit(int status)
744 #if !TARGET_RT_MAC_CFM
745 if (mac_gestalts.encvvers != 0)
746 TerminateUnicodeConverter();
752 void fatalbox(char *fmt, ...) {
757 /* We'd like stuff to be a Pascal string */
758 stuff[0] = vsprintf((char *)(&stuff[1]), fmt, ap);
760 ParamText(stuff, NULL, NULL, NULL);
761 StopAlert(128, NULL);
765 void modalfatalbox(char *fmt, ...) {
770 /* We'd like stuff to be a Pascal string */
771 stuff[0] = vsprintf((char *)(&stuff[1]), fmt, ap);
773 ParamText(stuff, NULL, NULL, NULL);
774 StopAlert(128, NULL);
778 /* This should only kill the current session, not the whole application. */
779 void connection_fatal(void *fontend, char *fmt, ...) {
784 /* We'd like stuff to be a Pascal string */
785 stuff[0] = vsprintf((char *)(&stuff[1]), fmt, ap);
787 ParamText(stuff, NULL, NULL, NULL);
788 StopAlert(128, NULL);
792 /* Null SSH agent client -- never finds an agent. */
794 int agent_exists(void)
800 void agent_query(void *in, int inlen, void **out, int *outlen)
807 /* Temporary null routines for testing. */
809 void verify_ssh_host_key(void *frontend, char *host, int port, char *keytype,
810 char *keystr, char *fingerprint)
815 void askcipher(void *frontend, char *ciphername, int cs)
820 void old_keyfile_warning(void)
825 FontSpec platform_default_fontspec(char const *name)
830 if (!strcmp(name, "Font")) {
831 smfs = GetScriptVariable(smSystemScript, smScriptMonoFondSize);
833 smfs = GetScriptVariable(smRoman, smScriptMonoFondSize);
835 GetFontName(HiWord(smfs), ret.name);
836 if (ret.name[0] == 0)
837 memcpy(ret.name, "\pMonaco", 7);
838 ret.size = LoWord(smfs);
840 memcpy(ret.name, "\pMonaco", 7);
851 Filename platform_default_filename(const char *name)
854 if (!strcmp(name, "LogFileName"))
855 FSMakeFSSpec(0, 0, "\pputty.log", &ret.fss);
857 memset(&ret, 0, sizeof(ret));
861 char *platform_default_s(char const *name)
866 int platform_default_i(char const *name, int def)
869 /* Non-raw cut and paste of line-drawing chars works badly on the
870 * current Unix stub implementation of the Unicode functions.
871 * So I'm going to temporarily set the default to raw mode so
872 * that the failure mode isn't quite so drastically horrid.
873 * When Unicode comes in, this can all be put right. */
874 if (!strcmp(name, "RawCNP"))
879 void platform_get_x11_auth(char *display, int *proto,
880 unsigned char *data, int *datalen)
882 /* SGT: I have no idea whether Mac X servers need anything here. */
885 Filename filename_from_str(const char *str)
890 /* XXX This fails for filenames over 255 characters long. */
892 FSMakeFSSpec(0, 0, tmp, &ret.fss);
897 * Convert a filename to a string for display purposes.
898 * See pp 2-44--2-46 of IM:Files
900 * XXX static storage considered harmful
902 const char *filename_to_str(const Filename *fn)
907 static char *path = NULL;
910 if (path != NULL) sfree(path);
911 path = smalloc(fn->fss.name[0]);
912 p2cstrcpy(path, fn->fss.name);
913 pb.dirInfo.ioNamePtr = dirname;
914 pb.dirInfo.ioVRefNum = fn->fss.vRefNum;
915 pb.dirInfo.ioDrParID = fn->fss.parID;
916 pb.dirInfo.ioFDirIndex = -1;
918 pb.dirInfo.ioDrDirID = pb.dirInfo.ioDrParID;
919 err = PBGetCatInfoSync(&pb);
921 /* XXX Assume not A/UX */
922 newpath = smalloc(strlen(path) + dirname[0] + 2);
923 p2cstrcpy(newpath, dirname);
924 strcat(newpath, ":");
925 strcat(newpath, path);
928 } while (pb.dirInfo.ioDrDirID != fsRtDirID);
932 int filename_equal(Filename f1, Filename f2)
935 return f1.fss.vRefNum == f2.fss.vRefNum &&
936 f1.fss.parID == f2.fss.parID &&
937 f1.fss.name[0] == f2.fss.name[0] &&
938 memcmp(f1.fss.name + 1, f2.fss.name + 1, f1.fss.name[0]) == 0;
941 int filename_is_null(Filename fn)
944 return fn.fss.vRefNum == 0 && fn.fss.parID == 0 && fn.fss.name[0] == 0;
947 FILE *f_open(Filename fn, char const *mode)
954 HGetVol(NULL, &savevol, &savedir);
955 if (HSetVol(NULL, fn.fss.vRefNum, fn.fss.parID) == noErr) {
956 p2cstrcpy(tmp, fn.fss.name);
957 ret = fopen(tmp, mode);
960 HSetVol(NULL, savevol, savedir);
966 * c-file-style: "simon"