]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - mac/mac.c
Implement Simon's suggestion of moving DEFAULT_PROTOCOL into a per-backend-
[PuTTY.git] / mac / mac.c
1 /* $Id: mac.c,v 1.30 2003/01/15 20:47:50 jacob Exp $ */
2 /*
3  * Copyright (c) 1999 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 <Quickdraw.h>
33 #include <Fonts.h>
34 #include <MacWindows.h>
35 #include <Menus.h>
36 #include <TextEdit.h>
37 #include <Appearance.h>
38 #include <CodeFragments.h>
39 #include <Dialogs.h>
40 #include <Devices.h>
41 #include <DiskInit.h>
42 #include <Gestalt.h>
43 #include <LowMem.h>
44 #include <Resources.h>
45 #include <Script.h>
46 #include <TextCommon.h>
47 #include <ToolUtils.h>
48 #include <UnicodeConverter.h>
49
50 #include <assert.h>
51 #include <limits.h>
52 #include <stdarg.h>
53 #include <stdlib.h>             /* putty.h needs size_t */
54 #include <stdio.h>              /* for vsprintf */
55
56 #define PUTTY_DO_GLOBALS
57
58 #include "macresid.h"
59 #include "putty.h"
60 #include "ssh.h"
61 #include "mac.h"
62
63 QDGlobals qd;
64
65 Session *sesslist;
66
67 static int cold = 1;
68 struct mac_gestalts mac_gestalts;
69
70 static void mac_startup(void);
71 static void mac_eventloop(void);
72 #pragma noreturn (mac_eventloop)
73 static void mac_event(EventRecord *);
74 static void mac_contentclick(WindowPtr, EventRecord *);
75 static void mac_growwindow(WindowPtr, EventRecord *);
76 static void mac_activatewindow(WindowPtr, EventRecord *);
77 static void mac_activateabout(WindowPtr, EventRecord *);
78 static void mac_updatewindow(WindowPtr);
79 static void mac_updatelicence(WindowPtr);
80 static void mac_keypress(EventRecord *);
81 static int mac_windowtype(WindowPtr);
82 static void mac_menucommand(long);
83 static void mac_openabout(void);
84 static void mac_openlicence(void);
85 static void mac_adjustcursor(RgnHandle);
86 static void mac_adjustmenus(void);
87 static void mac_closewindow(WindowPtr);
88 static void mac_zoomwindow(WindowPtr, short);
89 static void mac_shutdown(void);
90 #pragma noreturn (cleanup_exit)
91
92 struct mac_windows {
93     WindowPtr about;
94     WindowPtr licence;
95 };
96
97 struct mac_windows windows;
98
99 int main (int argc, char **argv) {
100
101     mac_startup();
102     mac_eventloop();
103 }
104
105 #pragma noreturn (main)
106
107 static void mac_startup(void) {
108     Handle menuBar;
109     TECInfoHandle ti;
110
111     /* Init Memory Manager */
112     MaxApplZone();
113     /* Init QuickDraw */
114     InitGraf(&qd.thePort);
115     /* Init Font Manager */
116     InitFonts();
117     /* Init Window Manager */
118     InitWindows();
119     /* Init Menu Manager */
120     InitMenus();
121     /* Init TextEdit */
122     TEInit();
123     /* Init Dialog Manager */
124     InitDialogs(NULL);
125     cold = 0;
126     
127     /* Get base system version (only used if there's no better selector) */
128     if (Gestalt(gestaltSystemVersion, &mac_gestalts.sysvers) != noErr ||
129         (mac_gestalts.sysvers &= 0xffff) < 0x700)
130         fatalbox("PuTTY requires System 7 or newer");
131     /* Find out if we've got Color Quickdraw */
132     if (Gestalt(gestaltQuickdrawVersion, &mac_gestalts.qdvers) != noErr)
133         mac_gestalts.qdvers = gestaltOriginalQD;
134     /* ... and the Appearance Manager? */
135     if (Gestalt(gestaltAppearanceVersion, &mac_gestalts.apprvers) != noErr)
136         if (Gestalt(gestaltAppearanceAttr, NULL) == noErr)
137             mac_gestalts.apprvers = 0x0100;
138         else
139             mac_gestalts.apprvers = 0;
140 #if TARGET_RT_MAC_CFM
141     /* Paranoia: Did we manage to pull in AppearanceLib? */
142     if (&RegisterAppearanceClient == kUnresolvedCFragSymbolAddress)
143         mac_gestalts.apprvers = 0;
144 #endif
145 #if TARGET_CPU_68K
146     mac_gestalts.cntlattr = 0;
147     mac_gestalts.windattr = 0;
148 #else
149     /* Mac OS 8.5 Control Manager (proportional scrollbars)? */
150     if (Gestalt(gestaltControlMgrAttr, &mac_gestalts.cntlattr) != noErr ||
151         &SetControlViewSize == kUnresolvedCFragSymbolAddress)
152         mac_gestalts.cntlattr = 0;
153     /* Mac OS 8.5 Window Manager? */
154     if (Gestalt(gestaltWindowMgrAttr, &mac_gestalts.windattr) != noErr ||
155         &SetWindowContentColor == kUnresolvedCFragSymbolAddress)
156         mac_gestalts.windattr = 0;
157 #endif
158     /* Text Encoding Conversion Manager? */
159     if (
160 #if TARGET_RT_MAC_CFM
161         &TECGetInfo == kUnresolvedCFragSymbolAddress ||
162 #else
163         InitializeUnicodeConverter(NULL) != noErr ||
164 #endif
165         TECGetInfo(&ti) != noErr)
166         mac_gestalts.encvvers = 0;
167     else {
168         mac_gestalts.encvvers = (*ti)->tecVersion;
169         mac_gestalts.uncvattr = (*ti)->tecUnicodeConverterFeatures;
170         DisposeHandle((Handle)ti);
171     }
172     /* OpenTransport? */
173     if (Gestalt(gestaltOpenTpt, &mac_gestalts.otptattr) != noErr ||
174         (mac_gestalts.otptattr & gestaltOpenTptTCPPresentMask) == 0 ||
175         ot_init() != noErr)
176         mac_gestalts.otptattr = 0;
177     if (mac_gestalts.otptattr == 0) {
178         /* MacTCP? */
179         if (Gestalt(FOUR_CHAR_CODE('mtcp'), &mac_gestalts.mtcpvers) != noErr)
180             mac_gestalts.mtcpvers = 0;
181         if (mac_gestalts.mtcpvers > 0) {
182             if (mactcp_init() != noErr)
183                 mac_gestalts.mtcpvers = 0;
184         }
185     } else
186         mac_gestalts.mtcpvers = 0;
187
188     /* We've been tested with the Appearance Manager */
189     if (mac_gestalts.apprvers != 0)
190         RegisterAppearanceClient();
191
192     menuBar = GetNewMBar(128);
193     if (menuBar == NULL)
194         fatalbox("Unable to create menu bar.");
195     SetMenuBar(menuBar);
196     AppendResMenu(GetMenuHandle(mApple), 'DRVR');
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         default_port = 0; /* illegal */
207         int i;
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     {
217         short vol;
218         long dirid;
219
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);
225         }
226     }
227 }
228
229 static void mac_eventloop(void) {
230     Boolean gotevent;
231     EventRecord event;
232     RgnHandle cursrgn;
233
234     cursrgn = NewRgn();
235     for (;;) {
236         mac_adjustcursor(cursrgn);
237         gotevent = WaitNextEvent(everyEvent, &event, LONG_MAX, cursrgn);
238         mac_adjustcursor(cursrgn);
239         if (gotevent)
240             mac_event(&event);
241         if (mac_gestalts.mtcpvers != 0)
242             mactcp_poll();
243         if (mac_gestalts.otptattr != 0)
244             ot_poll();
245         mac_pollterm();
246     }
247     DisposeRgn(cursrgn);
248 }
249
250 static void mac_event(EventRecord *event) {
251     short part;
252     WindowPtr window;
253     Point pt;
254
255     switch (event->what) {
256       case mouseDown:
257         part = FindWindow(event->where, &window);
258         switch (part) {
259           case inMenuBar:
260             mac_adjustmenus();
261             mac_menucommand(MenuSelect(event->where));
262             break;
263           case inSysWindow:
264             SystemClick(event, window);
265             break;
266           case inContent:
267             if (window != FrontWindow())
268                 /* XXX: check for movable modal dboxes? */
269                 SelectWindow(window);
270             else
271                 mac_contentclick(window, event);
272             break;
273           case inGoAway:
274             if (TrackGoAway(window, event->where))
275                 mac_closewindow(window);
276             break;
277           case inDrag:
278             /* XXX: moveable modal check? */
279             DragWindow(window, event->where, &qd.screenBits.bounds);
280             break;
281           case inGrow:
282             mac_growwindow(window, event);
283             break;
284           case inZoomIn:
285           case inZoomOut:
286             if (TrackBox(window, event->where, part))
287                 mac_zoomwindow(window, part);
288             break;
289         }
290         break;
291       case keyDown:
292       case autoKey:
293         mac_keypress(event);
294         break;
295       case activateEvt:
296         mac_activatewindow((WindowPtr)event->message, event);
297         break;
298       case updateEvt:
299         mac_updatewindow((WindowPtr)event->message);
300         break;
301       case diskEvt:
302         if (HiWord(event->message) != noErr) {
303             SetPt(&pt, 120, 120);
304             DIBadMount(pt, event->message);
305         }
306         break;
307     }
308 }
309
310 static void mac_contentclick(WindowPtr window, EventRecord *event) {
311     short item;
312
313     switch (mac_windowtype(window)) {
314       case wTerminal:
315         mac_clickterm(window, event);
316         break;
317       case wAbout:
318         if (DialogSelect(event, &window, &item))
319             switch (item) {
320               case wiAboutLicence:
321                 mac_openlicence();
322                 break;
323             }
324         break;
325       case wSettings:
326         mac_clickdlg(window, event);
327         break;
328     }
329 }
330
331 static void mac_growwindow(WindowPtr window, EventRecord *event) {
332
333     switch (mac_windowtype(window)) {
334       case wTerminal:
335         mac_growterm(window, event);
336     }
337 }
338
339 static void mac_activatewindow(WindowPtr window, EventRecord *event) {
340     int active;
341
342     active = (event->modifiers & activeFlag) != 0;
343     mac_adjustmenus();
344     switch (mac_windowtype(window)) {
345       case wTerminal:
346         mac_activateterm(window, active);
347         break;
348       case wSettings:
349         mac_activatedlg(window, event);
350         break;
351       case wAbout:
352         mac_activateabout(window, event);
353         break;
354     }
355 }
356
357 static void mac_activateabout(WindowPtr window, EventRecord *event) {
358     DialogItemType itemtype;
359     Handle itemhandle;
360     short item;
361     Rect itemrect;
362     int active;
363
364     active = (event->modifiers & activeFlag) != 0;
365     GetDialogItem(window, wiAboutLicence, &itemtype, &itemhandle, &itemrect);
366     HiliteControl((ControlHandle)itemhandle, active ? 0 : 255);
367     DialogSelect(event, &window, &item);
368 }
369
370 static void mac_updatewindow(WindowPtr window) {
371
372     switch (mac_windowtype(window)) {
373       case wTerminal:
374         mac_updateterm(window);
375         break;
376       case wAbout:
377       case wSettings:
378         BeginUpdate(window);
379         UpdateDialog(window, window->visRgn);
380         EndUpdate(window);
381         break;
382       case wLicence:
383         mac_updatelicence(window);
384         break;
385     }
386 }
387
388 static void mac_updatelicence(WindowPtr window)
389 {
390     Handle h;
391     int len;
392     long fondsize;
393
394     SetPort(window);
395     BeginUpdate(window);
396     fondsize = GetScriptVariable(smRoman, smScriptSmallFondSize);
397     TextFont(HiWord(fondsize));
398     TextSize(LoWord(fondsize));
399     h = Get1Resource('TEXT', wLicence);
400     len = GetResourceSizeOnDisk(h);
401     if (h != NULL) {
402         HLock(h);
403         TETextBox(*h, len, &window->portRect, teFlushDefault);
404         HUnlock(h);
405     }
406     EndUpdate(window);
407 }
408
409 /*
410  * Work out what kind of window we're dealing with.
411  * Concept shamelessly nicked from SurfWriter.
412  */
413 static int mac_windowtype(WindowPtr window) {
414     int kind;
415     long refcon;
416
417     if (window == NULL)
418         return wNone;
419     kind = ((WindowPeek)window)->windowKind;
420     if (kind < 0)
421         return wDA;
422     if (GetWVariant(window) == zoomDocProc)
423         return wTerminal;
424     refcon = GetWRefCon(window);
425     if (refcon < 1024)
426         return refcon;
427     else
428         return wSettings;
429 }
430
431 /*
432  * Handle a key press
433  */
434 static void mac_keypress(EventRecord *event) {
435     WindowPtr window;
436
437     window = FrontWindow();
438     /*
439      * Check for a command-key combination, but ignore it if it counts
440      * as a meta-key combination and we're in a terminal window.
441      */
442     if (event->what == keyDown && (event->modifiers & cmdKey) /*&&
443         !((event->modifiers & cfg.meta_modifiers) == cfg.meta_modifiers &&
444             mac_windowtype(window) == wTerminal)*/) {
445         mac_adjustmenus();
446         mac_menucommand(MenuKey(event->message & charCodeMask));
447     } else {
448         switch (mac_windowtype(window)) {
449           case wTerminal:
450             mac_keyterm(window, event);
451             break;
452         }
453     }       
454 }
455
456 static void mac_menucommand(long result) {
457     short menu, item;
458     Str255 da;
459     WindowPtr window;
460
461     menu = HiWord(result);
462     item = LoWord(result);
463     window = FrontWindow();
464     /* Things which do the same whatever window we're in. */
465     switch (menu) {
466       case mApple:
467         switch (item) {
468           case iAbout:
469             mac_openabout();
470             goto done;
471           default:
472             GetMenuItemText(GetMenuHandle(mApple), item, da);
473             OpenDeskAcc(da);
474             goto done;
475         }
476         break;
477       case mFile:
478         switch (item) {
479           case iNew:
480             mac_newsession();
481             goto done;
482           case iOpen:
483             mac_opensession();
484             goto done;
485           case iClose:
486             mac_closewindow(window);
487             goto done;
488           case iQuit:
489             cleanup_exit(0);
490             goto done;
491         }
492         break;
493     }
494     /* If we get here, handling is up to window-specific code. */
495     switch (mac_windowtype(window)) {
496       case wTerminal:
497         mac_menuterm(window, menu, item);
498         break;
499     }
500   done:
501     HiliteMenu(0);
502 }
503
504 static void mac_openabout(void) {
505     DialogItemType itemtype;
506     Handle item;
507     VersRecHndl vers;
508     Rect box;
509     StringPtr longvers;
510
511     if (windows.about)
512         SelectWindow(windows.about);
513     else {
514         windows.about = GetNewDialog(wAbout, NULL, (WindowPtr)-1);
515         vers = (VersRecHndl)Get1Resource('vers', 1);
516         if (vers != NULL && *vers != NULL) {
517             longvers = (*vers)->shortVersion + (*vers)->shortVersion[0] + 1;
518             GetDialogItem(windows.about, wiAboutVersion,
519                           &itemtype, &item, &box);
520             assert(itemtype & kStaticTextDialogItem);
521             SetDialogItemText(item, longvers);
522         }
523         ShowWindow(windows.about);
524     }
525 }
526
527 static void mac_openlicence(void) {
528
529     if (windows.licence)
530         SelectWindow(windows.licence);
531     else {
532         windows.licence = GetNewWindow(wLicence, NULL, (WindowPtr)-1);
533         ShowWindow(windows.licence);
534     }
535 }
536
537 static void mac_closewindow(WindowPtr window) {
538
539     switch (mac_windowtype(window)) {
540       case wDA:
541         CloseDeskAcc(((WindowPeek)window)->windowKind);
542         break;
543       case wTerminal:
544         /* FIXME: end session and stuff */
545         break;
546       case wAbout:
547         windows.about = NULL;
548         CloseWindow(window);
549         break;
550       case wLicence:
551         windows.licence = NULL;
552         CloseWindow(window);
553         break;
554       default:
555         CloseWindow(window);
556         break;
557     }
558 }
559
560 static void mac_zoomwindow(WindowPtr window, short part) {
561
562     /* FIXME: do something */
563 }
564
565 /*
566  * Make the menus look right before the user gets to see them.
567  */
568 static void mac_adjustmenus(void) {
569     WindowPtr window;
570     MenuHandle menu;
571
572     window = FrontWindow();
573     menu = GetMenuHandle(mApple);
574     EnableItem(menu, 0);
575     EnableItem(menu, iAbout);
576
577     menu = GetMenuHandle(mFile);
578     EnableItem(menu, 0);
579     EnableItem(menu, iNew);
580     if (window != NULL)
581         EnableItem(menu, iClose);
582     else
583         DisableItem(menu, iClose);
584     EnableItem(menu, iQuit);
585
586     switch (mac_windowtype(window)) {
587       case wTerminal:
588         mac_adjusttermmenus(window);
589         break;
590       default:
591         menu = GetMenuHandle(mEdit);
592         DisableItem(menu, 0);
593         break;
594     }
595     DrawMenuBar();
596 }
597
598 /*
599  * Make sure the right cursor's being displayed.
600  */
601 static void mac_adjustcursor(RgnHandle cursrgn) {
602     Point mouse;
603     WindowPtr window, front;
604     short part;
605
606     GetMouse(&mouse);
607     LocalToGlobal(&mouse);
608     part = FindWindow(mouse, &window);
609     front = FrontWindow();
610     if (part != inContent || window == NULL || window != front) {
611         /* Cursor isn't in the front window, so switch to arrow */
612         SetCursor(&qd.arrow);
613         SetRectRgn(cursrgn, SHRT_MIN, SHRT_MIN, SHRT_MAX, SHRT_MAX);
614         if (front != NULL)
615             DiffRgn(cursrgn, front->visRgn, cursrgn);
616     } else {
617         switch (mac_windowtype(window)) {
618           case wTerminal:
619             mac_adjusttermcursor(window, mouse, cursrgn);
620             break;
621           default:
622             SetCursor(&qd.arrow);
623             CopyRgn(window->visRgn, cursrgn);
624             break;
625         }
626     }
627 }
628
629 void cleanup_exit(int status)
630 {
631
632 #if !TARGET_RT_MAC_CFM
633     if (mac_gestalts.encvvers != 0)
634         TerminateUnicodeConverter();
635 #endif
636     sk_cleanup();
637     exit(status);
638 }
639
640 void fatalbox(char *fmt, ...) {
641     va_list ap;
642     Str255 stuff;
643     
644     va_start(ap, fmt);
645     /* We'd like stuff to be a Pascal string */
646     stuff[0] = vsprintf((char *)(&stuff[1]), fmt, ap);
647     va_end(ap);
648     ParamText(stuff, NULL, NULL, NULL);
649     StopAlert(128, NULL);
650     cleanup_exit(1);
651 }
652
653 void modalfatalbox(char *fmt, ...) {
654     va_list ap;
655     Str255 stuff;
656     
657     va_start(ap, fmt);
658     /* We'd like stuff to be a Pascal string */
659     stuff[0] = vsprintf((char *)(&stuff[1]), fmt, ap);
660     va_end(ap);
661     ParamText(stuff, NULL, NULL, NULL);
662     StopAlert(128, NULL);
663     cleanup_exit(1);
664 }
665
666 /* This should only kill the current session, not the whole application. */
667 void connection_fatal(void *fontend, char *fmt, ...) {
668     va_list ap;
669     Str255 stuff;
670     
671     va_start(ap, fmt);
672     /* We'd like stuff to be a Pascal string */
673     stuff[0] = vsprintf((char *)(&stuff[1]), fmt, ap);
674     va_end(ap);
675     ParamText(stuff, NULL, NULL, NULL);
676     StopAlert(128, NULL);
677     cleanup_exit(1);
678 }
679
680 /* Null SSH agent client -- never finds an agent. */
681
682 int agent_exists(void)
683 {
684
685     return FALSE;
686 }
687
688 void agent_query(void *in, int inlen, void **out, int *outlen)
689 {
690
691     *out = NULL;
692     *outlen = 0;
693 }
694
695 /* Temporary null routines for testing. */
696
697 void verify_ssh_host_key(void *frontend, char *host, int port, char *keytype,
698                          char *keystr, char *fingerprint)
699 {
700
701 }
702
703 void askcipher(void *frontend, char *ciphername, int cs)
704 {
705
706 }
707
708 void old_keyfile_warning(void)
709 {
710
711 }
712
713 char *platform_default_s(char const *name)
714 {
715     long smfs;
716     Str255 pname;
717     static char cname[256];
718
719     if (!strcmp(name, "Font")) {
720         smfs = GetScriptVariable(smSystemScript, smScriptMonoFondSize);
721         if (smfs == 0)
722             smfs = GetScriptVariable(smRoman, smScriptMonoFondSize);
723         if (smfs != 0) {
724             GetFontName(HiWord(smfs), pname);
725             if (pname[0] == 0)
726                 return "Monaco";
727             p2cstrcpy(cname, pname);
728             return cname;
729         } else
730             return "Monaco";
731     }
732     return NULL;
733 }
734
735 int platform_default_i(char const *name, int def)
736 {
737     long smfs;
738
739     if (!strcmp(name, "FontHeight")) {
740         smfs = GetScriptVariable(smSystemScript, smScriptMonoFondSize);
741         if (smfs == 0)
742             smfs = GetScriptVariable(smRoman, smScriptMonoFondSize);
743         if (smfs != 0)
744             return LoWord(smfs);
745         else
746             return 9;
747     }
748
749     /* Non-raw cut and paste of line-drawing chars works badly on the
750      * current Unix stub implementation of the Unicode functions.
751      * So I'm going to temporarily set the default to raw mode so
752      * that the failure mode isn't quite so drastically horrid.
753      * When Unicode comes in, this can all be put right. */
754     if (!strcmp(name, "RawCNP"))
755         return 1;
756     return def;
757 }
758
759 void platform_get_x11_auth(char *display, int *proto,
760                            unsigned char *data, int *datalen)
761 {
762     /* SGT: I have no idea whether Mac X servers need anything here. */
763 }
764
765 /*
766  * Local Variables:
767  * c-file-style: "simon"
768  * End:
769  */