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