]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - mac/mac.c
Fix a couple of stupid typos in the session-saving code.
[PuTTY.git] / mac / mac.c
1 /* $Id: mac.c,v 1.53 2003/03/01 15:12:03 ben Exp $ */
2 /*
3  * Copyright (c) 1999, 2003 Ben Harris
4  * All rights reserved.
5  *
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
13  * conditions:
14  * 
15  * The above copyright notice and this permission notice shall be
16  * included in all copies or substantial portions of the Software.
17  * 
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
25  * SOFTWARE.
26  */
27 /*
28  * mac.c -- miscellaneous Mac-specific routines
29  */
30
31 #include <MacTypes.h>
32 #include <AEDataModel.h>
33 #include <AppleEvents.h>
34 #include <Quickdraw.h>
35 #include <Fonts.h>
36 #include <MacWindows.h>
37 #include <Menus.h>
38 #include <TextEdit.h>
39 #include <Appearance.h>
40 #include <CodeFragments.h>
41 #include <Dialogs.h>
42 #include <Devices.h>
43 #include <DiskInit.h>
44 #include <Gestalt.h>
45 #include <LowMem.h>
46 #include <Navigation.h>
47 #include <Resources.h>
48 #include <Script.h>
49 #include <TextCommon.h>
50 #include <ToolUtils.h>
51 #include <UnicodeConverter.h>
52
53 #include <assert.h>
54 #include <limits.h>
55 #include <stdarg.h>
56 #include <stdlib.h>             /* putty.h needs size_t */
57 #include <stdio.h>              /* for vsprintf */
58
59 #define PUTTY_DO_GLOBALS
60
61 #include "macresid.h"
62 #include "putty.h"
63 #include "ssh.h"
64 #include "mac.h"
65
66 Session *sesslist;
67
68 static int cold = 1;
69 static int borednow = FALSE;
70 struct mac_gestalts mac_gestalts;
71 UInt32 sleeptime;
72
73 static void mac_startup(void);
74 static void mac_eventloop(void);
75 #pragma noreturn (mac_eventloop)
76 static void mac_event(EventRecord *);
77 static void mac_contentclick(WindowPtr, EventRecord *);
78 static void mac_growwindow(WindowPtr, EventRecord *);
79 static void mac_activatewindow(WindowPtr, EventRecord *);
80 static void mac_suspendresume(EventRecord *);
81 static void mac_activateabout(WindowPtr, EventRecord *);
82 static void mac_updatewindow(WindowPtr);
83 static void mac_updatelicence(WindowPtr);
84 static void mac_keypress(EventRecord *);
85 static int mac_windowtype(WindowPtr);
86 static void mac_menucommand(long);
87 static void mac_openlicence(void);
88 static void mac_adjustcursor(RgnHandle);
89 static void mac_adjustmenus(void);
90 static void mac_closewindow(WindowPtr);
91 static void mac_zoomwindow(WindowPtr, short);
92 #pragma noreturn (cleanup_exit)
93
94 struct mac_windows {
95     WindowPtr about;
96     WindowPtr licence;
97 };
98
99 struct mac_windows windows;
100
101 int main (int argc, char **argv) {
102
103     mac_startup();
104     mac_eventloop();
105 }
106
107 #pragma noreturn (main)
108
109 static void mac_startup(void) {
110     Handle menuBar;
111     TECInfoHandle ti;
112
113 #if !TARGET_API_MAC_CARBON
114     /* Init Memory Manager */
115     MaxApplZone();
116     /* Init QuickDraw */
117     InitGraf(&qd.thePort);
118     /* Init Font Manager */
119     InitFonts();
120     /* Init Window Manager */
121     InitWindows();
122     /* Init Menu Manager */
123     InitMenus();
124     /* Init TextEdit */
125     TEInit();
126     /* Init Dialog Manager */
127     InitDialogs(NULL);
128 #endif
129     cold = 0;
130     
131     /* Get base system version (only used if there's no better selector) */
132     if (Gestalt(gestaltSystemVersion, &mac_gestalts.sysvers) != noErr ||
133         (mac_gestalts.sysvers &= 0xffff) < 0x700)
134         fatalbox("PuTTY requires System 7 or newer");
135     /* Find out if we've got Color Quickdraw */
136     if (Gestalt(gestaltQuickdrawVersion, &mac_gestalts.qdvers) != noErr)
137         mac_gestalts.qdvers = gestaltOriginalQD;
138     /* ... and the Appearance Manager? */
139     if (Gestalt(gestaltAppearanceVersion, &mac_gestalts.apprvers) != noErr)
140         if (Gestalt(gestaltAppearanceAttr, NULL) == noErr)
141             mac_gestalts.apprvers = 0x0100;
142         else
143             mac_gestalts.apprvers = 0;
144 #if TARGET_RT_MAC_CFM
145     /* Paranoia: Did we manage to pull in AppearanceLib? */
146     if (&RegisterAppearanceClient == kUnresolvedCFragSymbolAddress)
147         mac_gestalts.apprvers = 0;
148 #endif
149 #if TARGET_CPU_68K
150     mac_gestalts.cntlattr = 0;
151     mac_gestalts.windattr = 0;
152 #else
153     /* Mac OS 8.5 Control Manager (proportional scrollbars)? */
154     if (Gestalt(gestaltControlMgrAttr, &mac_gestalts.cntlattr) != noErr ||
155         &SetControlViewSize == kUnresolvedCFragSymbolAddress)
156         mac_gestalts.cntlattr = 0;
157     /* Mac OS 8.5 Window Manager? */
158     if (Gestalt(gestaltWindowMgrAttr, &mac_gestalts.windattr) != noErr ||
159         &SetWindowContentColor == kUnresolvedCFragSymbolAddress)
160         mac_gestalts.windattr = 0;
161     /* Mac OS 8.5 Menu Manager? */
162     if (Gestalt(gestaltMenuMgrAttr, &mac_gestalts.menuattr) != noErr)
163         mac_gestalts.menuattr = 0;
164 #endif
165     /* Text Encoding Conversion Manager? */
166     if (
167 #if TARGET_RT_MAC_CFM
168         &TECGetInfo == kUnresolvedCFragSymbolAddress ||
169 #else
170         InitializeUnicodeConverter(NULL) != noErr ||
171 #endif
172         TECGetInfo(&ti) != noErr)
173         mac_gestalts.encvvers = 0;
174     else {
175         mac_gestalts.encvvers = (*ti)->tecVersion;
176         mac_gestalts.uncvattr = (*ti)->tecUnicodeConverterFeatures;
177         DisposeHandle((Handle)ti);
178     }
179     /* Navigation Services? */
180     if (NavServicesAvailable())
181         mac_gestalts.navsvers = NavLibraryVersion();
182     else
183         mac_gestalts.navsvers = 0;
184
185     sk_init();
186
187     /* We've been tested with the Appearance Manager */
188     if (mac_gestalts.apprvers != 0)
189         RegisterAppearanceClient();
190
191     menuBar = GetNewMBar(128);
192     if (menuBar == NULL)
193         fatalbox("Unable to create menu bar.");
194     SetMenuBar(menuBar);
195     AppendResMenu(GetMenuHandle(mApple), 'DRVR');
196     if (mac_gestalts.menuattr & gestaltMenuMgrAquaLayoutMask)
197         DeleteMenuItem(GetMenuHandle(mFile), iQuit);
198     mac_adjustmenus();
199     DrawMenuBar();
200     InitCursor();
201     windows.about = NULL;
202     windows.licence = NULL;
203
204     default_protocol = be_default_protocol;
205     /* Find the appropriate default port. */
206     {
207         int i;
208         default_port = 0; /* illegal */
209         for (i = 0; backends[i].backend != NULL; i++)
210             if (backends[i].protocol == default_protocol) {
211                 default_port = backends[i].backend->default_port;
212                 break;
213             }
214     }
215     flags = FLAG_INTERACTIVE;
216
217 #if !TARGET_API_MAC_CARBON
218     {
219         short vol;
220         long dirid;
221
222         /* Set the default directory for loading and saving settings. */
223         /* XXX Should we create it? */
224         if (get_session_dir(FALSE, &vol, &dirid) == noErr) {
225             LMSetSFSaveDisk(-vol);
226             LMSetCurDirStore(dirid);
227         }
228     }
229 #endif
230
231     /* Install Apple Event handlers. */
232     AEInstallEventHandler(kCoreEventClass, kAEOpenApplication,
233                           NewAEEventHandlerUPP(&mac_aevt_oapp), 0, FALSE);
234     AEInstallEventHandler(kCoreEventClass, kAEOpenDocuments,
235                           NewAEEventHandlerUPP(&mac_aevt_odoc), 0, FALSE);
236     AEInstallEventHandler(kCoreEventClass, kAEPrintDocuments,
237                           NewAEEventHandlerUPP(&mac_aevt_pdoc), 0, FALSE);
238     AEInstallEventHandler(kCoreEventClass, kAEQuitApplication,
239                           NewAEEventHandlerUPP(&mac_aevt_quit), 0, FALSE);
240 }
241
242 static void mac_eventloop(void) {
243     Boolean gotevent;
244     EventRecord event;
245     RgnHandle cursrgn;
246
247     cursrgn = NewRgn();
248     sleeptime = 0;
249     for (;;) {
250         mac_adjustcursor(cursrgn);
251         gotevent = WaitNextEvent(everyEvent, &event, sleeptime, cursrgn);
252         /*
253          * XXX For now, limit sleep time to 1/10 s to work around
254          * wake-before-sleep race in MacTCP code.
255          */
256         sleeptime = 6;
257         mac_adjustcursor(cursrgn);
258         if (gotevent) {
259             /* Ensure we get a null event when the real ones run out. */
260             sleeptime = 0;
261             mac_event(&event);
262             if (borednow)
263                 cleanup_exit(0);
264         }
265         sk_poll();
266         if (!gotevent)
267             mac_pollterm();
268     }
269     DisposeRgn(cursrgn);
270 }
271
272 static void mac_event(EventRecord *event) {
273     short part;
274     WindowPtr window;
275
276     switch (event->what) {
277       case mouseDown:
278         part = FindWindow(event->where, &window);
279         switch (part) {
280           case inMenuBar:
281             mac_adjustmenus();
282             mac_menucommand(MenuSelect(event->where));
283             break;
284 #if !TARGET_API_MAC_CARBON
285           case inSysWindow:
286             SystemClick(event, window);
287             break;
288 #endif
289           case inContent:
290             if (window != FrontWindow())
291                 /* XXX: check for movable modal dboxes? */
292                 SelectWindow(window);
293             else
294                 mac_contentclick(window, event);
295             break;
296           case inGoAway:
297             if (TrackGoAway(window, event->where))
298                 mac_closewindow(window);
299             break;
300           case inDrag:
301             /* XXX: moveable modal check? */
302 #if TARGET_API_MAC_CARBON
303             {
304                 BitMap screenBits;
305
306                 GetQDGlobalsScreenBits(&screenBits);
307                 DragWindow(window, event->where, &screenBits.bounds);
308             }
309 #else
310             DragWindow(window, event->where, &qd.screenBits.bounds);
311 #endif
312             break;
313           case inGrow:
314             mac_growwindow(window, event);
315             break;
316           case inZoomIn:
317           case inZoomOut:
318             if (TrackBox(window, event->where, part))
319                 mac_zoomwindow(window, part);
320             break;
321         }
322         break;
323       case keyDown:
324       case autoKey:
325         mac_keypress(event);
326         break;
327       case activateEvt:
328         mac_activatewindow((WindowPtr)event->message, event);
329         break;
330       case updateEvt:
331         mac_updatewindow((WindowPtr)event->message);
332         break;
333 #if !TARGET_API_MAC_CARBON
334       case diskEvt:
335         if (HiWord(event->message) != noErr) {
336             Point pt;
337
338             SetPt(&pt, 120, 120);
339             DIBadMount(pt, event->message);
340         }
341         break;
342 #endif
343       case osEvt:
344         switch ((event->message & osEvtMessageMask) >> 24) {
345           case suspendResumeMessage:
346             mac_suspendresume(event);
347             break;
348         }
349         break;
350       case kHighLevelEvent:
351         AEProcessAppleEvent(event); /* errors? */
352         break;
353     }
354 }
355
356 static void mac_contentclick(WindowPtr window, EventRecord *event)
357 {
358
359     if (mac_wininfo(window)->click != NULL)
360         (*mac_wininfo(window)->click)(window, event);
361 }
362
363 static void mac_growwindow(WindowPtr window, EventRecord *event)
364 {
365
366     if (mac_wininfo(window)->grow != NULL)
367         (*mac_wininfo(window)->grow)(window, event);
368 }
369
370 static void mac_activatewindow(WindowPtr window, EventRecord *event)
371 {
372
373     mac_adjustmenus();
374     if (mac_wininfo(window)->activate != NULL)
375         (*mac_wininfo(window)->activate)(window, event);
376 }
377
378 static void mac_updatewindow(WindowPtr window)
379 {
380
381     if (mac_wininfo(window)->update != NULL)
382         (*mac_wininfo(window)->update)(window);
383 }
384
385 /*
386  * Work out what kind of window we're dealing with.
387  */
388 static int mac_windowtype(WindowPtr window)
389 {
390
391 #if !TARGET_API_MAC_CARBON
392     if (GetWindowKind(window) < 0)
393         return wDA;
394 #endif
395     return ((WinInfo *)GetWRefCon(window))->wtype;
396 }
397
398 /*
399  * Handle a key press
400  */
401 static void mac_keypress(EventRecord *event) {
402     WindowPtr window;
403
404     window = mac_frontwindow();
405     /*
406      * Check for a command-key combination, but ignore it if it counts
407      * as a meta-key combination and we're in a terminal window.
408      */
409     if (event->what == keyDown && (event->modifiers & cmdKey) /*&&
410         !((event->modifiers & cfg.meta_modifiers) == cfg.meta_modifiers &&
411             mac_windowtype(window) == wTerminal)*/) {
412         mac_adjustmenus();
413         mac_menucommand(MenuKey(event->message & charCodeMask));
414     } else {
415         if (window != NULL && mac_wininfo(window)->key != NULL)
416             (*mac_wininfo(window)->key)(window, event);
417     }       
418 }
419
420 static void mac_menucommand(long result) {
421     short menu, item;
422     WindowPtr window;
423 #if !TARGET_API_MAC_CARBON
424     Str255 da;
425 #endif
426
427     menu = HiWord(result);
428     item = LoWord(result);
429     window = mac_frontwindow();
430     /* Things which do the same whatever window we're in. */
431     switch (menu) {
432       case mApple:
433         switch (item) {
434           case iAbout:
435             mac_openabout();
436             goto done;
437 #if !TARGET_API_MAC_CARBON
438           default:
439             GetMenuItemText(GetMenuHandle(mApple), item, da);
440             OpenDeskAcc(da);
441             goto done;
442 #endif
443         }
444         break;
445       case mFile:
446         switch (item) {
447           case iNew:
448             mac_newsession();
449             goto done;
450           case iOpen:
451             mac_opensession();
452             goto done;
453           case iClose:
454             mac_closewindow(window);
455             goto done;
456           case iSave:
457             mac_savesession();
458             goto done;
459           case iSaveAs:
460             mac_savesessionas();
461             goto done;
462           case iDuplicate:
463             mac_dupsession();
464             goto done;
465           case iQuit:
466             cleanup_exit(0);
467             goto done;
468         }
469         break;
470     }
471     /* If we get here, handling is up to window-specific code. */
472     if (window != NULL && mac_wininfo(window)->menu != NULL)
473         (*mac_wininfo(window)->menu)(window, menu, item);
474
475   done:
476     HiliteMenu(0);
477 }
478
479 static void mac_closewindow(WindowPtr window) {
480
481     switch (mac_windowtype(window)) {
482 #if !TARGET_API_MAC_CARBON
483       case wDA:
484         CloseDeskAcc(GetWindowKind(window));
485         break;
486 #endif
487       default:
488         if (mac_wininfo(window)->close != NULL)
489             (*mac_wininfo(window)->close)(window);
490         break;
491     }
492 }
493
494 static void mac_suspendresume(EventRecord *event)
495 {
496     WindowPtr front;
497     EventRecord fakeevent;
498
499     /*
500      * We're called either before we're suspended or after we're
501      * resumed, so we're the front application at this point.
502      */
503     front = FrontWindow();
504     if (front != NULL) {
505         fakeevent.what = activateEvt;
506         fakeevent.message = (UInt32)front;
507         fakeevent.when = event->when;
508         fakeevent.where = event->where;
509         fakeevent.modifiers =
510             (event->message & resumeFlag) ? activeFlag : 0;
511         mac_activatewindow(front, &fakeevent);
512     }
513 }
514
515 static void mac_zoomwindow(WindowPtr window, short part) {
516
517     /* FIXME: do something */
518 }
519
520 /*
521  * Make the menus look right before the user gets to see them.
522  */
523 #if TARGET_API_MAC_CARBON
524 #define EnableItem EnableMenuItem
525 #define DisableItem DisableMenuItem
526 #endif
527 static void mac_adjustmenus(void) {
528     WindowPtr window;
529     MenuHandle menu;
530
531     window = mac_frontwindow();
532     menu = GetMenuHandle(mApple);
533     EnableItem(menu, 0);
534     EnableItem(menu, iAbout);
535
536     menu = GetMenuHandle(mFile);
537     EnableItem(menu, 0);
538     EnableItem(menu, iNew);
539     if (window != NULL)
540         EnableItem(menu, iClose);
541     else
542         DisableItem(menu, iClose);
543     EnableItem(menu, iQuit);
544
545     if (window != NULL && mac_wininfo(window)->adjustmenus != NULL)
546         (*mac_wininfo(window)->adjustmenus)(window);
547     else {
548         DisableItem(menu, iSave);
549         DisableItem(menu, iSaveAs);
550         DisableItem(menu, iDuplicate);
551         menu = GetMenuHandle(mEdit);
552         DisableItem(menu, 0);
553         menu = GetMenuHandle(mWindow);
554         DisableItem(menu, 0); /* Until we get more than 1 item on it. */
555     }
556     DrawMenuBar();
557 }
558
559 /*
560  * Make sure the right cursor's being displayed.
561  */
562 static void mac_adjustcursor(RgnHandle cursrgn) {
563     Point mouse;
564     WindowPtr window, front;
565     short part;
566 #if TARGET_API_MAC_CARBON
567     Cursor arrow;
568     RgnHandle visrgn;
569 #endif
570
571     GetMouse(&mouse);
572     LocalToGlobal(&mouse);
573     part = FindWindow(mouse, &window);
574     front = FrontWindow();
575     if (part != inContent || window == NULL || window != front) {
576         /* Cursor isn't in the front window, so switch to arrow */
577 #if TARGET_API_MAC_CARBON
578         GetQDGlobalsArrow(&arrow);
579         SetCursor(&arrow);
580 #else
581         SetCursor(&qd.arrow);
582 #endif
583         SetRectRgn(cursrgn, SHRT_MIN, SHRT_MIN, SHRT_MAX, SHRT_MAX);
584         if (front != NULL) {
585 #if TARGET_API_MAC_CARBON
586             visrgn = NewRgn();
587             GetPortVisibleRegion(GetWindowPort(front), visrgn);
588             DiffRgn(cursrgn, visrgn, cursrgn);
589             DisposeRgn(visrgn);
590 #else
591             DiffRgn(cursrgn, front->visRgn, cursrgn);
592 #endif
593         }
594     } else {
595         if (mac_wininfo(window)->adjustcursor != NULL)
596             (*mac_wininfo(window)->adjustcursor)(window, mouse, cursrgn);
597         else {
598 #if TARGET_API_MAC_CARBON
599             GetQDGlobalsArrow(&arrow);
600             SetCursor(&arrow);
601             GetPortVisibleRegion(GetWindowPort(window), cursrgn);
602 #else
603             SetCursor(&qd.arrow);
604             CopyRgn(window->visRgn, cursrgn);
605 #endif
606         }
607     }
608 }
609
610 pascal OSErr mac_aevt_quit(const AppleEvent *req, AppleEvent *reply,
611                                   long refcon)
612 {
613     DescType type;
614     Size size;
615
616     if (AEGetAttributePtr(req, keyMissedKeywordAttr, typeWildCard,
617                           &type, NULL, 0, &size) == noErr)
618         return errAEParamMissed;
619
620     borednow = 1;
621     return noErr;
622 }
623
624 void cleanup_exit(int status)
625 {
626
627 #if !TARGET_RT_MAC_CFM
628     if (mac_gestalts.encvvers != 0)
629         TerminateUnicodeConverter();
630 #endif
631     sk_cleanup();
632     exit(status);
633 }
634
635 /* This should only kill the current session, not the whole application. */
636 void connection_fatal(void *fontend, char *fmt, ...) {
637     va_list ap;
638     Str255 stuff;
639     
640     va_start(ap, fmt);
641     /* We'd like stuff to be a Pascal string */
642     stuff[0] = vsprintf((char *)(&stuff[1]), fmt, ap);
643     va_end(ap);
644     ParamText(stuff, NULL, NULL, NULL);
645     StopAlert(128, NULL);
646     cleanup_exit(1);
647 }
648
649 /* Null SSH agent client -- never finds an agent. */
650
651 int agent_exists(void)
652 {
653
654     return FALSE;
655 }
656
657 void agent_query(void *in, int inlen, void **out, int *outlen)
658 {
659
660     *out = NULL;
661     *outlen = 0;
662 }
663
664 /* Temporary null routines for testing. */
665
666 void verify_ssh_host_key(void *frontend, char *host, int port, char *keytype,
667                          char *keystr, char *fingerprint)
668 {
669
670 }
671
672 void askcipher(void *frontend, char *ciphername, int cs)
673 {
674
675 }
676
677 void old_keyfile_warning(void)
678 {
679
680 }
681
682 FontSpec platform_default_fontspec(char const *name)
683 {
684     FontSpec ret;
685     long smfs;
686
687     if (!strcmp(name, "Font")) {
688         smfs = GetScriptVariable(smSystemScript, smScriptMonoFondSize);
689         if (smfs == 0)
690             smfs = GetScriptVariable(smRoman, smScriptMonoFondSize);
691         if (smfs != 0) {
692             GetFontName(HiWord(smfs), ret.name);
693             if (ret.name[0] == 0)
694                 memcpy(ret.name, "\pMonaco", 7);
695             ret.size = LoWord(smfs);
696         } else {
697             memcpy(ret.name, "\pMonaco", 7);
698             ret.size = 9;
699         }
700         ret.face = 0;
701     } else {
702         ret.name[0] = 0;
703     }
704
705     return ret;
706 }
707
708 Filename platform_default_filename(const char *name)
709 {
710     Filename ret;
711     if (!strcmp(name, "LogFileName"))
712         FSMakeFSSpec(0, 0, "\pputty.log", &ret.fss);
713     else
714         memset(&ret, 0, sizeof(ret));
715     return ret;
716 }
717
718 char *platform_default_s(char const *name)
719 {
720     return NULL;
721 }
722
723 int platform_default_i(char const *name, int def)
724 {
725
726     /* Non-raw cut and paste of line-drawing chars works badly on the
727      * current Unix stub implementation of the Unicode functions.
728      * So I'm going to temporarily set the default to raw mode so
729      * that the failure mode isn't quite so drastically horrid.
730      * When Unicode comes in, this can all be put right. */
731     if (!strcmp(name, "RawCNP"))
732         return 1;
733     return def;
734 }
735
736 void platform_get_x11_auth(char *display, int *proto,
737                            unsigned char *data, int *datalen)
738 {
739     /* SGT: I have no idea whether Mac X servers need anything here. */
740 }
741
742 /*
743  * Local Variables:
744  * c-file-style: "simon"
745  * End:
746  */