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