1 /* Unix emulation routines for GNU Emacs on the Mac OS.
2 Copyright (C) 2000, 2001, 2002, 2003, 2004,
3 2005, 2006 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs; see the file COPYING. If not, write to
19 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
20 Boston, MA 02110-1301, USA. */
22 /* Contributed by Andrew Choi (akochoi@mac.com). */
35 #include "sysselect.h"
36 #include "blockinput.h"
42 #if !TARGET_API_MAC_CARBON
45 #include <TextUtils.h>
47 #include <Resources.h>
52 #include <AppleScript.h>
55 #include <Processes.h>
57 #include <MacLocales.h>
59 #endif /* not TARGET_API_MAC_CARBON */
63 #include <sys/types.h>
67 #include <sys/param.h>
73 /* The system script code. */
74 static int mac_system_script_code
;
76 /* The system locale identifier string. */
77 static Lisp_Object Vmac_system_locale
;
79 /* An instance of the AppleScript component. */
80 static ComponentInstance as_scripting_component
;
81 /* The single script context used for all script executions. */
82 static OSAID as_script_context
;
85 static OSErr posix_pathname_to_fsspec
P_ ((const char *, FSSpec
*));
86 static OSErr fsspec_to_posix_pathname
P_ ((const FSSpec
*, char *, int));
89 /* When converting from Mac to Unix pathnames, /'s in folder names are
90 converted to :'s. This function, used in copying folder names,
91 performs a strncat and converts all character a to b in the copy of
92 the string s2 appended to the end of s1. */
95 string_cat_and_replace (char *s1
, const char *s2
, int n
, char a
, char b
)
103 for (i
= 0; i
< l2
; i
++)
112 /* Convert a Mac pathname to Posix form. A Mac full pathname is one
113 that does not begin with a ':' and contains at least one ':'. A Mac
114 full pathname causes a '/' to be prepended to the Posix pathname.
115 The algorithm for the rest of the pathname is as follows:
116 For each segment between two ':',
117 if it is non-null, copy as is and then add a '/' at the end,
118 otherwise, insert a "../" into the Posix pathname.
119 Returns 1 if successful; 0 if fails. */
122 mac_to_posix_pathname (const char *mfn
, char *ufn
, int ufnbuflen
)
124 const char *p
, *q
, *pe
;
131 p
= strchr (mfn
, ':');
132 if (p
!= 0 && p
!= mfn
) /* full pathname */
139 pe
= mfn
+ strlen (mfn
);
146 { /* two consecutive ':' */
147 if (strlen (ufn
) + 3 >= ufnbuflen
)
153 if (strlen (ufn
) + (q
- p
) + 1 >= ufnbuflen
)
155 string_cat_and_replace (ufn
, p
, q
- p
, '/', ':');
162 if (strlen (ufn
) + (pe
- p
) >= ufnbuflen
)
164 string_cat_and_replace (ufn
, p
, pe
- p
, '/', ':');
165 /* no separator for last one */
174 extern char *get_temp_dir_name ();
177 /* Convert a Posix pathname to Mac form. Approximately reverse of the
178 above in algorithm. */
181 posix_to_mac_pathname (const char *ufn
, char *mfn
, int mfnbuflen
)
183 const char *p
, *q
, *pe
;
184 char expanded_pathname
[MAXPATHLEN
+1];
193 /* Check for and handle volume names. Last comparison: strangely
194 somewhere "/.emacs" is passed. A temporary fix for now. */
195 if (*p
== '/' && strchr (p
+1, '/') == NULL
&& strcmp (p
, "/.emacs") != 0)
197 if (strlen (p
) + 1 > mfnbuflen
)
204 /* expand to emacs dir found by init_emacs_passwd_dir */
205 if (strncmp (p
, "~emacs/", 7) == 0)
207 struct passwd
*pw
= getpwnam ("emacs");
209 if (strlen (pw
->pw_dir
) + strlen (p
) > MAXPATHLEN
)
211 strcpy (expanded_pathname
, pw
->pw_dir
);
212 strcat (expanded_pathname
, p
);
213 p
= expanded_pathname
;
214 /* now p points to the pathname with emacs dir prefix */
216 else if (strncmp (p
, "/tmp/", 5) == 0)
218 char *t
= get_temp_dir_name ();
220 if (strlen (t
) + strlen (p
) > MAXPATHLEN
)
222 strcpy (expanded_pathname
, t
);
223 strcat (expanded_pathname
, p
);
224 p
= expanded_pathname
;
225 /* now p points to the pathname with emacs dir prefix */
227 else if (*p
!= '/') /* relative pathname */
239 if (q
- p
== 2 && *p
== '.' && *(p
+1) == '.')
241 if (strlen (mfn
) + 1 >= mfnbuflen
)
247 if (strlen (mfn
) + (q
- p
) + 1 >= mfnbuflen
)
249 string_cat_and_replace (mfn
, p
, q
- p
, ':', '/');
256 if (strlen (mfn
) + (pe
- p
) >= mfnbuflen
)
258 string_cat_and_replace (mfn
, p
, pe
- p
, ':', '/');
267 /***********************************************************************
268 Conversions on Apple event objects
269 ***********************************************************************/
271 static Lisp_Object Qundecoded_file_name
;
278 {{keyTransactionIDAttr
, "transaction-id"},
279 {keyReturnIDAttr
, "return-id"},
280 {keyEventClassAttr
, "event-class"},
281 {keyEventIDAttr
, "event-id"},
282 {keyAddressAttr
, "address"},
283 {keyOptionalKeywordAttr
, "optional-keyword"},
284 {keyTimeoutAttr
, "timeout"},
285 {keyInteractLevelAttr
, "interact-level"},
286 {keyEventSourceAttr
, "event-source"},
287 /* {keyMissedKeywordAttr, "missed-keyword"}, */
288 {keyOriginalAddressAttr
, "original-address"},
289 {keyReplyRequestedAttr
, "reply-requested"},
290 {KEY_EMACS_SUSPENSION_ID_ATTR
, "emacs-suspension-id"}
294 mac_aelist_to_lisp (desc_list
)
295 const AEDescList
*desc_list
;
299 Lisp_Object result
, elem
;
306 err
= AECountItems (desc_list
, &count
);
316 keyword
= ae_attr_table
[count
- 1].keyword
;
317 err
= AESizeOfAttribute (desc_list
, keyword
, &desc_type
, &size
);
320 err
= AESizeOfNthItem (desc_list
, count
, &desc_type
, &size
);
329 err
= AEGetAttributeDesc (desc_list
, keyword
, typeWildCard
,
332 err
= AEGetNthDesc (desc_list
, count
, typeWildCard
,
336 elem
= mac_aelist_to_lisp (&desc
);
337 AEDisposeDesc (&desc
);
341 if (desc_type
== typeNull
)
345 elem
= make_uninit_string (size
);
347 err
= AEGetAttributePtr (desc_list
, keyword
, typeWildCard
,
348 &desc_type
, SDATA (elem
),
351 err
= AEGetNthPtr (desc_list
, count
, typeWildCard
, &keyword
,
352 &desc_type
, SDATA (elem
), size
, &size
);
356 desc_type
= EndianU32_NtoB (desc_type
);
357 elem
= Fcons (make_unibyte_string ((char *) &desc_type
, 4), elem
);
361 if (err
== noErr
|| desc_list
->descriptorType
== typeAEList
)
364 elem
= Qnil
; /* Don't skip elements in AEList. */
365 else if (desc_list
->descriptorType
!= typeAEList
)
368 elem
= Fcons (ae_attr_table
[count
-1].symbol
, elem
);
371 keyword
= EndianU32_NtoB (keyword
);
372 elem
= Fcons (make_unibyte_string ((char *) &keyword
, 4),
377 result
= Fcons (elem
, result
);
383 if (desc_list
->descriptorType
== typeAppleEvent
&& !attribute_p
)
386 count
= sizeof (ae_attr_table
) / sizeof (ae_attr_table
[0]);
390 desc_type
= EndianU32_NtoB (desc_list
->descriptorType
);
391 return Fcons (make_unibyte_string ((char *) &desc_type
, 4), result
);
395 mac_aedesc_to_lisp (desc
)
399 DescType desc_type
= desc
->descriptorType
;
411 return mac_aelist_to_lisp (desc
);
413 /* The following one is much simpler, but creates and disposes
414 of Apple event descriptors many times. */
421 err
= AECountItems (desc
, &count
);
427 err
= AEGetNthDesc (desc
, count
, typeWildCard
, &keyword
, &desc1
);
430 elem
= mac_aedesc_to_lisp (&desc1
);
431 AEDisposeDesc (&desc1
);
432 if (desc_type
!= typeAEList
)
434 keyword
= EndianU32_NtoB (keyword
);
435 elem
= Fcons (make_unibyte_string ((char *) &keyword
, 4), elem
);
437 result
= Fcons (elem
, result
);
445 #if TARGET_API_MAC_CARBON
446 result
= make_uninit_string (AEGetDescDataSize (desc
));
447 err
= AEGetDescData (desc
, SDATA (result
), SBYTES (result
));
449 result
= make_uninit_string (GetHandleSize (desc
->dataHandle
));
450 memcpy (SDATA (result
), *(desc
->dataHandle
), SBYTES (result
));
458 desc_type
= EndianU32_NtoB (desc_type
);
459 return Fcons (make_unibyte_string ((char *) &desc_type
, 4), result
);
463 mac_ae_put_lisp (desc
, keyword_or_index
, obj
)
465 UInt32 keyword_or_index
;
470 if (!(desc
->descriptorType
== typeAppleEvent
471 || desc
->descriptorType
== typeAERecord
472 || desc
->descriptorType
== typeAEList
))
473 return errAEWrongDataType
;
475 if (CONSP (obj
) && STRINGP (XCAR (obj
)) && SBYTES (XCAR (obj
)) == 4)
477 DescType desc_type1
= EndianU32_BtoN (*((UInt32
*) SDATA (XCAR (obj
))));
478 Lisp_Object data
= XCDR (obj
), rest
;
489 err
= AECreateList (NULL
, 0, desc_type1
== typeAERecord
, &desc1
);
492 for (rest
= data
; CONSP (rest
); rest
= XCDR (rest
))
494 UInt32 keyword_or_index1
= 0;
495 Lisp_Object elem
= XCAR (rest
);
497 if (desc_type1
== typeAERecord
)
499 if (CONSP (elem
) && STRINGP (XCAR (elem
))
500 && SBYTES (XCAR (elem
)) == 4)
503 EndianU32_BtoN (*((UInt32
*)
504 SDATA (XCAR (elem
))));
511 err
= mac_ae_put_lisp (&desc1
, keyword_or_index1
, elem
);
518 if (desc
->descriptorType
== typeAEList
)
519 err
= AEPutDesc (desc
, keyword_or_index
, &desc1
);
521 err
= AEPutParamDesc (desc
, keyword_or_index
, &desc1
);
524 AEDisposeDesc (&desc1
);
531 if (desc
->descriptorType
== typeAEList
)
532 err
= AEPutPtr (desc
, keyword_or_index
, desc_type1
,
533 SDATA (data
), SBYTES (data
));
535 err
= AEPutParamPtr (desc
, keyword_or_index
, desc_type1
,
536 SDATA (data
), SBYTES (data
));
541 if (desc
->descriptorType
== typeAEList
)
542 err
= AEPutPtr (desc
, keyword_or_index
, typeNull
, NULL
, 0);
544 err
= AEPutParamPtr (desc
, keyword_or_index
, typeNull
, NULL
, 0);
550 mac_coerce_file_name_ptr (type_code
, data_ptr
, data_size
,
551 to_type
, handler_refcon
, result
)
553 const void *data_ptr
;
561 if (type_code
== typeNull
)
562 err
= errAECoercionFail
;
563 else if (type_code
== to_type
|| to_type
== typeWildCard
)
564 err
= AECreateDesc (TYPE_FILE_NAME
, data_ptr
, data_size
, result
);
565 else if (type_code
== TYPE_FILE_NAME
)
566 /* Coercion from undecoded file name. */
571 CFDataRef data
= NULL
;
573 str
= CFStringCreateWithBytes (NULL
, data_ptr
, data_size
,
574 kCFStringEncodingUTF8
, false);
577 url
= CFURLCreateWithFileSystemPath (NULL
, str
,
578 kCFURLPOSIXPathStyle
, false);
583 data
= CFURLCreateData (NULL
, url
, kCFStringEncodingUTF8
, true);
588 err
= AECoercePtr (typeFileURL
, CFDataGetBytePtr (data
),
589 CFDataGetLength (data
), to_type
, result
);
597 /* Just to be paranoid ... */
601 buf
= xmalloc (data_size
+ 1);
602 memcpy (buf
, data_ptr
, data_size
);
603 buf
[data_size
] = '\0';
604 err
= FSPathMakeRef (buf
, &fref
, NULL
);
607 err
= AECoercePtr (typeFSRef
, &fref
, sizeof (FSRef
),
614 buf
= xmalloc (data_size
+ 1);
615 memcpy (buf
, data_ptr
, data_size
);
616 buf
[data_size
] = '\0';
617 err
= posix_pathname_to_fsspec (buf
, &fs
);
620 err
= AECoercePtr (typeFSS
, &fs
, sizeof (FSSpec
), to_type
, result
);
623 else if (to_type
== TYPE_FILE_NAME
)
624 /* Coercion to undecoded file name. */
628 CFStringRef str
= NULL
;
629 CFDataRef data
= NULL
;
631 if (type_code
== typeFileURL
)
632 url
= CFURLCreateWithBytes (NULL
, data_ptr
, data_size
,
633 kCFStringEncodingUTF8
, NULL
);
640 err
= AECoercePtr (type_code
, data_ptr
, data_size
,
644 size
= AEGetDescDataSize (&desc
);
645 buf
= xmalloc (size
);
646 err
= AEGetDescData (&desc
, buf
, size
);
648 url
= CFURLCreateWithBytes (NULL
, buf
, size
,
649 kCFStringEncodingUTF8
, NULL
);
651 AEDisposeDesc (&desc
);
656 str
= CFURLCopyFileSystemPath (url
, kCFURLPOSIXPathStyle
);
661 data
= CFStringCreateExternalRepresentation (NULL
, str
,
662 kCFStringEncodingUTF8
,
668 err
= AECreateDesc (TYPE_FILE_NAME
, CFDataGetBytePtr (data
),
669 CFDataGetLength (data
), result
);
675 /* Coercion from typeAlias to typeFileURL fails on Mac OS X
676 10.2. In such cases, try typeFSRef as a target type. */
677 char file_name
[MAXPATHLEN
];
679 if (type_code
== typeFSRef
&& data_size
== sizeof (FSRef
))
680 err
= FSRefMakePath (data_ptr
, file_name
, sizeof (file_name
));
686 err
= AECoercePtr (type_code
, data_ptr
, data_size
,
690 err
= AEGetDescData (&desc
, &fref
, sizeof (FSRef
));
691 AEDisposeDesc (&desc
);
694 err
= FSRefMakePath (&fref
, file_name
, sizeof (file_name
));
697 err
= AECreateDesc (TYPE_FILE_NAME
, file_name
,
698 strlen (file_name
), result
);
701 char file_name
[MAXPATHLEN
];
703 if (type_code
== typeFSS
&& data_size
== sizeof (FSSpec
))
704 err
= fsspec_to_posix_pathname (data_ptr
, file_name
,
705 sizeof (file_name
) - 1);
711 err
= AECoercePtr (type_code
, data_ptr
, data_size
, typeFSS
, &desc
);
714 #if TARGET_API_MAC_CARBON
715 err
= AEGetDescData (&desc
, &fs
, sizeof (FSSpec
));
717 fs
= *(FSSpec
*)(*(desc
.dataHandle
));
719 AEDisposeDesc (&desc
);
722 err
= fsspec_to_posix_pathname (&fs
, file_name
,
723 sizeof (file_name
) - 1);
726 err
= AECreateDesc (TYPE_FILE_NAME
, file_name
,
727 strlen (file_name
), result
);
734 return errAECoercionFail
;
739 mac_coerce_file_name_desc (from_desc
, to_type
, handler_refcon
, result
)
740 const AEDesc
*from_desc
;
746 DescType from_type
= from_desc
->descriptorType
;
748 if (from_type
== typeNull
)
749 err
= errAECoercionFail
;
750 else if (from_type
== to_type
|| to_type
== typeWildCard
)
751 err
= AEDuplicateDesc (from_desc
, result
);
757 #if TARGET_API_MAC_CARBON
758 data_size
= AEGetDescDataSize (from_desc
);
760 data_size
= GetHandleSize (from_desc
->dataHandle
);
762 data_ptr
= xmalloc (data_size
);
763 #if TARGET_API_MAC_CARBON
764 err
= AEGetDescData (from_desc
, data_ptr
, data_size
);
766 memcpy (data_ptr
, *(from_desc
->dataHandle
), data_size
);
769 err
= mac_coerce_file_name_ptr (from_type
, data_ptr
,
771 handler_refcon
, result
);
776 return errAECoercionFail
;
781 init_coercion_handler ()
785 static AECoercePtrUPP coerce_file_name_ptrUPP
= NULL
;
786 static AECoerceDescUPP coerce_file_name_descUPP
= NULL
;
788 if (coerce_file_name_ptrUPP
== NULL
)
790 coerce_file_name_ptrUPP
= NewAECoercePtrUPP (mac_coerce_file_name_ptr
);
791 coerce_file_name_descUPP
= NewAECoerceDescUPP (mac_coerce_file_name_desc
);
794 err
= AEInstallCoercionHandler (TYPE_FILE_NAME
, typeWildCard
,
795 (AECoercionHandlerUPP
)
796 coerce_file_name_ptrUPP
, 0, false, false);
798 err
= AEInstallCoercionHandler (typeWildCard
, TYPE_FILE_NAME
,
799 (AECoercionHandlerUPP
)
800 coerce_file_name_ptrUPP
, 0, false, false);
802 err
= AEInstallCoercionHandler (TYPE_FILE_NAME
, typeWildCard
,
803 coerce_file_name_descUPP
, 0, true, false);
805 err
= AEInstallCoercionHandler (typeWildCard
, TYPE_FILE_NAME
,
806 coerce_file_name_descUPP
, 0, true, false);
810 #if TARGET_API_MAC_CARBON
812 create_apple_event (class, id
, result
)
818 static const ProcessSerialNumber psn
= {0, kCurrentProcess
};
819 AEAddressDesc address_desc
;
821 err
= AECreateDesc (typeProcessSerialNumber
, &psn
,
822 sizeof (ProcessSerialNumber
), &address_desc
);
825 err
= AECreateAppleEvent (class, id
,
826 &address_desc
, /* NULL is not allowed
827 on Mac OS Classic. */
828 kAutoGenerateReturnID
,
829 kAnyTransactionID
, result
);
830 AEDisposeDesc (&address_desc
);
837 create_apple_event_from_event_ref (event
, num_params
, names
, types
, result
)
840 EventParamName
*names
;
841 EventParamType
*types
;
850 err
= create_apple_event (0, 0, result
); /* Dummy class and ID. */
854 for (i
= 0; i
< num_params
; i
++)
858 case typeCFStringRef
:
859 err
= GetEventParameter (event
, names
[i
], typeCFStringRef
, NULL
,
860 sizeof (CFStringRef
), NULL
, &string
);
863 data
= CFStringCreateExternalRepresentation (NULL
, string
,
864 kCFStringEncodingUTF8
,
868 AEPutParamPtr (result
, names
[i
], typeUTF8Text
,
869 CFDataGetBytePtr (data
), CFDataGetLength (data
));
875 err
= GetEventParameter (event
, names
[i
], types
[i
], NULL
,
879 buf
= xrealloc (buf
, size
);
880 err
= GetEventParameter (event
, names
[i
], types
[i
], NULL
,
883 AEPutParamPtr (result
, names
[i
], types
[i
], buf
, size
);
893 create_apple_event_from_drag_ref (drag
, num_types
, types
, result
)
905 err
= CountDragItems (drag
, &num_items
);
908 err
= AECreateList (NULL
, 0, false, &items
);
912 for (index
= 1; index
<= num_items
; index
++)
915 DescType desc_type
= typeNull
;
918 err
= GetDragItemReferenceNumber (drag
, index
, &item
);
923 for (i
= 0; i
< num_types
; i
++)
925 err
= GetFlavorDataSize (drag
, item
, types
[i
], &size
);
928 buf
= xrealloc (buf
, size
);
929 err
= GetFlavorData (drag
, item
, types
[i
], buf
, &size
, 0);
933 desc_type
= types
[i
];
938 err
= AEPutPtr (&items
, index
, desc_type
,
939 desc_type
!= typeNull
? buf
: NULL
,
940 desc_type
!= typeNull
? size
: 0);
949 err
= create_apple_event (0, 0, result
); /* Dummy class and ID. */
951 err
= AEPutParamDesc (result
, keyDirectObject
, &items
);
953 AEDisposeDesc (result
);
956 AEDisposeDesc (&items
);
960 #endif /* TARGET_API_MAC_CARBON */
962 /***********************************************************************
963 Conversion between Lisp and Core Foundation objects
964 ***********************************************************************/
966 #if TARGET_API_MAC_CARBON
967 static Lisp_Object Qstring
, Qnumber
, Qboolean
, Qdate
, Qdata
;
968 static Lisp_Object Qarray
, Qdictionary
;
970 struct cfdict_context
973 int with_tag
, hash_bound
;
976 /* C string to CFString. */
979 cfstring_create_with_utf8_cstring (c_str
)
984 str
= CFStringCreateWithCString (NULL
, c_str
, kCFStringEncodingUTF8
);
986 /* Failed to interpret as UTF 8. Fall back on Mac Roman. */
987 str
= CFStringCreateWithCString (NULL
, c_str
, kCFStringEncodingMacRoman
);
993 /* Lisp string to CFString. */
996 cfstring_create_with_string (s
)
999 CFStringRef string
= NULL
;
1001 if (STRING_MULTIBYTE (s
))
1003 char *p
, *end
= SDATA (s
) + SBYTES (s
);
1005 for (p
= SDATA (s
); p
< end
; p
++)
1008 s
= ENCODE_UTF_8 (s
);
1011 string
= CFStringCreateWithBytes (NULL
, SDATA (s
), SBYTES (s
),
1012 kCFStringEncodingUTF8
, false);
1016 /* Failed to interpret as UTF 8. Fall back on Mac Roman. */
1017 string
= CFStringCreateWithBytes (NULL
, SDATA (s
), SBYTES (s
),
1018 kCFStringEncodingMacRoman
, false);
1024 /* From CFData to a lisp string. Always returns a unibyte string. */
1027 cfdata_to_lisp (data
)
1030 CFIndex len
= CFDataGetLength (data
);
1031 Lisp_Object result
= make_uninit_string (len
);
1033 CFDataGetBytes (data
, CFRangeMake (0, len
), SDATA (result
));
1039 /* From CFString to a lisp string. Returns a unibyte string
1040 containing a UTF-8 byte sequence. */
1043 cfstring_to_lisp_nodecode (string
)
1046 Lisp_Object result
= Qnil
;
1047 const char *s
= CFStringGetCStringPtr (string
, kCFStringEncodingUTF8
);
1050 result
= make_unibyte_string (s
, strlen (s
));
1054 CFStringCreateExternalRepresentation (NULL
, string
,
1055 kCFStringEncodingUTF8
, '?');
1059 result
= cfdata_to_lisp (data
);
1068 /* From CFString to a lisp string. Never returns a unibyte string
1069 (even if it only contains ASCII characters).
1070 This may cause GC during code conversion. */
1073 cfstring_to_lisp (string
)
1076 Lisp_Object result
= cfstring_to_lisp_nodecode (string
);
1080 result
= code_convert_string_norecord (result
, Qutf_8
, 0);
1081 /* This may be superfluous. Just to make sure that the result
1082 is a multibyte string. */
1083 result
= string_to_multibyte (result
);
1090 /* CFNumber to a lisp integer or a lisp float. */
1093 cfnumber_to_lisp (number
)
1096 Lisp_Object result
= Qnil
;
1097 #if BITS_PER_EMACS_INT > 32
1099 CFNumberType emacs_int_type
= kCFNumberSInt64Type
;
1102 CFNumberType emacs_int_type
= kCFNumberSInt32Type
;
1106 if (CFNumberGetValue (number
, emacs_int_type
, &int_val
)
1107 && !FIXNUM_OVERFLOW_P (int_val
))
1108 result
= make_number (int_val
);
1110 if (CFNumberGetValue (number
, kCFNumberDoubleType
, &float_val
))
1111 result
= make_float (float_val
);
1116 /* CFDate to a list of three integers as in a return value of
1120 cfdate_to_lisp (date
)
1123 static const CFGregorianDate epoch_gdate
= {1970, 1, 1, 0, 0, 0.0};
1124 static CFAbsoluteTime epoch
= 0.0, sec
;
1128 epoch
= CFGregorianDateGetAbsoluteTime (epoch_gdate
, NULL
);
1130 sec
= CFDateGetAbsoluteTime (date
) - epoch
;
1131 high
= sec
/ 65536.0;
1132 low
= sec
- high
* 65536.0;
1134 return list3 (make_number (high
), make_number (low
), make_number (0));
1138 /* CFBoolean to a lisp symbol, `t' or `nil'. */
1141 cfboolean_to_lisp (boolean
)
1142 CFBooleanRef boolean
;
1144 return CFBooleanGetValue (boolean
) ? Qt
: Qnil
;
1148 /* Any Core Foundation object to a (lengthy) lisp string. */
1151 cfobject_desc_to_lisp (object
)
1154 Lisp_Object result
= Qnil
;
1155 CFStringRef desc
= CFCopyDescription (object
);
1159 result
= cfstring_to_lisp (desc
);
1167 /* Callback functions for cfproperty_list_to_lisp. */
1170 cfdictionary_add_to_list (key
, value
, context
)
1175 struct cfdict_context
*cxt
= (struct cfdict_context
*)context
;
1178 Fcons (Fcons (cfstring_to_lisp (key
),
1179 cfproperty_list_to_lisp (value
, cxt
->with_tag
,
1185 cfdictionary_puthash (key
, value
, context
)
1190 Lisp_Object lisp_key
= cfstring_to_lisp (key
);
1191 struct cfdict_context
*cxt
= (struct cfdict_context
*)context
;
1192 struct Lisp_Hash_Table
*h
= XHASH_TABLE (*(cxt
->result
));
1195 hash_lookup (h
, lisp_key
, &hash_code
);
1196 hash_put (h
, lisp_key
,
1197 cfproperty_list_to_lisp (value
, cxt
->with_tag
, cxt
->hash_bound
),
1202 /* Convert CFPropertyList PLIST to a lisp object. If WITH_TAG is
1203 non-zero, a symbol that represents the type of the original Core
1204 Foundation object is prepended. HASH_BOUND specifies which kinds
1205 of the lisp objects, alists or hash tables, are used as the targets
1206 of the conversion from CFDictionary. If HASH_BOUND is negative,
1207 always generate alists. If HASH_BOUND >= 0, generate an alist if
1208 the number of keys in the dictionary is smaller than HASH_BOUND,
1209 and a hash table otherwise. */
1212 cfproperty_list_to_lisp (plist
, with_tag
, hash_bound
)
1213 CFPropertyListRef plist
;
1214 int with_tag
, hash_bound
;
1216 CFTypeID type_id
= CFGetTypeID (plist
);
1217 Lisp_Object tag
= Qnil
, result
= Qnil
;
1218 struct gcpro gcpro1
, gcpro2
;
1220 GCPRO2 (tag
, result
);
1222 if (type_id
== CFStringGetTypeID ())
1225 result
= cfstring_to_lisp (plist
);
1227 else if (type_id
== CFNumberGetTypeID ())
1230 result
= cfnumber_to_lisp (plist
);
1232 else if (type_id
== CFBooleanGetTypeID ())
1235 result
= cfboolean_to_lisp (plist
);
1237 else if (type_id
== CFDateGetTypeID ())
1240 result
= cfdate_to_lisp (plist
);
1242 else if (type_id
== CFDataGetTypeID ())
1245 result
= cfdata_to_lisp (plist
);
1247 else if (type_id
== CFArrayGetTypeID ())
1249 CFIndex index
, count
= CFArrayGetCount (plist
);
1252 result
= Fmake_vector (make_number (count
), Qnil
);
1253 for (index
= 0; index
< count
; index
++)
1254 XVECTOR (result
)->contents
[index
] =
1255 cfproperty_list_to_lisp (CFArrayGetValueAtIndex (plist
, index
),
1256 with_tag
, hash_bound
);
1258 else if (type_id
== CFDictionaryGetTypeID ())
1260 struct cfdict_context context
;
1261 CFIndex count
= CFDictionaryGetCount (plist
);
1264 context
.result
= &result
;
1265 context
.with_tag
= with_tag
;
1266 context
.hash_bound
= hash_bound
;
1267 if (hash_bound
< 0 || count
< hash_bound
)
1270 CFDictionaryApplyFunction (plist
, cfdictionary_add_to_list
,
1275 result
= make_hash_table (Qequal
,
1276 make_number (count
),
1277 make_float (DEFAULT_REHASH_SIZE
),
1278 make_float (DEFAULT_REHASH_THRESHOLD
),
1280 CFDictionaryApplyFunction (plist
, cfdictionary_puthash
,
1290 result
= Fcons (tag
, result
);
1297 /***********************************************************************
1298 Emulation of the X Resource Manager
1299 ***********************************************************************/
1301 /* Parser functions for resource lines. Each function takes an
1302 address of a variable whose value points to the head of a string.
1303 The value will be advanced so that it points to the next character
1304 of the parsed part when the function returns.
1306 A resource name such as "Emacs*font" is parsed into a non-empty
1307 list called `quarks'. Each element is either a Lisp string that
1308 represents a concrete component, a Lisp symbol LOOSE_BINDING
1309 (actually Qlambda) that represents any number (>=0) of intervening
1310 components, or a Lisp symbol SINGLE_COMPONENT (actually Qquote)
1311 that represents as any single component. */
1315 #define LOOSE_BINDING Qlambda /* '*' ("L"oose) */
1316 #define SINGLE_COMPONENT Qquote /* '?' ("Q"uestion) */
1319 skip_white_space (p
)
1322 /* WhiteSpace = {<space> | <horizontal tab>} */
1323 while (*P
== ' ' || *P
== '\t')
1331 /* Comment = "!" {<any character except null or newline>} */
1344 /* Don't interpret filename. Just skip until the newline. */
1346 parse_include_file (p
)
1349 /* IncludeFile = "#" WhiteSpace "include" WhiteSpace FileName WhiteSpace */
1366 /* Binding = "." | "*" */
1367 if (*P
== '.' || *P
== '*')
1369 char binding
= *P
++;
1371 while (*P
== '.' || *P
== '*')
1384 /* Component = "?" | ComponentName
1385 ComponentName = NameChar {NameChar}
1386 NameChar = "a"-"z" | "A"-"Z" | "0"-"9" | "_" | "-" */
1390 return SINGLE_COMPONENT
;
1392 else if (isalnum (*P
) || *P
== '_' || *P
== '-')
1396 while (isalnum (*P
) || *P
== '_' || *P
== '-')
1399 return make_unibyte_string (start
, P
- start
);
1406 parse_resource_name (p
)
1409 Lisp_Object result
= Qnil
, component
;
1412 /* ResourceName = [Binding] {Component Binding} ComponentName */
1413 if (parse_binding (p
) == '*')
1414 result
= Fcons (LOOSE_BINDING
, result
);
1416 component
= parse_component (p
);
1417 if (NILP (component
))
1420 result
= Fcons (component
, result
);
1421 while ((binding
= parse_binding (p
)) != '\0')
1424 result
= Fcons (LOOSE_BINDING
, result
);
1425 component
= parse_component (p
);
1426 if (NILP (component
))
1429 result
= Fcons (component
, result
);
1432 /* The final component should not be '?'. */
1433 if (EQ (component
, SINGLE_COMPONENT
))
1436 return Fnreverse (result
);
1444 Lisp_Object seq
= Qnil
, result
;
1445 int buf_len
, total_len
= 0, len
, continue_p
;
1447 q
= strchr (P
, '\n');
1448 buf_len
= q
? q
- P
: strlen (P
);
1449 buf
= xmalloc (buf_len
);
1462 else if (*P
== '\\')
1467 else if (*P
== '\n')
1478 else if ('0' <= P
[0] && P
[0] <= '7'
1479 && '0' <= P
[1] && P
[1] <= '7'
1480 && '0' <= P
[2] && P
[2] <= '7')
1482 *q
++ = ((P
[0] - '0') << 6) + ((P
[1] - '0') << 3) + (P
[2] - '0');
1492 seq
= Fcons (make_unibyte_string (buf
, len
), seq
);
1497 q
= strchr (P
, '\n');
1498 len
= q
? q
- P
: strlen (P
);
1503 buf
= xmalloc (buf_len
);
1511 if (SBYTES (XCAR (seq
)) == total_len
)
1512 return make_string (SDATA (XCAR (seq
)), total_len
);
1515 buf
= xmalloc (total_len
);
1516 q
= buf
+ total_len
;
1517 for (; CONSP (seq
); seq
= XCDR (seq
))
1519 len
= SBYTES (XCAR (seq
));
1521 memcpy (q
, SDATA (XCAR (seq
)), len
);
1523 result
= make_string (buf
, total_len
);
1530 parse_resource_line (p
)
1533 Lisp_Object quarks
, value
;
1535 /* ResourceLine = Comment | IncludeFile | ResourceSpec | <empty line> */
1536 if (parse_comment (p
) || parse_include_file (p
))
1539 /* ResourceSpec = WhiteSpace ResourceName WhiteSpace ":" WhiteSpace Value */
1540 skip_white_space (p
);
1541 quarks
= parse_resource_name (p
);
1544 skip_white_space (p
);
1548 skip_white_space (p
);
1549 value
= parse_value (p
);
1550 return Fcons (quarks
, value
);
1553 /* Skip the remaining data as a dummy value. */
1560 /* Equivalents of X Resource Manager functions.
1562 An X Resource Database acts as a collection of resource names and
1563 associated values. It is implemented as a trie on quarks. Namely,
1564 each edge is labeled by either a string, LOOSE_BINDING, or
1565 SINGLE_COMPONENT. Each node has a node id, which is a unique
1566 nonnegative integer, and the root node id is 0. A database is
1567 implemented as a hash table that maps a pair (SRC-NODE-ID .
1568 EDGE-LABEL) to DEST-NODE-ID. It also holds a maximum node id used
1569 in the table as a value for HASHKEY_MAX_NID. A value associated to
1570 a node is recorded as a value for the node id.
1572 A database also has a cache for past queries as a value for
1573 HASHKEY_QUERY_CACHE. It is another hash table that maps
1574 "NAME-STRING\0CLASS-STRING" to the result of the query. */
1576 #define HASHKEY_MAX_NID (make_number (0))
1577 #define HASHKEY_QUERY_CACHE (make_number (-1))
1580 xrm_create_database ()
1582 XrmDatabase database
;
1584 database
= make_hash_table (Qequal
, make_number (DEFAULT_HASH_SIZE
),
1585 make_float (DEFAULT_REHASH_SIZE
),
1586 make_float (DEFAULT_REHASH_THRESHOLD
),
1588 Fputhash (HASHKEY_MAX_NID
, make_number (0), database
);
1589 Fputhash (HASHKEY_QUERY_CACHE
, Qnil
, database
);
1595 xrm_q_put_resource (database
, quarks
, value
)
1596 XrmDatabase database
;
1597 Lisp_Object quarks
, value
;
1599 struct Lisp_Hash_Table
*h
= XHASH_TABLE (database
);
1602 Lisp_Object node_id
, key
;
1604 max_nid
= XINT (Fgethash (HASHKEY_MAX_NID
, database
, Qnil
));
1606 XSETINT (node_id
, 0);
1607 for (; CONSP (quarks
); quarks
= XCDR (quarks
))
1609 key
= Fcons (node_id
, XCAR (quarks
));
1610 i
= hash_lookup (h
, key
, &hash_code
);
1614 XSETINT (node_id
, max_nid
);
1615 hash_put (h
, key
, node_id
, hash_code
);
1618 node_id
= HASH_VALUE (h
, i
);
1620 Fputhash (node_id
, value
, database
);
1622 Fputhash (HASHKEY_MAX_NID
, make_number (max_nid
), database
);
1623 Fputhash (HASHKEY_QUERY_CACHE
, Qnil
, database
);
1626 /* Merge multiple resource entries specified by DATA into a resource
1627 database DATABASE. DATA points to the head of a null-terminated
1628 string consisting of multiple resource lines. It's like a
1629 combination of XrmGetStringDatabase and XrmMergeDatabases. */
1632 xrm_merge_string_database (database
, data
)
1633 XrmDatabase database
;
1636 Lisp_Object quarks_value
;
1640 quarks_value
= parse_resource_line (&data
);
1641 if (!NILP (quarks_value
))
1642 xrm_q_put_resource (database
,
1643 XCAR (quarks_value
), XCDR (quarks_value
));
1648 xrm_q_get_resource_1 (database
, node_id
, quark_name
, quark_class
)
1649 XrmDatabase database
;
1650 Lisp_Object node_id
, quark_name
, quark_class
;
1652 struct Lisp_Hash_Table
*h
= XHASH_TABLE (database
);
1653 Lisp_Object key
, labels
[3], value
;
1656 if (!CONSP (quark_name
))
1657 return Fgethash (node_id
, database
, Qnil
);
1659 /* First, try tight bindings */
1660 labels
[0] = XCAR (quark_name
);
1661 labels
[1] = XCAR (quark_class
);
1662 labels
[2] = SINGLE_COMPONENT
;
1664 key
= Fcons (node_id
, Qnil
);
1665 for (k
= 0; k
< sizeof (labels
) / sizeof (*labels
); k
++)
1667 XSETCDR (key
, labels
[k
]);
1668 i
= hash_lookup (h
, key
, NULL
);
1671 value
= xrm_q_get_resource_1 (database
, HASH_VALUE (h
, i
),
1672 XCDR (quark_name
), XCDR (quark_class
));
1678 /* Then, try loose bindings */
1679 XSETCDR (key
, LOOSE_BINDING
);
1680 i
= hash_lookup (h
, key
, NULL
);
1683 value
= xrm_q_get_resource_1 (database
, HASH_VALUE (h
, i
),
1684 quark_name
, quark_class
);
1688 return xrm_q_get_resource_1 (database
, node_id
,
1689 XCDR (quark_name
), XCDR (quark_class
));
1696 xrm_q_get_resource (database
, quark_name
, quark_class
)
1697 XrmDatabase database
;
1698 Lisp_Object quark_name
, quark_class
;
1700 return xrm_q_get_resource_1 (database
, make_number (0),
1701 quark_name
, quark_class
);
1704 /* Retrieve a resource value for the specified NAME and CLASS from the
1705 resource database DATABASE. It corresponds to XrmGetResource. */
1708 xrm_get_resource (database
, name
, class)
1709 XrmDatabase database
;
1712 Lisp_Object key
, query_cache
, quark_name
, quark_class
, tmp
;
1714 struct Lisp_Hash_Table
*h
;
1718 nc
= strlen (class);
1719 key
= make_uninit_string (nn
+ nc
+ 1);
1720 strcpy (SDATA (key
), name
);
1721 strncpy (SDATA (key
) + nn
+ 1, class, nc
);
1723 query_cache
= Fgethash (HASHKEY_QUERY_CACHE
, database
, Qnil
);
1724 if (NILP (query_cache
))
1726 query_cache
= make_hash_table (Qequal
, make_number (DEFAULT_HASH_SIZE
),
1727 make_float (DEFAULT_REHASH_SIZE
),
1728 make_float (DEFAULT_REHASH_THRESHOLD
),
1730 Fputhash (HASHKEY_QUERY_CACHE
, query_cache
, database
);
1732 h
= XHASH_TABLE (query_cache
);
1733 i
= hash_lookup (h
, key
, &hash_code
);
1735 return HASH_VALUE (h
, i
);
1737 quark_name
= parse_resource_name (&name
);
1740 for (tmp
= quark_name
, nn
= 0; CONSP (tmp
); tmp
= XCDR (tmp
), nn
++)
1741 if (!STRINGP (XCAR (tmp
)))
1744 quark_class
= parse_resource_name (&class);
1747 for (tmp
= quark_class
, nc
= 0; CONSP (tmp
); tmp
= XCDR (tmp
), nc
++)
1748 if (!STRINGP (XCAR (tmp
)))
1755 tmp
= xrm_q_get_resource (database
, quark_name
, quark_class
);
1756 hash_put (h
, key
, tmp
, hash_code
);
1761 #if TARGET_API_MAC_CARBON
1763 xrm_cfproperty_list_to_value (plist
)
1764 CFPropertyListRef plist
;
1766 CFTypeID type_id
= CFGetTypeID (plist
);
1768 if (type_id
== CFStringGetTypeID ())
1769 return cfstring_to_lisp (plist
);
1770 else if (type_id
== CFNumberGetTypeID ())
1773 Lisp_Object result
= Qnil
;
1775 string
= CFStringCreateWithFormat (NULL
, NULL
, CFSTR ("%@"), plist
);
1778 result
= cfstring_to_lisp (string
);
1783 else if (type_id
== CFBooleanGetTypeID ())
1784 return build_string (CFBooleanGetValue (plist
) ? "true" : "false");
1785 else if (type_id
== CFDataGetTypeID ())
1786 return cfdata_to_lisp (plist
);
1792 /* Create a new resource database from the preferences for the
1793 application APPLICATION. APPLICATION is either a string that
1794 specifies an application ID, or NULL that represents the current
1798 xrm_get_preference_database (application
)
1801 #if TARGET_API_MAC_CARBON
1802 CFStringRef app_id
, *keys
, user_doms
[2], host_doms
[2];
1803 CFMutableSetRef key_set
= NULL
;
1804 CFArrayRef key_array
;
1805 CFIndex index
, count
;
1807 XrmDatabase database
;
1808 Lisp_Object quarks
= Qnil
, value
= Qnil
;
1809 CFPropertyListRef plist
;
1811 struct gcpro gcpro1
, gcpro2
, gcpro3
;
1813 user_doms
[0] = kCFPreferencesCurrentUser
;
1814 user_doms
[1] = kCFPreferencesAnyUser
;
1815 host_doms
[0] = kCFPreferencesCurrentHost
;
1816 host_doms
[1] = kCFPreferencesAnyHost
;
1818 database
= xrm_create_database ();
1820 GCPRO3 (database
, quarks
, value
);
1824 app_id
= kCFPreferencesCurrentApplication
;
1827 app_id
= cfstring_create_with_utf8_cstring (application
);
1832 key_set
= CFSetCreateMutable (NULL
, 0, &kCFCopyStringSetCallBacks
);
1833 if (key_set
== NULL
)
1835 for (iu
= 0; iu
< sizeof (user_doms
) / sizeof (*user_doms
) ; iu
++)
1836 for (ih
= 0; ih
< sizeof (host_doms
) / sizeof (*host_doms
); ih
++)
1838 key_array
= CFPreferencesCopyKeyList (app_id
, user_doms
[iu
],
1842 count
= CFArrayGetCount (key_array
);
1843 for (index
= 0; index
< count
; index
++)
1844 CFSetAddValue (key_set
,
1845 CFArrayGetValueAtIndex (key_array
, index
));
1846 CFRelease (key_array
);
1850 count
= CFSetGetCount (key_set
);
1851 keys
= xmalloc (sizeof (CFStringRef
) * count
);
1852 CFSetGetValues (key_set
, (const void **)keys
);
1853 for (index
= 0; index
< count
; index
++)
1855 res_name
= SDATA (cfstring_to_lisp_nodecode (keys
[index
]));
1856 quarks
= parse_resource_name (&res_name
);
1857 if (!(NILP (quarks
) || *res_name
))
1859 plist
= CFPreferencesCopyAppValue (keys
[index
], app_id
);
1860 value
= xrm_cfproperty_list_to_value (plist
);
1863 xrm_q_put_resource (database
, quarks
, value
);
1870 CFRelease (key_set
);
1879 return xrm_create_database ();
1886 /* The following functions with "sys_" prefix are stubs to Unix
1887 functions that have already been implemented by CW or MPW. The
1888 calls to them in Emacs source course are #define'd to call the sys_
1889 versions by the header files s-mac.h. In these stubs pathnames are
1890 converted between their Unix and Mac forms. */
1893 /* Unix epoch is Jan 1, 1970 while Mac epoch is Jan 1, 1904: 66 years
1894 + 17 leap days. These are for adjusting time values returned by
1895 MacOS Toolbox functions. */
1897 #define MAC_UNIX_EPOCH_DIFF ((365L * 66 + 17) * 24 * 60 * 60)
1900 #if __MSL__ < 0x6000
1901 /* CW Pro 5 epoch is Jan 1, 1900 (aaarghhhhh!); remember, 1900 is not
1902 a leap year! This is for adjusting time_t values returned by MSL
1904 #define CW_OR_MPW_UNIX_EPOCH_DIFF ((365L * 70 + 17) * 24 * 60 * 60)
1905 #else /* __MSL__ >= 0x6000 */
1906 /* CW changes Pro 6 to follow Unix! */
1907 #define CW_OR_MPW_UNIX_EPOCH_DIFF ((365L * 66 + 17) * 24 * 60 * 60)
1908 #endif /* __MSL__ >= 0x6000 */
1910 /* MPW library functions follow Unix (confused?). */
1911 #define CW_OR_MPW_UNIX_EPOCH_DIFF ((365L * 66 + 17) * 24 * 60 * 60)
1912 #else /* not __MRC__ */
1914 #endif /* not __MRC__ */
1917 /* Define our own stat function for both MrC and CW. The reason for
1918 doing this: "stat" is both the name of a struct and function name:
1919 can't use the same trick like that for sys_open, sys_close, etc. to
1920 redirect Emacs's calls to our own version that converts Unix style
1921 filenames to Mac style filename because all sorts of compilation
1922 errors will be generated if stat is #define'd to be sys_stat. */
1925 stat_noalias (const char *path
, struct stat
*buf
)
1927 char mac_pathname
[MAXPATHLEN
+1];
1930 if (posix_to_mac_pathname (path
, mac_pathname
, MAXPATHLEN
+1) == 0)
1933 c2pstr (mac_pathname
);
1934 cipb
.hFileInfo
.ioNamePtr
= mac_pathname
;
1935 cipb
.hFileInfo
.ioVRefNum
= 0;
1936 cipb
.hFileInfo
.ioDirID
= 0;
1937 cipb
.hFileInfo
.ioFDirIndex
= 0;
1938 /* set to 0 to get information about specific dir or file */
1940 errno
= PBGetCatInfo (&cipb
, false);
1941 if (errno
== -43) /* -43: fnfErr defined in Errors.h */
1946 if (cipb
.hFileInfo
.ioFlAttrib
& 0x10) /* bit 4 = 1 for directories */
1948 buf
->st_mode
= S_IFDIR
| S_IREAD
| S_IEXEC
;
1950 if (!(cipb
.hFileInfo
.ioFlAttrib
& 0x1))
1951 buf
->st_mode
|= S_IWRITE
; /* bit 1 = 1 for locked files/directories */
1952 buf
->st_ino
= cipb
.dirInfo
.ioDrDirID
;
1953 buf
->st_dev
= cipb
.dirInfo
.ioVRefNum
;
1954 buf
->st_size
= cipb
.dirInfo
.ioDrNmFls
;
1955 /* size of dir = number of files and dirs */
1958 = cipb
.dirInfo
.ioDrMdDat
- MAC_UNIX_EPOCH_DIFF
;
1959 buf
->st_ctime
= cipb
.dirInfo
.ioDrCrDat
- MAC_UNIX_EPOCH_DIFF
;
1963 buf
->st_mode
= S_IFREG
| S_IREAD
;
1964 if (!(cipb
.hFileInfo
.ioFlAttrib
& 0x1))
1965 buf
->st_mode
|= S_IWRITE
; /* bit 1 = 1 for locked files/directories */
1966 if (cipb
.hFileInfo
.ioFlFndrInfo
.fdType
== 'APPL')
1967 buf
->st_mode
|= S_IEXEC
;
1968 buf
->st_ino
= cipb
.hFileInfo
.ioDirID
;
1969 buf
->st_dev
= cipb
.hFileInfo
.ioVRefNum
;
1970 buf
->st_size
= cipb
.hFileInfo
.ioFlLgLen
;
1973 = cipb
.hFileInfo
.ioFlMdDat
- MAC_UNIX_EPOCH_DIFF
;
1974 buf
->st_ctime
= cipb
.hFileInfo
.ioFlCrDat
- MAC_UNIX_EPOCH_DIFF
;
1977 if (cipb
.hFileInfo
.ioFlFndrInfo
.fdFlags
& 0x8000)
1979 /* identify alias files as symlinks */
1980 buf
->st_mode
&= ~S_IFREG
;
1981 buf
->st_mode
|= S_IFLNK
;
1985 buf
->st_uid
= getuid ();
1986 buf
->st_gid
= getgid ();
1994 lstat (const char *path
, struct stat
*buf
)
1997 char true_pathname
[MAXPATHLEN
+1];
1999 /* Try looking for the file without resolving aliases first. */
2000 if ((result
= stat_noalias (path
, buf
)) >= 0)
2003 if (find_true_pathname (path
, true_pathname
, MAXPATHLEN
+1) == -1)
2006 return stat_noalias (true_pathname
, buf
);
2011 stat (const char *path
, struct stat
*sb
)
2014 char true_pathname
[MAXPATHLEN
+1], fully_resolved_name
[MAXPATHLEN
+1];
2017 if ((result
= stat_noalias (path
, sb
)) >= 0 &&
2018 ! (sb
->st_mode
& S_IFLNK
))
2021 if (find_true_pathname (path
, true_pathname
, MAXPATHLEN
+1) == -1)
2024 len
= readlink (true_pathname
, fully_resolved_name
, MAXPATHLEN
);
2027 fully_resolved_name
[len
] = '\0';
2028 /* in fact our readlink terminates strings */
2029 return lstat (fully_resolved_name
, sb
);
2032 return lstat (true_pathname
, sb
);
2037 /* CW defines fstat in stat.mac.c while MPW does not provide this
2038 function. Without the information of how to get from a file
2039 descriptor in MPW StdCLib to a Mac OS file spec, it should be hard
2040 to implement this function. Fortunately, there is only one place
2041 where this function is called in our configuration: in fileio.c,
2042 where only the st_dev and st_ino fields are used to determine
2043 whether two fildes point to different i-nodes to prevent copying
2044 a file onto itself equal. What we have here probably needs
2048 fstat (int fildes
, struct stat
*buf
)
2051 buf
->st_ino
= fildes
;
2052 buf
->st_mode
= S_IFREG
; /* added by T.I. for the copy-file */
2053 return 0; /* success */
2055 #endif /* __MRC__ */
2059 mkdir (const char *dirname
, int mode
)
2061 #pragma unused(mode)
2064 char true_pathname
[MAXPATHLEN
+1], mac_pathname
[MAXPATHLEN
+1];
2066 if (find_true_pathname (dirname
, true_pathname
, MAXPATHLEN
+1) == -1)
2069 if (posix_to_mac_pathname (true_pathname
, mac_pathname
, MAXPATHLEN
+1) == 0)
2072 c2pstr (mac_pathname
);
2073 hfpb
.ioNamePtr
= mac_pathname
;
2074 hfpb
.ioVRefNum
= 0; /* ignored unless name is invalid */
2075 hfpb
.ioDirID
= 0; /* parent is the root */
2077 errno
= PBDirCreate ((HParmBlkPtr
) &hfpb
, false);
2078 /* just return the Mac OSErr code for now */
2079 return errno
== noErr
? 0 : -1;
2084 sys_rmdir (const char *dirname
)
2087 char mac_pathname
[MAXPATHLEN
+1];
2089 if (posix_to_mac_pathname (dirname
, mac_pathname
, MAXPATHLEN
+1) == 0)
2092 c2pstr (mac_pathname
);
2093 hfpb
.ioNamePtr
= mac_pathname
;
2094 hfpb
.ioVRefNum
= 0; /* ignored unless name is invalid */
2095 hfpb
.ioDirID
= 0; /* parent is the root */
2097 errno
= PBHDelete ((HParmBlkPtr
) &hfpb
, false);
2098 return errno
== noErr
? 0 : -1;
2103 /* No implementation yet. */
2105 execvp (const char *path
, ...)
2109 #endif /* __MRC__ */
2113 utime (const char *path
, const struct utimbuf
*times
)
2115 char true_pathname
[MAXPATHLEN
+1], fully_resolved_name
[MAXPATHLEN
+1];
2117 char mac_pathname
[MAXPATHLEN
+1];
2120 if (find_true_pathname (path
, true_pathname
, MAXPATHLEN
+1) == -1)
2123 len
= readlink (true_pathname
, fully_resolved_name
, MAXPATHLEN
);
2125 fully_resolved_name
[len
] = '\0';
2127 strcpy (fully_resolved_name
, true_pathname
);
2129 if (!posix_to_mac_pathname (fully_resolved_name
, mac_pathname
, MAXPATHLEN
+1))
2132 c2pstr (mac_pathname
);
2133 cipb
.hFileInfo
.ioNamePtr
= mac_pathname
;
2134 cipb
.hFileInfo
.ioVRefNum
= 0;
2135 cipb
.hFileInfo
.ioDirID
= 0;
2136 cipb
.hFileInfo
.ioFDirIndex
= 0;
2137 /* set to 0 to get information about specific dir or file */
2139 errno
= PBGetCatInfo (&cipb
, false);
2143 if (cipb
.hFileInfo
.ioFlAttrib
& 0x10) /* bit 4 = 1 for directories */
2146 cipb
.dirInfo
.ioDrMdDat
= times
->modtime
+ MAC_UNIX_EPOCH_DIFF
;
2148 GetDateTime (&cipb
.dirInfo
.ioDrMdDat
);
2153 cipb
.hFileInfo
.ioFlMdDat
= times
->modtime
+ MAC_UNIX_EPOCH_DIFF
;
2155 GetDateTime (&cipb
.hFileInfo
.ioFlMdDat
);
2158 errno
= PBSetCatInfo (&cipb
, false);
2159 return errno
== noErr
? 0 : -1;
2173 /* Like stat, but test for access mode in hfpb.ioFlAttrib */
2175 access (const char *path
, int mode
)
2177 char true_pathname
[MAXPATHLEN
+1], fully_resolved_name
[MAXPATHLEN
+1];
2179 char mac_pathname
[MAXPATHLEN
+1];
2182 if (find_true_pathname (path
, true_pathname
, MAXPATHLEN
+1) == -1)
2185 len
= readlink (true_pathname
, fully_resolved_name
, MAXPATHLEN
);
2187 fully_resolved_name
[len
] = '\0';
2189 strcpy (fully_resolved_name
, true_pathname
);
2191 if (!posix_to_mac_pathname (fully_resolved_name
, mac_pathname
, MAXPATHLEN
+1))
2194 c2pstr (mac_pathname
);
2195 cipb
.hFileInfo
.ioNamePtr
= mac_pathname
;
2196 cipb
.hFileInfo
.ioVRefNum
= 0;
2197 cipb
.hFileInfo
.ioDirID
= 0;
2198 cipb
.hFileInfo
.ioFDirIndex
= 0;
2199 /* set to 0 to get information about specific dir or file */
2201 errno
= PBGetCatInfo (&cipb
, false);
2205 if (mode
== F_OK
) /* got this far, file exists */
2209 if (cipb
.hFileInfo
.ioFlAttrib
& 0x10) /* path refers to a directory */
2213 if (cipb
.hFileInfo
.ioFlFndrInfo
.fdType
== 'APPL')
2220 return (cipb
.hFileInfo
.ioFlAttrib
& 0x1) ? -1 : 0;
2221 /* don't allow if lock bit is on */
2227 #define DEV_NULL_FD 0x10000
2231 sys_open (const char *path
, int oflag
)
2233 char true_pathname
[MAXPATHLEN
+1], fully_resolved_name
[MAXPATHLEN
+1];
2235 char mac_pathname
[MAXPATHLEN
+1];
2237 if (strcmp (path
, "/dev/null") == 0)
2238 return DEV_NULL_FD
; /* some bogus fd to be ignored in write */
2240 if (find_true_pathname (path
, true_pathname
, MAXPATHLEN
+1) == -1)
2243 len
= readlink (true_pathname
, fully_resolved_name
, MAXPATHLEN
);
2245 fully_resolved_name
[len
] = '\0';
2247 strcpy (fully_resolved_name
, true_pathname
);
2249 if (!posix_to_mac_pathname (fully_resolved_name
, mac_pathname
, MAXPATHLEN
+1))
2254 int res
= open (mac_pathname
, oflag
);
2255 /* if (oflag == O_WRONLY || oflag == O_RDWR) */
2256 if (oflag
& O_CREAT
)
2257 fsetfileinfo (mac_pathname
, 'EMAx', 'TEXT');
2259 #else /* not __MRC__ */
2260 return open (mac_pathname
, oflag
);
2261 #endif /* not __MRC__ */
2268 sys_creat (const char *path
, mode_t mode
)
2270 char true_pathname
[MAXPATHLEN
+1];
2272 char mac_pathname
[MAXPATHLEN
+1];
2274 if (find_true_pathname (path
, true_pathname
, MAXPATHLEN
+1) == -1)
2277 if (!posix_to_mac_pathname (true_pathname
, mac_pathname
, MAXPATHLEN
+1))
2282 int result
= creat (mac_pathname
);
2283 fsetfileinfo (mac_pathname
, 'EMAx', 'TEXT');
2285 #else /* not __MRC__ */
2286 return creat (mac_pathname
, mode
);
2287 #endif /* not __MRC__ */
2294 sys_unlink (const char *path
)
2296 char true_pathname
[MAXPATHLEN
+1], fully_resolved_name
[MAXPATHLEN
+1];
2298 char mac_pathname
[MAXPATHLEN
+1];
2300 if (find_true_pathname (path
, true_pathname
, MAXPATHLEN
+1) == -1)
2303 len
= readlink (true_pathname
, fully_resolved_name
, MAXPATHLEN
);
2305 fully_resolved_name
[len
] = '\0';
2307 strcpy (fully_resolved_name
, true_pathname
);
2309 if (!posix_to_mac_pathname (fully_resolved_name
, mac_pathname
, MAXPATHLEN
+1))
2312 return unlink (mac_pathname
);
2318 sys_read (int fildes
, char *buf
, int count
)
2320 if (fildes
== 0) /* this should not be used for console input */
2323 #if __MSL__ >= 0x6000
2324 return _read (fildes
, buf
, count
);
2326 return read (fildes
, buf
, count
);
2333 sys_write (int fildes
, const char *buf
, int count
)
2335 if (fildes
== DEV_NULL_FD
)
2338 #if __MSL__ >= 0x6000
2339 return _write (fildes
, buf
, count
);
2341 return write (fildes
, buf
, count
);
2348 sys_rename (const char * old_name
, const char * new_name
)
2350 char true_old_pathname
[MAXPATHLEN
+1], true_new_pathname
[MAXPATHLEN
+1];
2351 char fully_resolved_old_name
[MAXPATHLEN
+1];
2353 char mac_old_name
[MAXPATHLEN
+1], mac_new_name
[MAXPATHLEN
+1];
2355 if (find_true_pathname (old_name
, true_old_pathname
, MAXPATHLEN
+1) == -1)
2358 len
= readlink (true_old_pathname
, fully_resolved_old_name
, MAXPATHLEN
);
2360 fully_resolved_old_name
[len
] = '\0';
2362 strcpy (fully_resolved_old_name
, true_old_pathname
);
2364 if (find_true_pathname (new_name
, true_new_pathname
, MAXPATHLEN
+1) == -1)
2367 if (strcmp (fully_resolved_old_name
, true_new_pathname
) == 0)
2370 if (!posix_to_mac_pathname (fully_resolved_old_name
,
2375 if (!posix_to_mac_pathname(true_new_pathname
, mac_new_name
, MAXPATHLEN
+1))
2378 /* If a file with new_name already exists, rename deletes the old
2379 file in Unix. CW version fails in these situation. So we add a
2380 call to unlink here. */
2381 (void) unlink (mac_new_name
);
2383 return rename (mac_old_name
, mac_new_name
);
2388 extern FILE *fopen (const char *name
, const char *mode
);
2390 sys_fopen (const char *name
, const char *mode
)
2392 char true_pathname
[MAXPATHLEN
+1], fully_resolved_name
[MAXPATHLEN
+1];
2394 char mac_pathname
[MAXPATHLEN
+1];
2396 if (find_true_pathname (name
, true_pathname
, MAXPATHLEN
+1) == -1)
2399 len
= readlink (true_pathname
, fully_resolved_name
, MAXPATHLEN
);
2401 fully_resolved_name
[len
] = '\0';
2403 strcpy (fully_resolved_name
, true_pathname
);
2405 if (!posix_to_mac_pathname (fully_resolved_name
, mac_pathname
, MAXPATHLEN
+1))
2410 if (mode
[0] == 'w' || mode
[0] == 'a')
2411 fsetfileinfo (mac_pathname
, 'EMAx', 'TEXT');
2412 #endif /* not __MRC__ */
2413 return fopen (mac_pathname
, mode
);
2418 #include "keyboard.h"
2419 extern Boolean
mac_wait_next_event (EventRecord
*, UInt32
, Boolean
);
2422 select (n
, rfds
, wfds
, efds
, timeout
)
2427 struct timeval
*timeout
;
2430 #if TARGET_API_MAC_CARBON
2431 EventTimeout timeout_sec
=
2433 ? (EMACS_SECS (*timeout
) * kEventDurationSecond
2434 + EMACS_USECS (*timeout
) * kEventDurationMicrosecond
)
2435 : kEventDurationForever
);
2438 err
= ReceiveNextEvent (0, NULL
, timeout_sec
, kEventLeaveInQueue
, NULL
);
2440 #else /* not TARGET_API_MAC_CARBON */
2442 UInt32 sleep_time
= EMACS_SECS (*timeout
) * 60 +
2443 ((EMACS_USECS (*timeout
) * 60) / 1000000);
2445 /* Can only handle wait for keyboard input. */
2446 if (n
> 1 || wfds
|| efds
)
2449 /* Also return true if an event other than a keyDown has occurred.
2450 This causes kbd_buffer_get_event in keyboard.c to call
2451 read_avail_input which in turn calls XTread_socket to poll for
2452 these events. Otherwise these never get processed except but a
2453 very slow poll timer. */
2454 if (mac_wait_next_event (&e
, sleep_time
, false))
2457 err
= -9875; /* eventLoopTimedOutErr */
2458 #endif /* not TARGET_API_MAC_CARBON */
2460 if (FD_ISSET (0, rfds
))
2471 if (input_polling_used ())
2473 /* It could be confusing if a real alarm arrives while
2474 processing the fake one. Turn it off and let the
2475 handler reset it. */
2476 extern void poll_for_input_1
P_ ((void));
2477 int old_poll_suppress_count
= poll_suppress_count
;
2478 poll_suppress_count
= 1;
2479 poll_for_input_1 ();
2480 poll_suppress_count
= old_poll_suppress_count
;
2490 /* Simulation of SIGALRM. The stub for function signal stores the
2491 signal handler function in alarm_signal_func if a SIGALRM is
2495 #include "syssignal.h"
2497 static TMTask mac_atimer_task
;
2499 static QElemPtr mac_atimer_qlink
= (QElemPtr
) &mac_atimer_task
;
2501 static int signal_mask
= 0;
2504 __sigfun alarm_signal_func
= (__sigfun
) 0;
2506 __signal_func_ptr alarm_signal_func
= (__signal_func_ptr
) 0;
2507 #else /* not __MRC__ and not __MWERKS__ */
2509 #endif /* not __MRC__ and not __MWERKS__ */
2513 extern __sigfun
signal (int signal
, __sigfun signal_func
);
2515 sys_signal (int signal_num
, __sigfun signal_func
)
2517 extern __signal_func_ptr
signal (int signal
, __signal_func_ptr signal_func
);
2519 sys_signal (int signal_num
, __signal_func_ptr signal_func
)
2520 #else /* not __MRC__ and not __MWERKS__ */
2522 #endif /* not __MRC__ and not __MWERKS__ */
2524 if (signal_num
!= SIGALRM
)
2525 return signal (signal_num
, signal_func
);
2529 __sigfun old_signal_func
;
2531 __signal_func_ptr old_signal_func
;
2535 old_signal_func
= alarm_signal_func
;
2536 alarm_signal_func
= signal_func
;
2537 return old_signal_func
;
2543 mac_atimer_handler (qlink
)
2546 if (alarm_signal_func
)
2547 (alarm_signal_func
) (SIGALRM
);
2552 set_mac_atimer (count
)
2555 static TimerUPP mac_atimer_handlerUPP
= NULL
;
2557 if (mac_atimer_handlerUPP
== NULL
)
2558 mac_atimer_handlerUPP
= NewTimerUPP (mac_atimer_handler
);
2559 mac_atimer_task
.tmCount
= 0;
2560 mac_atimer_task
.tmAddr
= mac_atimer_handlerUPP
;
2561 mac_atimer_qlink
= (QElemPtr
) &mac_atimer_task
;
2562 InsTime (mac_atimer_qlink
);
2564 PrimeTime (mac_atimer_qlink
, count
);
2569 remove_mac_atimer (remaining_count
)
2570 long *remaining_count
;
2572 if (mac_atimer_qlink
)
2574 RmvTime (mac_atimer_qlink
);
2575 if (remaining_count
)
2576 *remaining_count
= mac_atimer_task
.tmCount
;
2577 mac_atimer_qlink
= NULL
;
2589 int old_mask
= signal_mask
;
2591 signal_mask
|= mask
;
2593 if ((old_mask
^ signal_mask
) & sigmask (SIGALRM
))
2594 remove_mac_atimer (NULL
);
2601 sigsetmask (int mask
)
2603 int old_mask
= signal_mask
;
2607 if ((old_mask
^ signal_mask
) & sigmask (SIGALRM
))
2608 if (signal_mask
& sigmask (SIGALRM
))
2609 remove_mac_atimer (NULL
);
2611 set_mac_atimer (mac_atimer_task
.tmCount
);
2620 long remaining_count
;
2622 if (remove_mac_atimer (&remaining_count
) == 0)
2624 set_mac_atimer (seconds
* 1000);
2626 return remaining_count
/ 1000;
2630 mac_atimer_task
.tmCount
= seconds
* 1000;
2638 setitimer (which
, value
, ovalue
)
2640 const struct itimerval
*value
;
2641 struct itimerval
*ovalue
;
2643 long remaining_count
;
2644 long count
= (EMACS_SECS (value
->it_value
) * 1000
2645 + (EMACS_USECS (value
->it_value
) + 999) / 1000);
2647 if (remove_mac_atimer (&remaining_count
) == 0)
2651 bzero (ovalue
, sizeof (*ovalue
));
2652 EMACS_SET_SECS_USECS (ovalue
->it_value
, remaining_count
/ 1000,
2653 (remaining_count
% 1000) * 1000);
2655 set_mac_atimer (count
);
2658 mac_atimer_task
.tmCount
= count
;
2664 /* gettimeofday should return the amount of time (in a timeval
2665 structure) since midnight today. The toolbox function Microseconds
2666 returns the number of microseconds (in a UnsignedWide value) since
2667 the machine was booted. Also making this complicated is WideAdd,
2668 WideSubtract, etc. take wide values. */
2675 static wide wall_clock_at_epoch
, clicks_at_epoch
;
2676 UnsignedWide uw_microseconds
;
2677 wide w_microseconds
;
2678 time_t sys_time (time_t *);
2680 /* If this function is called for the first time, record the number
2681 of seconds since midnight and the number of microseconds since
2682 boot at the time of this first call. */
2687 systime
= sys_time (NULL
);
2688 /* Store microseconds since midnight in wall_clock_at_epoch. */
2689 WideMultiply (systime
, 1000000L, &wall_clock_at_epoch
);
2690 Microseconds (&uw_microseconds
);
2691 /* Store microseconds since boot in clicks_at_epoch. */
2692 clicks_at_epoch
.hi
= uw_microseconds
.hi
;
2693 clicks_at_epoch
.lo
= uw_microseconds
.lo
;
2696 /* Get time since boot */
2697 Microseconds (&uw_microseconds
);
2699 /* Convert to time since midnight*/
2700 w_microseconds
.hi
= uw_microseconds
.hi
;
2701 w_microseconds
.lo
= uw_microseconds
.lo
;
2702 WideSubtract (&w_microseconds
, &clicks_at_epoch
);
2703 WideAdd (&w_microseconds
, &wall_clock_at_epoch
);
2704 tp
->tv_sec
= WideDivide (&w_microseconds
, 1000000L, &tp
->tv_usec
);
2712 sleep (unsigned int seconds
)
2714 unsigned long time_up
;
2717 time_up
= TickCount () + seconds
* 60;
2718 while (TickCount () < time_up
)
2720 /* Accept no event; just wait. by T.I. */
2721 WaitNextEvent (0, &e
, 30, NULL
);
2726 #endif /* __MRC__ */
2729 /* The time functions adjust time values according to the difference
2730 between the Unix and CW epoches. */
2733 extern struct tm
*gmtime (const time_t *);
2735 sys_gmtime (const time_t *timer
)
2737 time_t unix_time
= *timer
+ CW_OR_MPW_UNIX_EPOCH_DIFF
;
2739 return gmtime (&unix_time
);
2744 extern struct tm
*localtime (const time_t *);
2746 sys_localtime (const time_t *timer
)
2748 #if __MSL__ >= 0x6000
2749 time_t unix_time
= *timer
;
2751 time_t unix_time
= *timer
+ CW_OR_MPW_UNIX_EPOCH_DIFF
;
2754 return localtime (&unix_time
);
2759 extern char *ctime (const time_t *);
2761 sys_ctime (const time_t *timer
)
2763 #if __MSL__ >= 0x6000
2764 time_t unix_time
= *timer
;
2766 time_t unix_time
= *timer
+ CW_OR_MPW_UNIX_EPOCH_DIFF
;
2769 return ctime (&unix_time
);
2774 extern time_t time (time_t *);
2776 sys_time (time_t *timer
)
2778 #if __MSL__ >= 0x6000
2779 time_t mac_time
= time (NULL
);
2781 time_t mac_time
= time (NULL
) - CW_OR_MPW_UNIX_EPOCH_DIFF
;
2791 /* no subprocesses, empty wait */
2801 croak (char *badfunc
)
2803 printf ("%s not yet implemented\r\n", badfunc
);
2809 mktemp (char *template)
2814 len
= strlen (template);
2816 while (k
>= 0 && template[k
] == 'X')
2819 k
++; /* make k index of first 'X' */
2823 /* Zero filled, number of digits equal to the number of X's. */
2824 sprintf (&template[k
], "%0*d", len
-k
, seqnum
++);
2833 /* Emulate getpwuid, getpwnam and others. */
2835 #define PASSWD_FIELD_SIZE 256
2837 static char my_passwd_name
[PASSWD_FIELD_SIZE
];
2838 static char my_passwd_dir
[MAXPATHLEN
+1];
2840 static struct passwd my_passwd
=
2846 static struct group my_group
=
2848 /* There are no groups on the mac, so we just return "root" as the
2854 /* Initialized by main () in macterm.c to pathname of emacs directory. */
2856 char emacs_passwd_dir
[MAXPATHLEN
+1];
2862 init_emacs_passwd_dir ()
2866 if (getwd (emacs_passwd_dir
) && getwd (my_passwd_dir
))
2868 /* Need pathname of first ancestor that begins with "emacs"
2869 since Mac emacs application is somewhere in the emacs-*
2871 int len
= strlen (emacs_passwd_dir
);
2873 /* j points to the "/" following the directory name being
2876 while (i
>= 0 && !found
)
2878 while (i
>= 0 && emacs_passwd_dir
[i
] != '/')
2880 if (emacs_passwd_dir
[i
] == '/' && i
+5 < len
)
2881 found
= (strncmp (&(emacs_passwd_dir
[i
+1]), "emacs", 5) == 0);
2883 emacs_passwd_dir
[j
+1] = '\0';
2894 /* Setting to "/" probably won't work but set it to something
2896 strcpy (emacs_passwd_dir
, "/");
2897 strcpy (my_passwd_dir
, "/");
2902 static struct passwd emacs_passwd
=
2908 static int my_passwd_inited
= 0;
2916 /* Note: my_passwd_dir initialized in int_emacs_passwd_dir to
2917 directory where Emacs was started. */
2919 owner_name
= (char **) GetResource ('STR ',-16096);
2923 BlockMove ((unsigned char *) *owner_name
,
2924 (unsigned char *) my_passwd_name
,
2926 HUnlock (owner_name
);
2927 p2cstr ((unsigned char *) my_passwd_name
);
2930 my_passwd_name
[0] = 0;
2935 getpwuid (uid_t uid
)
2937 if (!my_passwd_inited
)
2940 my_passwd_inited
= 1;
2948 getgrgid (gid_t gid
)
2955 getpwnam (const char *name
)
2957 if (strcmp (name
, "emacs") == 0)
2958 return &emacs_passwd
;
2960 if (!my_passwd_inited
)
2963 my_passwd_inited
= 1;
2970 /* The functions fork, kill, sigsetmask, sigblock, request_sigio,
2971 setpgrp, setpriority, and unrequest_sigio are defined to be empty
2992 error ("Can't spawn subshell");
2997 request_sigio (void)
3003 unrequest_sigio (void)
3018 pipe (int _fildes
[2])
3025 /* Hard and symbolic links. */
3028 symlink (const char *name1
, const char *name2
)
3036 link (const char *name1
, const char *name2
)
3042 #endif /* ! MAC_OSX */
3044 /* Determine the path name of the file specified by VREFNUM, DIRID,
3045 and NAME and place that in the buffer PATH of length
3048 path_from_vol_dir_name (char *path
, int man_path_len
, short vol_ref_num
,
3049 long dir_id
, ConstStr255Param name
)
3055 if (strlen (name
) > man_path_len
)
3058 memcpy (dir_name
, name
, name
[0]+1);
3059 memcpy (path
, name
, name
[0]+1);
3062 cipb
.dirInfo
.ioDrParID
= dir_id
;
3063 cipb
.dirInfo
.ioNamePtr
= dir_name
;
3067 cipb
.dirInfo
.ioVRefNum
= vol_ref_num
;
3068 cipb
.dirInfo
.ioFDirIndex
= -1;
3069 cipb
.dirInfo
.ioDrDirID
= cipb
.dirInfo
.ioDrParID
;
3070 /* go up to parent each time */
3072 err
= PBGetCatInfo (&cipb
, false);
3077 if (strlen (dir_name
) + strlen (path
) + 1 >= man_path_len
)
3080 strcat (dir_name
, ":");
3081 strcat (dir_name
, path
);
3082 /* attach to front since we're going up directory tree */
3083 strcpy (path
, dir_name
);
3085 while (cipb
.dirInfo
.ioDrDirID
!= fsRtDirID
);
3086 /* stop when we see the volume's root directory */
3088 return 1; /* success */
3095 posix_pathname_to_fsspec (ufn
, fs
)
3099 Str255 mac_pathname
;
3101 if (posix_to_mac_pathname (ufn
, mac_pathname
, sizeof (mac_pathname
)) == 0)
3105 c2pstr (mac_pathname
);
3106 return FSMakeFSSpec (0, 0, mac_pathname
, fs
);
3111 fsspec_to_posix_pathname (fs
, ufn
, ufnbuflen
)
3116 char mac_pathname
[MAXPATHLEN
];
3118 if (path_from_vol_dir_name (mac_pathname
, sizeof (mac_pathname
) - 1,
3119 fs
->vRefNum
, fs
->parID
, fs
->name
)
3120 && mac_to_posix_pathname (mac_pathname
, ufn
, ufnbuflen
))
3127 readlink (const char *path
, char *buf
, int bufsiz
)
3129 char mac_sym_link_name
[MAXPATHLEN
+1];
3132 Boolean target_is_folder
, was_aliased
;
3133 Str255 directory_name
, mac_pathname
;
3136 if (posix_to_mac_pathname (path
, mac_sym_link_name
, MAXPATHLEN
+1) == 0)
3139 c2pstr (mac_sym_link_name
);
3140 err
= FSMakeFSSpec (0, 0, mac_sym_link_name
, &fsspec
);
3147 err
= ResolveAliasFile (&fsspec
, true, &target_is_folder
, &was_aliased
);
3148 if (err
!= noErr
|| !was_aliased
)
3154 if (path_from_vol_dir_name (mac_pathname
, 255, fsspec
.vRefNum
, fsspec
.parID
,
3161 if (mac_to_posix_pathname (mac_pathname
, buf
, bufsiz
) == 0)
3167 return strlen (buf
);
3171 /* Convert a path to one with aliases fully expanded. */
3174 find_true_pathname (const char *path
, char *buf
, int bufsiz
)
3176 char *q
, temp
[MAXPATHLEN
+1];
3180 if (bufsiz
<= 0 || path
== 0 || path
[0] == '\0')
3187 q
= strchr (p
+ 1, '/');
3189 q
= strchr (p
, '/');
3190 len
= 0; /* loop may not be entered, e.g., for "/" */
3195 strncat (temp
, p
, q
- p
);
3196 len
= readlink (temp
, buf
, bufsiz
);
3199 if (strlen (temp
) + 1 > bufsiz
)
3209 if (len
+ strlen (p
) + 1 >= bufsiz
)
3213 return len
+ strlen (p
);
3218 umask (mode_t numask
)
3220 static mode_t mask
= 022;
3221 mode_t oldmask
= mask
;
3228 chmod (const char *path
, mode_t mode
)
3230 /* say it always succeed for now */
3236 fchmod (int fd
, mode_t mode
)
3238 /* say it always succeed for now */
3244 fchown (int fd
, uid_t owner
, gid_t group
)
3246 /* say it always succeed for now */
3255 return fcntl (oldd
, F_DUPFD
, 0);
3257 /* current implementation of fcntl in fcntl.mac.c simply returns old
3259 return fcntl (oldd
, F_DUPFD
);
3266 /* This is from the original sysdep.c. Emulate BSD dup2. First close
3267 newd if it already exists. Then, attempt to dup oldd. If not
3268 successful, call dup2 recursively until we are, then close the
3269 unsuccessful ones. */
3272 dup2 (int oldd
, int newd
)
3283 ret
= dup2 (oldd
, newd
);
3289 /* let it fail for now */
3306 ioctl (int d
, int request
, void *argp
)
3316 if (fildes
>=0 && fildes
<= 2)
3349 #endif /* __MRC__ */
3353 #if __MSL__ < 0x6000
3361 #endif /* __MWERKS__ */
3363 #endif /* ! MAC_OSX */
3366 /* Return the path to the directory in which Emacs can create
3367 temporary files. The MacOS "temporary items" directory cannot be
3368 used because it removes the file written by a process when it
3369 exits. In that sense it's more like "/dev/null" than "/tmp" (but
3370 again not exactly). And of course Emacs needs to read back the
3371 files written by its subprocesses. So here we write the files to a
3372 directory "Emacs" in the Preferences Folder. This directory is
3373 created if it does not exist. */
3376 get_temp_dir_name ()
3378 static char *temp_dir_name
= NULL
;
3383 char unix_dir_name
[MAXPATHLEN
+1];
3386 /* Cache directory name with pointer temp_dir_name.
3387 Look for it only the first time. */
3390 err
= FindFolder (kOnSystemDisk
, kPreferencesFolderType
, kCreateFolder
,
3391 &vol_ref_num
, &dir_id
);
3395 if (!path_from_vol_dir_name (full_path
, 255, vol_ref_num
, dir_id
, "\p"))
3398 if (strlen (full_path
) + 6 <= MAXPATHLEN
)
3399 strcat (full_path
, "Emacs:");
3403 if (!mac_to_posix_pathname (full_path
, unix_dir_name
, MAXPATHLEN
+1))
3406 dir
= opendir (unix_dir_name
); /* check whether temp directory exists */
3409 else if (mkdir (unix_dir_name
, 0700) != 0) /* create it if not */
3412 temp_dir_name
= (char *) malloc (strlen (unix_dir_name
) + 1);
3413 strcpy (temp_dir_name
, unix_dir_name
);
3416 return temp_dir_name
;
3421 /* Allocate and construct an array of pointers to strings from a list
3422 of strings stored in a 'STR#' resource. The returned pointer array
3423 is stored in the style of argv and environ: if the 'STR#' resource
3424 contains numString strings, a pointer array with numString+1
3425 elements is returned in which the last entry contains a null
3426 pointer. The pointer to the pointer array is passed by pointer in
3427 parameter t. The resource ID of the 'STR#' resource is passed in
3428 parameter StringListID.
3432 get_string_list (char ***t
, short string_list_id
)
3438 h
= GetResource ('STR#', string_list_id
);
3443 num_strings
= * (short *) p
;
3445 *t
= (char **) malloc (sizeof (char *) * (num_strings
+ 1));
3446 for (i
= 0; i
< num_strings
; i
++)
3448 short length
= *p
++;
3449 (*t
)[i
] = (char *) malloc (length
+ 1);
3450 strncpy ((*t
)[i
], p
, length
);
3451 (*t
)[i
][length
] = '\0';
3454 (*t
)[num_strings
] = 0;
3459 /* Return no string in case GetResource fails. Bug fixed by
3460 Ikegami Tsutomu. Caused MPW build to crash without sym -on
3461 option (no sym -on implies -opt local). */
3462 *t
= (char **) malloc (sizeof (char *));
3469 get_path_to_system_folder ()
3475 static char system_folder_unix_name
[MAXPATHLEN
+1];
3478 err
= FindFolder (kOnSystemDisk
, kSystemFolderType
, kDontCreateFolder
,
3479 &vol_ref_num
, &dir_id
);
3483 if (!path_from_vol_dir_name (full_path
, 255, vol_ref_num
, dir_id
, "\p"))
3486 if (!mac_to_posix_pathname (full_path
, system_folder_unix_name
,
3490 return system_folder_unix_name
;
3496 #define ENVIRON_STRING_LIST_ID 128
3498 /* Get environment variable definitions from STR# resource. */
3505 get_string_list (&environ
, ENVIRON_STRING_LIST_ID
);
3511 /* Make HOME directory the one Emacs starts up in if not specified
3513 if (getenv ("HOME") == NULL
)
3515 environ
= (char **) realloc (environ
, sizeof (char *) * (i
+ 2));
3518 environ
[i
] = (char *) malloc (strlen (my_passwd_dir
) + 6);
3521 strcpy (environ
[i
], "HOME=");
3522 strcat (environ
[i
], my_passwd_dir
);
3529 /* Make HOME directory the one Emacs starts up in if not specified
3531 if (getenv ("MAIL") == NULL
)
3533 environ
= (char **) realloc (environ
, sizeof (char *) * (i
+ 2));
3536 char * path_to_system_folder
= get_path_to_system_folder ();
3537 environ
[i
] = (char *) malloc (strlen (path_to_system_folder
) + 22);
3540 strcpy (environ
[i
], "MAIL=");
3541 strcat (environ
[i
], path_to_system_folder
);
3542 strcat (environ
[i
], "Eudora Folder/In");
3550 /* Return the value of the environment variable NAME. */
3553 getenv (const char *name
)
3555 int length
= strlen(name
);
3558 for (e
= environ
; *e
!= 0; e
++)
3559 if (strncmp(*e
, name
, length
) == 0 && (*e
)[length
] == '=')
3560 return &(*e
)[length
+ 1];
3562 if (strcmp (name
, "TMPDIR") == 0)
3563 return get_temp_dir_name ();
3570 /* see Interfaces&Libraries:Interfaces:CIncludes:signal.h */
3571 char *sys_siglist
[] =
3573 "Zero is not a signal!!!",
3575 "Interactive user interrupt", /* 2 */ "?",
3576 "Floating point exception", /* 4 */ "?", "?", "?",
3577 "Illegal instruction", /* 8 */ "?", "?", "?", "?", "?", "?", "?",
3578 "Segment violation", /* 16 */ "?", "?", "?", "?", "?", "?", "?",
3579 "?", "?", "?", "?", "?", "?", "?", "?",
3583 char *sys_siglist
[] =
3585 "Zero is not a signal!!!",
3587 "Floating point exception",
3588 "Illegal instruction",
3589 "Interactive user interrupt",
3590 "Segment violation",
3593 #else /* not __MRC__ and not __MWERKS__ */
3595 #endif /* not __MRC__ and not __MWERKS__ */
3598 #include <utsname.h>
3601 uname (struct utsname
*name
)
3604 system_name
= GetString (-16413); /* IM - Resource Manager Reference */
3607 BlockMove (*system_name
, name
->nodename
, (*system_name
)[0]+1);
3608 p2cstr (name
->nodename
);
3616 /* Event class of HLE sent to subprocess. */
3617 const OSType kEmacsSubprocessSend
= 'ESND';
3619 /* Event class of HLE sent back from subprocess. */
3620 const OSType kEmacsSubprocessReply
= 'ERPY';
3624 mystrchr (char *s
, char c
)
3626 while (*s
&& *s
!= c
)
3654 mystrcpy (char *to
, char *from
)
3666 /* Start a Mac subprocess. Arguments for it is passed in argv (null
3667 terminated). The process should run with the default directory
3668 "workdir", read input from "infn", and write output and error to
3669 "outfn" and "errfn", resp. The Process Manager call
3670 LaunchApplication is used to start the subprocess. We use high
3671 level events as the mechanism to pass arguments to the subprocess
3672 and to make Emacs wait for the subprocess to terminate and pass
3673 back a result code. The bulk of the code here packs the arguments
3674 into one message to be passed together with the high level event.
3675 Emacs also sometimes starts a subprocess using a shell to perform
3676 wildcard filename expansion. Since we don't really have a shell on
3677 the Mac, this case is detected and the starting of the shell is
3678 by-passed. We really need to add code here to do filename
3679 expansion to support such functionality.
3681 We can't use this strategy in Carbon because the High Level Event
3682 APIs are not available. */
3685 run_mac_command (argv
, workdir
, infn
, outfn
, errfn
)
3686 unsigned char **argv
;
3687 const char *workdir
;
3688 const char *infn
, *outfn
, *errfn
;
3690 #if TARGET_API_MAC_CARBON
3692 #else /* not TARGET_API_MAC_CARBON */
3693 char macappname
[MAXPATHLEN
+1], macworkdir
[MAXPATHLEN
+1];
3694 char macinfn
[MAXPATHLEN
+1], macoutfn
[MAXPATHLEN
+1], macerrfn
[MAXPATHLEN
+1];
3695 int paramlen
, argc
, newargc
, j
, retries
;
3696 char **newargv
, *param
, *p
;
3699 LaunchParamBlockRec lpbr
;
3700 EventRecord send_event
, reply_event
;
3701 RgnHandle cursor_region_handle
;
3703 unsigned long ref_con
, len
;
3705 if (posix_to_mac_pathname (workdir
, macworkdir
, MAXPATHLEN
+1) == 0)
3707 if (posix_to_mac_pathname (infn
, macinfn
, MAXPATHLEN
+1) == 0)
3709 if (posix_to_mac_pathname (outfn
, macoutfn
, MAXPATHLEN
+1) == 0)
3711 if (posix_to_mac_pathname (errfn
, macerrfn
, MAXPATHLEN
+1) == 0)
3714 paramlen
= strlen (macworkdir
) + strlen (macinfn
) + strlen (macoutfn
)
3715 + strlen (macerrfn
) + 4; /* count nulls at end of strings */
3724 /* If a subprocess is invoked with a shell, we receive 3 arguments
3725 of the form: "<path to emacs bins>/sh" "-c" "<path to emacs
3726 bins>/<command> <command args>" */
3727 j
= strlen (argv
[0]);
3728 if (j
>= 3 && strcmp (argv
[0]+j
-3, "/sh") == 0
3729 && argc
== 3 && strcmp (argv
[1], "-c") == 0)
3731 char *command
, *t
, tempmacpathname
[MAXPATHLEN
+1];
3733 /* The arguments for the command in argv[2] are separated by
3734 spaces. Count them and put the count in newargc. */
3735 command
= (char *) alloca (strlen (argv
[2])+2);
3736 strcpy (command
, argv
[2]);
3737 if (command
[strlen (command
) - 1] != ' ')
3738 strcat (command
, " ");
3742 t
= mystrchr (t
, ' ');
3746 t
= mystrchr (t
+1, ' ');
3749 newargv
= (char **) alloca (sizeof (char *) * newargc
);
3752 for (j
= 0; j
< newargc
; j
++)
3754 newargv
[j
] = (char *) alloca (strlen (t
) + 1);
3755 mystrcpy (newargv
[j
], t
);
3758 paramlen
+= strlen (newargv
[j
]) + 1;
3761 if (strncmp (newargv
[0], "~emacs/", 7) == 0)
3763 if (posix_to_mac_pathname (newargv
[0], tempmacpathname
, MAXPATHLEN
+1)
3768 { /* sometimes Emacs call "sh" without a path for the command */
3770 char *t
= (char *) alloca (strlen (newargv
[0]) + 7 + 1);
3771 strcpy (t
, "~emacs/");
3772 strcat (t
, newargv
[0]);
3775 openp (Vexec_path
, build_string (newargv
[0]), Vexec_suffixes
, &path
,
3776 make_number (X_OK
));
3780 if (posix_to_mac_pathname (SDATA (path
), tempmacpathname
,
3784 strcpy (macappname
, tempmacpathname
);
3788 if (posix_to_mac_pathname (argv
[0], macappname
, MAXPATHLEN
+1) == 0)
3791 newargv
= (char **) alloca (sizeof (char *) * argc
);
3793 for (j
= 1; j
< argc
; j
++)
3795 if (strncmp (argv
[j
], "~emacs/", 7) == 0)
3797 char *t
= strchr (argv
[j
], ' ');
3800 char tempcmdname
[MAXPATHLEN
+1], tempmaccmdname
[MAXPATHLEN
+1];
3801 strncpy (tempcmdname
, argv
[j
], t
-argv
[j
]);
3802 tempcmdname
[t
-argv
[j
]] = '\0';
3803 if (posix_to_mac_pathname (tempcmdname
, tempmaccmdname
,
3806 newargv
[j
] = (char *) alloca (strlen (tempmaccmdname
)
3808 strcpy (newargv
[j
], tempmaccmdname
);
3809 strcat (newargv
[j
], t
);
3813 char tempmaccmdname
[MAXPATHLEN
+1];
3814 if (posix_to_mac_pathname (argv
[j
], tempmaccmdname
,
3817 newargv
[j
] = (char *) alloca (strlen (tempmaccmdname
)+1);
3818 strcpy (newargv
[j
], tempmaccmdname
);
3822 newargv
[j
] = argv
[j
];
3823 paramlen
+= strlen (newargv
[j
]) + 1;
3827 /* After expanding all the arguments, we now know the length of the
3828 parameter block to be sent to the subprocess as a message
3829 attached to the HLE. */
3830 param
= (char *) malloc (paramlen
+ 1);
3836 /* first byte of message contains number of arguments for command */
3837 strcpy (p
, macworkdir
);
3838 p
+= strlen (macworkdir
);
3840 /* null terminate strings sent so it's possible to use strcpy over there */
3841 strcpy (p
, macinfn
);
3842 p
+= strlen (macinfn
);
3844 strcpy (p
, macoutfn
);
3845 p
+= strlen (macoutfn
);
3847 strcpy (p
, macerrfn
);
3848 p
+= strlen (macerrfn
);
3850 for (j
= 1; j
< newargc
; j
++)
3852 strcpy (p
, newargv
[j
]);
3853 p
+= strlen (newargv
[j
]);
3857 c2pstr (macappname
);
3859 iErr
= FSMakeFSSpec (0, 0, macappname
, &spec
);
3867 lpbr
.launchBlockID
= extendedBlock
;
3868 lpbr
.launchEPBLength
= extendedBlockLen
;
3869 lpbr
.launchControlFlags
= launchContinue
+ launchNoFileFlags
;
3870 lpbr
.launchAppSpec
= &spec
;
3871 lpbr
.launchAppParameters
= NULL
;
3873 iErr
= LaunchApplication (&lpbr
); /* call the subprocess */
3880 send_event
.what
= kHighLevelEvent
;
3881 send_event
.message
= kEmacsSubprocessSend
;
3882 /* Event ID stored in "where" unused */
3885 /* OS may think current subprocess has terminated if previous one
3886 terminated recently. */
3889 iErr
= PostHighLevelEvent (&send_event
, &lpbr
.launchProcessSN
, 0, param
,
3890 paramlen
+ 1, receiverIDisPSN
);
3892 while (iErr
== sessClosedErr
&& retries
-- > 0);
3900 cursor_region_handle
= NewRgn ();
3902 /* Wait for the subprocess to finish, when it will send us a ERPY
3903 high level event. */
3905 if (WaitNextEvent (highLevelEventMask
, &reply_event
, 180,
3906 cursor_region_handle
)
3907 && reply_event
.message
== kEmacsSubprocessReply
)
3910 /* The return code is sent through the refCon */
3911 iErr
= AcceptHighLevelEvent (&targ
, &ref_con
, NULL
, &len
);
3914 DisposeHandle ((Handle
) cursor_region_handle
);
3919 DisposeHandle ((Handle
) cursor_region_handle
);
3923 #endif /* not TARGET_API_MAC_CARBON */
3928 opendir (const char *dirname
)
3930 char true_pathname
[MAXPATHLEN
+1], fully_resolved_name
[MAXPATHLEN
+1];
3931 char mac_pathname
[MAXPATHLEN
+1], vol_name
[MAXPATHLEN
+1];
3935 int len
, vol_name_len
;
3937 if (find_true_pathname (dirname
, true_pathname
, MAXPATHLEN
+1) == -1)
3940 len
= readlink (true_pathname
, fully_resolved_name
, MAXPATHLEN
);
3942 fully_resolved_name
[len
] = '\0';
3944 strcpy (fully_resolved_name
, true_pathname
);
3946 dirp
= (DIR *) malloc (sizeof(DIR));
3950 /* Handle special case when dirname is "/": sets up for readir to
3951 get all mount volumes. */
3952 if (strcmp (fully_resolved_name
, "/") == 0)
3954 dirp
->getting_volumes
= 1; /* special all mounted volumes DIR struct */
3955 dirp
->current_index
= 1; /* index for first volume */
3959 /* Handle typical cases: not accessing all mounted volumes. */
3960 if (!posix_to_mac_pathname (fully_resolved_name
, mac_pathname
, MAXPATHLEN
+1))
3963 /* Emacs calls opendir without the trailing '/', Mac needs trailing ':' */
3964 len
= strlen (mac_pathname
);
3965 if (mac_pathname
[len
- 1] != ':' && len
< MAXPATHLEN
)
3966 strcat (mac_pathname
, ":");
3968 /* Extract volume name */
3969 vol_name_len
= strchr (mac_pathname
, ':') - mac_pathname
;
3970 strncpy (vol_name
, mac_pathname
, vol_name_len
);
3971 vol_name
[vol_name_len
] = '\0';
3972 strcat (vol_name
, ":");
3974 c2pstr (mac_pathname
);
3975 cipb
.hFileInfo
.ioNamePtr
= mac_pathname
;
3976 /* using full pathname so vRefNum and DirID ignored */
3977 cipb
.hFileInfo
.ioVRefNum
= 0;
3978 cipb
.hFileInfo
.ioDirID
= 0;
3979 cipb
.hFileInfo
.ioFDirIndex
= 0;
3980 /* set to 0 to get information about specific dir or file */
3982 errno
= PBGetCatInfo (&cipb
, false);
3989 if (!(cipb
.hFileInfo
.ioFlAttrib
& 0x10)) /* bit 4 = 1 for directories */
3990 return 0; /* not a directory */
3992 dirp
->dir_id
= cipb
.dirInfo
.ioDrDirID
; /* used later in readdir */
3993 dirp
->getting_volumes
= 0;
3994 dirp
->current_index
= 1; /* index for first file/directory */
3997 vpb
.ioNamePtr
= vol_name
;
3998 /* using full pathname so vRefNum and DirID ignored */
4000 vpb
.ioVolIndex
= -1;
4001 errno
= PBHGetVInfo ((union HParamBlockRec
*) &vpb
, false);
4008 dirp
->vol_ref_num
= vpb
.ioVRefNum
;
4025 HParamBlockRec hpblock
;
4027 static struct dirent s_dirent
;
4028 static Str255 s_name
;
4032 /* Handle the root directory containing the mounted volumes. Call
4033 PBHGetVInfo specifying an index to obtain the info for a volume.
4034 PBHGetVInfo returns an error when it receives an index beyond the
4035 last volume, at which time we should return a nil dirent struct
4037 if (dp
->getting_volumes
)
4039 hpblock
.volumeParam
.ioNamePtr
= s_name
;
4040 hpblock
.volumeParam
.ioVRefNum
= 0;
4041 hpblock
.volumeParam
.ioVolIndex
= dp
->current_index
;
4043 errno
= PBHGetVInfo (&hpblock
, false);
4051 strcat (s_name
, "/"); /* need "/" for stat to work correctly */
4053 dp
->current_index
++;
4055 s_dirent
.d_ino
= hpblock
.volumeParam
.ioVRefNum
;
4056 s_dirent
.d_name
= s_name
;
4062 cipb
.hFileInfo
.ioVRefNum
= dp
->vol_ref_num
;
4063 cipb
.hFileInfo
.ioNamePtr
= s_name
;
4064 /* location to receive filename returned */
4066 /* return only visible files */
4070 cipb
.hFileInfo
.ioDirID
= dp
->dir_id
;
4071 /* directory ID found by opendir */
4072 cipb
.hFileInfo
.ioFDirIndex
= dp
->current_index
;
4074 errno
= PBGetCatInfo (&cipb
, false);
4081 /* insist on a visible entry */
4082 if (cipb
.hFileInfo
.ioFlAttrib
& 0x10) /* directory? */
4083 done
= !(cipb
.dirInfo
.ioDrUsrWds
.frFlags
& fInvisible
);
4085 done
= !(cipb
.hFileInfo
.ioFlFndrInfo
.fdFlags
& fInvisible
);
4087 dp
->current_index
++;
4100 s_dirent
.d_ino
= cipb
.dirInfo
.ioDrDirID
;
4101 /* value unimportant: non-zero for valid file */
4102 s_dirent
.d_name
= s_name
;
4112 char mac_pathname
[MAXPATHLEN
+1];
4113 Str255 directory_name
;
4117 if (path_from_vol_dir_name (mac_pathname
, 255, 0, 0, "\p") == 0)
4120 if (mac_to_posix_pathname (mac_pathname
, path
, MAXPATHLEN
+1) == 0)
4126 #endif /* ! MAC_OSX */
4130 initialize_applescript ()
4135 /* if open fails, as_scripting_component is set to NULL. Its
4136 subsequent use in OSA calls will fail with badComponentInstance
4138 as_scripting_component
= OpenDefaultComponent (kOSAComponentType
,
4139 kAppleScriptSubtype
);
4141 null_desc
.descriptorType
= typeNull
;
4142 null_desc
.dataHandle
= 0;
4143 osaerror
= OSAMakeContext (as_scripting_component
, &null_desc
,
4144 kOSANullScript
, &as_script_context
);
4146 as_script_context
= kOSANullScript
;
4147 /* use default context if create fails */
4152 terminate_applescript()
4154 OSADispose (as_scripting_component
, as_script_context
);
4155 CloseComponent (as_scripting_component
);
4158 /* Convert a lisp string to the 4 byte character code. */
4161 mac_get_code_from_arg(Lisp_Object arg
, OSType defCode
)
4170 /* check type string */
4172 if (SBYTES (arg
) != 4)
4174 error ("Wrong argument: need string of length 4 for code");
4176 result
= EndianU32_BtoN (*((UInt32
*) SDATA (arg
)));
4181 /* Convert the 4 byte character code into a 4 byte string. */
4184 mac_get_object_from_code(OSType defCode
)
4186 UInt32 code
= EndianU32_NtoB (defCode
);
4188 return make_unibyte_string ((char *)&code
, 4);
4192 DEFUN ("mac-get-file-creator", Fmac_get_file_creator
, Smac_get_file_creator
, 1, 1, 0,
4193 doc
: /* Get the creator code of FILENAME as a four character string. */)
4195 Lisp_Object filename
;
4203 Lisp_Object result
= Qnil
;
4204 CHECK_STRING (filename
);
4206 if (NILP(Ffile_exists_p(filename
)) || !NILP(Ffile_directory_p(filename
))) {
4209 filename
= Fexpand_file_name (filename
, Qnil
);
4213 status
= FSPathMakeRef(SDATA(ENCODE_FILE(filename
)), &fref
, NULL
);
4215 status
= posix_pathname_to_fsspec (SDATA (ENCODE_FILE (filename
)), &fss
);
4218 if (status
== noErr
)
4221 FSCatalogInfo catalogInfo
;
4223 status
= FSGetCatalogInfo(&fref
, kFSCatInfoFinderInfo
,
4224 &catalogInfo
, NULL
, NULL
, NULL
);
4228 status
= FSpGetFInfo (&fss
, &finder_info
);
4230 if (status
== noErr
)
4233 result
= mac_get_object_from_code(((FileInfo
*)&catalogInfo
.finderInfo
)->fileCreator
);
4235 result
= mac_get_object_from_code (finder_info
.fdCreator
);
4240 if (status
!= noErr
) {
4241 error ("Error while getting file information.");
4246 DEFUN ("mac-get-file-type", Fmac_get_file_type
, Smac_get_file_type
, 1, 1, 0,
4247 doc
: /* Get the type code of FILENAME as a four character string. */)
4249 Lisp_Object filename
;
4257 Lisp_Object result
= Qnil
;
4258 CHECK_STRING (filename
);
4260 if (NILP(Ffile_exists_p(filename
)) || !NILP(Ffile_directory_p(filename
))) {
4263 filename
= Fexpand_file_name (filename
, Qnil
);
4267 status
= FSPathMakeRef(SDATA(ENCODE_FILE(filename
)), &fref
, NULL
);
4269 status
= posix_pathname_to_fsspec (SDATA (ENCODE_FILE (filename
)), &fss
);
4272 if (status
== noErr
)
4275 FSCatalogInfo catalogInfo
;
4277 status
= FSGetCatalogInfo(&fref
, kFSCatInfoFinderInfo
,
4278 &catalogInfo
, NULL
, NULL
, NULL
);
4282 status
= FSpGetFInfo (&fss
, &finder_info
);
4284 if (status
== noErr
)
4287 result
= mac_get_object_from_code(((FileInfo
*)&catalogInfo
.finderInfo
)->fileType
);
4289 result
= mac_get_object_from_code (finder_info
.fdType
);
4294 if (status
!= noErr
) {
4295 error ("Error while getting file information.");
4300 DEFUN ("mac-set-file-creator", Fmac_set_file_creator
, Smac_set_file_creator
, 1, 2, 0,
4301 doc
: /* Set creator code of file FILENAME to CODE.
4302 If non-nil, CODE must be a 4-character string. Otherwise, 'EMAx' is
4303 assumed. Return non-nil if successful. */)
4305 Lisp_Object filename
, code
;
4314 CHECK_STRING (filename
);
4316 cCode
= mac_get_code_from_arg(code
, 'EMAx');
4318 if (NILP(Ffile_exists_p(filename
)) || !NILP(Ffile_directory_p(filename
))) {
4321 filename
= Fexpand_file_name (filename
, Qnil
);
4325 status
= FSPathMakeRef(SDATA(ENCODE_FILE(filename
)), &fref
, NULL
);
4327 status
= posix_pathname_to_fsspec (SDATA (ENCODE_FILE (filename
)), &fss
);
4330 if (status
== noErr
)
4333 FSCatalogInfo catalogInfo
;
4335 status
= FSGetCatalogInfo(&fref
, kFSCatInfoFinderInfo
,
4336 &catalogInfo
, NULL
, NULL
, &parentDir
);
4340 status
= FSpGetFInfo (&fss
, &finder_info
);
4342 if (status
== noErr
)
4345 ((FileInfo
*)&catalogInfo
.finderInfo
)->fileCreator
= cCode
;
4346 status
= FSSetCatalogInfo(&fref
, kFSCatInfoFinderInfo
, &catalogInfo
);
4347 /* TODO: on Mac OS 10.2, we need to touch the parent dir, FNNotify? */
4349 finder_info
.fdCreator
= cCode
;
4350 status
= FSpSetFInfo (&fss
, &finder_info
);
4355 if (status
!= noErr
) {
4356 error ("Error while setting creator information.");
4361 DEFUN ("mac-set-file-type", Fmac_set_file_type
, Smac_set_file_type
, 2, 2, 0,
4362 doc
: /* Set file code of file FILENAME to CODE.
4363 CODE must be a 4-character string. Return non-nil if successful. */)
4365 Lisp_Object filename
, code
;
4374 CHECK_STRING (filename
);
4376 cCode
= mac_get_code_from_arg(code
, 0); /* Default to empty code*/
4378 if (NILP(Ffile_exists_p(filename
)) || !NILP(Ffile_directory_p(filename
))) {
4381 filename
= Fexpand_file_name (filename
, Qnil
);
4385 status
= FSPathMakeRef(SDATA(ENCODE_FILE(filename
)), &fref
, NULL
);
4387 status
= posix_pathname_to_fsspec (SDATA (ENCODE_FILE (filename
)), &fss
);
4390 if (status
== noErr
)
4393 FSCatalogInfo catalogInfo
;
4395 status
= FSGetCatalogInfo(&fref
, kFSCatInfoFinderInfo
,
4396 &catalogInfo
, NULL
, NULL
, &parentDir
);
4400 status
= FSpGetFInfo (&fss
, &finder_info
);
4402 if (status
== noErr
)
4405 ((FileInfo
*)&catalogInfo
.finderInfo
)->fileType
= cCode
;
4406 status
= FSSetCatalogInfo(&fref
, kFSCatInfoFinderInfo
, &catalogInfo
);
4407 /* TODO: on Mac OS 10.2, we need to touch the parent dir, FNNotify? */
4409 finder_info
.fdType
= cCode
;
4410 status
= FSpSetFInfo (&fss
, &finder_info
);
4415 if (status
!= noErr
) {
4416 error ("Error while setting creator information.");
4422 /* Compile and execute the AppleScript SCRIPT and return the error
4423 status as function value. A zero is returned if compilation and
4424 execution is successful, in which case *RESULT is set to a Lisp
4425 string containing the resulting script value. Otherwise, the Mac
4426 error code is returned and *RESULT is set to an error Lisp string.
4427 For documentation on the MacOS scripting architecture, see Inside
4428 Macintosh - Interapplication Communications: Scripting
4432 do_applescript (script
, result
)
4433 Lisp_Object script
, *result
;
4435 AEDesc script_desc
, result_desc
, error_desc
, *desc
= NULL
;
4441 if (!as_scripting_component
)
4442 initialize_applescript();
4444 error
= AECreateDesc (typeChar
, SDATA (script
), SBYTES (script
),
4449 osaerror
= OSADoScript (as_scripting_component
, &script_desc
, kOSANullScript
,
4450 typeChar
, kOSAModeNull
, &result_desc
);
4452 if (osaerror
== noErr
)
4453 /* success: retrieve resulting script value */
4454 desc
= &result_desc
;
4455 else if (osaerror
== errOSAScriptError
)
4456 /* error executing AppleScript: retrieve error message */
4457 if (!OSAScriptError (as_scripting_component
, kOSAErrorMessage
, typeChar
,
4463 #if TARGET_API_MAC_CARBON
4464 *result
= make_uninit_string (AEGetDescDataSize (desc
));
4465 AEGetDescData (desc
, SDATA (*result
), SBYTES (*result
));
4466 #else /* not TARGET_API_MAC_CARBON */
4467 *result
= make_uninit_string (GetHandleSize (desc
->dataHandle
));
4468 memcpy (SDATA (*result
), *(desc
->dataHandle
), SBYTES (*result
));
4469 #endif /* not TARGET_API_MAC_CARBON */
4470 AEDisposeDesc (desc
);
4473 AEDisposeDesc (&script_desc
);
4479 DEFUN ("do-applescript", Fdo_applescript
, Sdo_applescript
, 1, 1, 0,
4480 doc
: /* Compile and execute AppleScript SCRIPT and return the result.
4481 If compilation and execution are successful, the resulting script
4482 value is returned as a string. Otherwise the function aborts and
4483 displays the error message returned by the AppleScript scripting
4491 CHECK_STRING (script
);
4494 status
= do_applescript (script
, &result
);
4498 else if (!STRINGP (result
))
4499 error ("AppleScript error %d", status
);
4501 error ("%s", SDATA (result
));
4505 DEFUN ("mac-file-name-to-posix", Fmac_file_name_to_posix
,
4506 Smac_file_name_to_posix
, 1, 1, 0,
4507 doc
: /* Convert Macintosh FILENAME to Posix form. */)
4509 Lisp_Object filename
;
4511 char posix_filename
[MAXPATHLEN
+1];
4513 CHECK_STRING (filename
);
4515 if (mac_to_posix_pathname (SDATA (filename
), posix_filename
, MAXPATHLEN
))
4516 return build_string (posix_filename
);
4522 DEFUN ("posix-file-name-to-mac", Fposix_file_name_to_mac
,
4523 Sposix_file_name_to_mac
, 1, 1, 0,
4524 doc
: /* Convert Posix FILENAME to Mac form. */)
4526 Lisp_Object filename
;
4528 char mac_filename
[MAXPATHLEN
+1];
4530 CHECK_STRING (filename
);
4532 if (posix_to_mac_pathname (SDATA (filename
), mac_filename
, MAXPATHLEN
))
4533 return build_string (mac_filename
);
4539 DEFUN ("mac-coerce-ae-data", Fmac_coerce_ae_data
, Smac_coerce_ae_data
, 3, 3, 0,
4540 doc
: /* Coerce Apple event data SRC-DATA of type SRC-TYPE to DST-TYPE.
4541 Each type should be a string of length 4 or the symbol
4542 `undecoded-file-name'. */)
4543 (src_type
, src_data
, dst_type
)
4544 Lisp_Object src_type
, src_data
, dst_type
;
4547 Lisp_Object result
= Qnil
;
4548 DescType src_desc_type
, dst_desc_type
;
4551 CHECK_STRING (src_data
);
4552 if (EQ (src_type
, Qundecoded_file_name
))
4553 src_desc_type
= TYPE_FILE_NAME
;
4555 src_desc_type
= mac_get_code_from_arg (src_type
, 0);
4557 if (EQ (dst_type
, Qundecoded_file_name
))
4558 dst_desc_type
= TYPE_FILE_NAME
;
4560 dst_desc_type
= mac_get_code_from_arg (dst_type
, 0);
4563 err
= AECoercePtr (src_desc_type
, SDATA (src_data
), SBYTES (src_data
),
4564 dst_desc_type
, &dst_desc
);
4567 result
= Fcdr (mac_aedesc_to_lisp (&dst_desc
));
4568 AEDisposeDesc (&dst_desc
);
4576 #if TARGET_API_MAC_CARBON
4577 static Lisp_Object Qxml
, Qmime_charset
;
4578 static Lisp_Object QNFD
, QNFKD
, QNFC
, QNFKC
, QHFS_plus_D
, QHFS_plus_C
;
4580 DEFUN ("mac-get-preference", Fmac_get_preference
, Smac_get_preference
, 1, 4, 0,
4581 doc
: /* Return the application preference value for KEY.
4582 KEY is either a string specifying a preference key, or a list of key
4583 strings. If it is a list, the (i+1)-th element is used as a key for
4584 the CFDictionary value obtained by the i-th element. Return nil if
4585 lookup is failed at some stage.
4587 Optional arg APPLICATION is an application ID string. If omitted or
4588 nil, that stands for the current application.
4590 Optional arg FORMAT specifies the data format of the return value. If
4591 omitted or nil, each Core Foundation object is converted into a
4592 corresponding Lisp object as follows:
4594 Core Foundation Lisp Tag
4595 ------------------------------------------------------------
4596 CFString Multibyte string string
4597 CFNumber Integer or float number
4598 CFBoolean Symbol (t or nil) boolean
4599 CFDate List of three integers date
4600 (cf. `current-time')
4601 CFData Unibyte string data
4602 CFArray Vector array
4603 CFDictionary Alist or hash table dictionary
4604 (depending on HASH-BOUND)
4606 If it is t, a symbol that represents the type of the original Core
4607 Foundation object is prepended. If it is `xml', the value is returned
4608 as an XML representation.
4610 Optional arg HASH-BOUND specifies which kinds of the list objects,
4611 alists or hash tables, are used as the targets of the conversion from
4612 CFDictionary. If HASH-BOUND is a negative integer or nil, always
4613 generate alists. If HASH-BOUND >= 0, generate an alist if the number
4614 of keys in the dictionary is smaller than HASH-BOUND, and a hash table
4616 (key
, application
, format
, hash_bound
)
4617 Lisp_Object key
, application
, format
, hash_bound
;
4619 CFStringRef app_id
, key_str
;
4620 CFPropertyListRef app_plist
= NULL
, plist
;
4621 Lisp_Object result
= Qnil
, tmp
;
4624 key
= Fcons (key
, Qnil
);
4628 for (tmp
= key
; CONSP (tmp
); tmp
= XCDR (tmp
))
4629 CHECK_STRING_CAR (tmp
);
4631 wrong_type_argument (Qlistp
, key
);
4633 if (!NILP (application
))
4634 CHECK_STRING (application
);
4635 CHECK_SYMBOL (format
);
4636 if (!NILP (hash_bound
))
4637 CHECK_NUMBER (hash_bound
);
4641 app_id
= kCFPreferencesCurrentApplication
;
4642 if (!NILP (application
))
4644 app_id
= cfstring_create_with_string (application
);
4648 key_str
= cfstring_create_with_string (XCAR (key
));
4649 if (key_str
== NULL
)
4651 app_plist
= CFPreferencesCopyAppValue (key_str
, app_id
);
4652 CFRelease (key_str
);
4653 if (app_plist
== NULL
)
4657 for (key
= XCDR (key
); CONSP (key
); key
= XCDR (key
))
4659 if (CFGetTypeID (plist
) != CFDictionaryGetTypeID ())
4661 key_str
= cfstring_create_with_string (XCAR (key
));
4662 if (key_str
== NULL
)
4664 plist
= CFDictionaryGetValue (plist
, key_str
);
4665 CFRelease (key_str
);
4672 if (EQ (format
, Qxml
))
4674 CFDataRef data
= CFPropertyListCreateXMLData (NULL
, plist
);
4677 result
= cfdata_to_lisp (data
);
4682 cfproperty_list_to_lisp (plist
, EQ (format
, Qt
),
4683 NILP (hash_bound
) ? -1 : XINT (hash_bound
));
4688 CFRelease (app_plist
);
4697 static CFStringEncoding
4698 get_cfstring_encoding_from_lisp (obj
)
4701 CFStringRef iana_name
;
4702 CFStringEncoding encoding
= kCFStringEncodingInvalidId
;
4705 return kCFStringEncodingUnicode
;
4710 if (SYMBOLP (obj
) && !NILP (Fcoding_system_p (obj
)))
4712 Lisp_Object coding_spec
, plist
;
4714 coding_spec
= Fget (obj
, Qcoding_system
);
4715 plist
= XVECTOR (coding_spec
)->contents
[3];
4716 obj
= Fplist_get (XVECTOR (coding_spec
)->contents
[3], Qmime_charset
);
4720 obj
= SYMBOL_NAME (obj
);
4724 iana_name
= cfstring_create_with_string (obj
);
4727 encoding
= CFStringConvertIANACharSetNameToEncoding (iana_name
);
4728 CFRelease (iana_name
);
4735 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1020
4737 cfstring_create_normalized (str
, symbol
)
4742 TextEncodingVariant variant
;
4743 float initial_mag
= 0.0;
4744 CFStringRef result
= NULL
;
4746 if (EQ (symbol
, QNFD
))
4747 form
= kCFStringNormalizationFormD
;
4748 else if (EQ (symbol
, QNFKD
))
4749 form
= kCFStringNormalizationFormKD
;
4750 else if (EQ (symbol
, QNFC
))
4751 form
= kCFStringNormalizationFormC
;
4752 else if (EQ (symbol
, QNFKC
))
4753 form
= kCFStringNormalizationFormKC
;
4754 else if (EQ (symbol
, QHFS_plus_D
))
4756 variant
= kUnicodeHFSPlusDecompVariant
;
4759 else if (EQ (symbol
, QHFS_plus_C
))
4761 variant
= kUnicodeHFSPlusCompVariant
;
4767 CFMutableStringRef mut_str
= CFStringCreateMutableCopy (NULL
, 0, str
);
4771 CFStringNormalize (mut_str
, form
);
4775 else if (initial_mag
> 0.0)
4777 UnicodeToTextInfo uni
= NULL
;
4780 UniChar
*in_text
, *buffer
= NULL
, *out_buf
= NULL
;
4782 ByteCount out_read
, out_size
, out_len
;
4784 map
.unicodeEncoding
= CreateTextEncoding (kTextEncodingUnicodeDefault
,
4786 kTextEncodingDefaultFormat
);
4787 map
.otherEncoding
= CreateTextEncoding (kTextEncodingUnicodeDefault
,
4789 kTextEncodingDefaultFormat
);
4790 map
.mappingVersion
= kUnicodeUseLatestMapping
;
4792 length
= CFStringGetLength (str
);
4793 out_size
= (int)((float)length
* initial_mag
) * sizeof (UniChar
);
4797 in_text
= (UniChar
*)CFStringGetCharactersPtr (str
);
4798 if (in_text
== NULL
)
4800 buffer
= xmalloc (sizeof (UniChar
) * length
);
4801 CFStringGetCharacters (str
, CFRangeMake (0, length
), buffer
);
4806 err
= CreateUnicodeToTextInfo (&map
, &uni
);
4807 while (err
== noErr
)
4809 out_buf
= xmalloc (out_size
);
4810 err
= ConvertFromUnicodeToText (uni
, length
* sizeof (UniChar
),
4812 kUnicodeDefaultDirectionMask
,
4813 0, NULL
, NULL
, NULL
,
4814 out_size
, &out_read
, &out_len
,
4816 if (err
== noErr
&& out_read
< length
* sizeof (UniChar
))
4825 result
= CFStringCreateWithCharacters (NULL
, out_buf
,
4826 out_len
/ sizeof (UniChar
));
4828 DisposeUnicodeToTextInfo (&uni
);
4844 DEFUN ("mac-code-convert-string", Fmac_code_convert_string
, Smac_code_convert_string
, 3, 4, 0,
4845 doc
: /* Convert STRING from SOURCE encoding to TARGET encoding.
4846 The conversion is performed using the converter provided by the system.
4847 Each encoding is specified by either a coding system symbol, a mime
4848 charset string, or an integer as a CFStringEncoding value. Nil for
4849 encoding means UTF-16 in native byte order, no byte order mark.
4850 On Mac OS X 10.2 and later, you can do Unicode Normalization by
4851 specifying the optional argument NORMALIZATION-FORM with a symbol NFD,
4852 NFKD, NFC, NFKC, HFS+D, or HFS+C.
4853 On successful conversion, return the result string, else return nil. */)
4854 (string
, source
, target
, normalization_form
)
4855 Lisp_Object string
, source
, target
, normalization_form
;
4857 Lisp_Object result
= Qnil
;
4858 CFStringEncoding src_encoding
, tgt_encoding
;
4859 CFStringRef str
= NULL
;
4861 CHECK_STRING (string
);
4862 if (!INTEGERP (source
) && !STRINGP (source
))
4863 CHECK_SYMBOL (source
);
4864 if (!INTEGERP (target
) && !STRINGP (target
))
4865 CHECK_SYMBOL (target
);
4866 CHECK_SYMBOL (normalization_form
);
4870 src_encoding
= get_cfstring_encoding_from_lisp (source
);
4871 tgt_encoding
= get_cfstring_encoding_from_lisp (target
);
4873 /* We really want string_to_unibyte, but since it doesn't exist yet, we
4874 use string_as_unibyte which works as well, except for the fact that
4875 it's too permissive (it doesn't check that the multibyte string only
4876 contain single-byte chars). */
4877 string
= Fstring_as_unibyte (string
);
4878 if (src_encoding
!= kCFStringEncodingInvalidId
4879 && tgt_encoding
!= kCFStringEncodingInvalidId
)
4880 str
= CFStringCreateWithBytes (NULL
, SDATA (string
), SBYTES (string
),
4881 src_encoding
, !NILP (source
));
4882 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1020
4885 CFStringRef saved_str
= str
;
4887 str
= cfstring_create_normalized (saved_str
, normalization_form
);
4888 CFRelease (saved_str
);
4893 CFIndex str_len
, buf_len
;
4895 str_len
= CFStringGetLength (str
);
4896 if (CFStringGetBytes (str
, CFRangeMake (0, str_len
), tgt_encoding
, 0,
4897 !NILP (target
), NULL
, 0, &buf_len
) == str_len
)
4899 result
= make_uninit_string (buf_len
);
4900 CFStringGetBytes (str
, CFRangeMake (0, str_len
), tgt_encoding
, 0,
4901 !NILP (target
), SDATA (result
), buf_len
, NULL
);
4910 #endif /* TARGET_API_MAC_CARBON */
4914 mac_get_system_locale ()
4922 lang
= GetScriptVariable (smSystemScript
, smScriptLang
);
4923 region
= GetScriptManagerVariable (smRegionCode
);
4924 err
= LocaleRefFromLangOrRegionCode (lang
, region
, &locale
);
4926 err
= LocaleRefGetPartString (locale
, kLocaleAllPartsMask
,
4929 return build_string (str
);
4937 extern int inhibit_window_system
;
4938 extern int noninteractive
;
4940 /* Unlike in X11, window events in Carbon do not come from sockets.
4941 So we cannot simply use `select' to monitor two kinds of inputs:
4942 window events and process outputs. We emulate such functionality
4943 by regarding fd 0 as the window event channel and simultaneously
4944 monitoring both kinds of input channels. It is implemented by
4945 dividing into some cases:
4946 1. The window event channel is not involved.
4948 2. Sockets are not involved.
4949 -> Use ReceiveNextEvent.
4950 3. [If SELECT_USE_CFSOCKET is defined]
4951 Only the window event channel and socket read channels are
4952 involved, and timeout is not too short (greater than
4953 SELECT_TIMEOUT_THRESHHOLD_RUNLOOP seconds).
4954 -> Create CFSocket for each socket and add it into the current
4955 event RunLoop so that a `ready-to-read' event can be posted
4956 to the event queue that is also used for window events. Then
4957 ReceiveNextEvent can wait for both kinds of inputs.
4959 -> Periodically poll the window input channel while repeatedly
4960 executing `select' with a short timeout
4961 (SELECT_POLLING_PERIOD_USEC microseconds). */
4963 #define SELECT_POLLING_PERIOD_USEC 20000
4964 #ifdef SELECT_USE_CFSOCKET
4965 #define SELECT_TIMEOUT_THRESHOLD_RUNLOOP 0.2
4966 #define EVENT_CLASS_SOCK 'Sock'
4969 socket_callback (s
, type
, address
, data
, info
)
4971 CFSocketCallBackType type
;
4978 CreateEvent (NULL
, EVENT_CLASS_SOCK
, 0, 0, kEventAttributeNone
, &event
);
4979 PostEventToQueue (GetCurrentEventQueue (), event
, kEventPriorityStandard
);
4980 ReleaseEvent (event
);
4982 #endif /* SELECT_USE_CFSOCKET */
4985 select_and_poll_event (n
, rfds
, wfds
, efds
, timeout
)
4990 struct timeval
*timeout
;
4995 r
= select (n
, rfds
, wfds
, efds
, timeout
);
4999 err
= ReceiveNextEvent (0, NULL
, kEventDurationNoWait
,
5000 kEventLeaveInQueue
, NULL
);
5011 #if MAC_OS_X_VERSION_MAX_ALLOWED < 1020
5012 #undef SELECT_INVALIDATE_CFSOCKET
5016 sys_select (n
, rfds
, wfds
, efds
, timeout
)
5021 struct timeval
*timeout
;
5025 EMACS_TIME select_timeout
;
5027 if (inhibit_window_system
|| noninteractive
5028 || rfds
== NULL
|| !FD_ISSET (0, rfds
))
5029 return select (n
, rfds
, wfds
, efds
, timeout
);
5033 if (wfds
== NULL
&& efds
== NULL
)
5036 SELECT_TYPE orfds
= *rfds
;
5038 EventTimeout timeout_sec
=
5040 ? (EMACS_SECS (*timeout
) * kEventDurationSecond
5041 + EMACS_USECS (*timeout
) * kEventDurationMicrosecond
)
5042 : kEventDurationForever
);
5044 for (i
= 1; i
< n
; i
++)
5045 if (FD_ISSET (i
, rfds
))
5051 err
= ReceiveNextEvent (0, NULL
, timeout_sec
,
5052 kEventLeaveInQueue
, NULL
);
5064 mac_prepare_for_quickdraw (NULL
);
5066 /* Avoid initial overhead of RunLoop setup for the case that
5067 some input is already available. */
5068 EMACS_SET_SECS_USECS (select_timeout
, 0, 0);
5069 r
= select_and_poll_event (n
, rfds
, wfds
, efds
, &select_timeout
);
5070 if (r
!= 0 || timeout_sec
== 0.0)
5075 #ifdef SELECT_USE_CFSOCKET
5076 if (timeout_sec
> 0 && timeout_sec
<= SELECT_TIMEOUT_THRESHOLD_RUNLOOP
)
5077 goto poll_periodically
;
5080 CFRunLoopRef runloop
=
5081 (CFRunLoopRef
) GetCFRunLoopFromEventLoop (GetCurrentEventLoop ());
5082 EventTypeSpec specs
[] = {{EVENT_CLASS_SOCK
, 0}};
5083 #ifdef SELECT_INVALIDATE_CFSOCKET
5084 CFSocketRef
*shead
, *s
;
5086 CFRunLoopSourceRef
*shead
, *s
;
5091 #ifdef SELECT_INVALIDATE_CFSOCKET
5092 shead
= xmalloc (sizeof (CFSocketRef
) * nsocks
);
5094 shead
= xmalloc (sizeof (CFRunLoopSourceRef
) * nsocks
);
5097 for (i
= 1; i
< n
; i
++)
5098 if (FD_ISSET (i
, rfds
))
5100 CFSocketRef socket
=
5101 CFSocketCreateWithNative (NULL
, i
, kCFSocketReadCallBack
,
5102 socket_callback
, NULL
);
5103 CFRunLoopSourceRef source
=
5104 CFSocketCreateRunLoopSource (NULL
, socket
, 0);
5106 #ifdef SELECT_INVALIDATE_CFSOCKET
5107 CFSocketSetSocketFlags (socket
, 0);
5109 CFRunLoopAddSource (runloop
, source
, kCFRunLoopDefaultMode
);
5110 #ifdef SELECT_INVALIDATE_CFSOCKET
5120 err
= ReceiveNextEvent (0, NULL
, timeout_sec
, kEventLeaveInQueue
, NULL
);
5125 #ifdef SELECT_INVALIDATE_CFSOCKET
5126 CFSocketInvalidate (*s
);
5128 CFRunLoopRemoveSource (runloop
, *s
, kCFRunLoopDefaultMode
);
5143 FlushEventsMatchingListFromQueue (GetCurrentEventQueue (),
5144 GetEventTypeCount (specs
),
5146 EMACS_SET_SECS_USECS (select_timeout
, 0, 0);
5147 r
= select_and_poll_event (n
, rfds
, wfds
, efds
, &select_timeout
);
5154 #endif /* SELECT_USE_CFSOCKET */
5159 EMACS_TIME end_time
, now
, remaining_time
;
5160 SELECT_TYPE orfds
= *rfds
, owfds
, oefds
;
5168 remaining_time
= *timeout
;
5169 EMACS_GET_TIME (now
);
5170 EMACS_ADD_TIME (end_time
, now
, remaining_time
);
5175 EMACS_SET_SECS_USECS (select_timeout
, 0, SELECT_POLLING_PERIOD_USEC
);
5176 if (timeout
&& EMACS_TIME_LT (remaining_time
, select_timeout
))
5177 select_timeout
= remaining_time
;
5178 r
= select_and_poll_event (n
, rfds
, wfds
, efds
, &select_timeout
);
5190 EMACS_GET_TIME (now
);
5191 EMACS_SUB_TIME (remaining_time
, end_time
, now
);
5194 while (!timeout
|| EMACS_TIME_LT (now
, end_time
));
5205 /* Set up environment variables so that Emacs can correctly find its
5206 support files when packaged as an application bundle. Directories
5207 placed in /usr/local/share/emacs/<emacs-version>/, /usr/local/bin,
5208 and /usr/local/libexec/emacs/<emacs-version>/<system-configuration>
5209 by `make install' by default can instead be placed in
5210 .../Emacs.app/Contents/Resources/ and
5211 .../Emacs.app/Contents/MacOS/. Each of these environment variables
5212 is changed only if it is not already set. Presumably if the user
5213 sets an environment variable, he will want to use files in his path
5214 instead of ones in the application bundle. */
5216 init_mac_osx_environment ()
5220 CFStringRef cf_app_bundle_pathname
;
5221 int app_bundle_pathname_len
;
5222 char *app_bundle_pathname
;
5226 /* Initialize locale related variables. */
5227 mac_system_script_code
=
5228 (ScriptCode
) GetScriptManagerVariable (smSysScript
);
5229 Vmac_system_locale
= mac_get_system_locale ();
5231 /* Fetch the pathname of the application bundle as a C string into
5232 app_bundle_pathname. */
5234 bundle
= CFBundleGetMainBundle ();
5235 if (!bundle
|| CFBundleGetIdentifier (bundle
) == NULL
)
5237 /* We could not find the bundle identifier. For now, prevent
5238 the fatal error by bringing it up in the terminal. */
5239 inhibit_window_system
= 1;
5243 bundleURL
= CFBundleCopyBundleURL (bundle
);
5247 cf_app_bundle_pathname
= CFURLCopyFileSystemPath (bundleURL
,
5248 kCFURLPOSIXPathStyle
);
5249 app_bundle_pathname_len
= CFStringGetLength (cf_app_bundle_pathname
);
5250 app_bundle_pathname
= (char *) alloca (app_bundle_pathname_len
+ 1);
5252 if (!CFStringGetCString (cf_app_bundle_pathname
,
5253 app_bundle_pathname
,
5254 app_bundle_pathname_len
+ 1,
5255 kCFStringEncodingISOLatin1
))
5257 CFRelease (cf_app_bundle_pathname
);
5261 CFRelease (cf_app_bundle_pathname
);
5263 /* P should have sufficient room for the pathname of the bundle plus
5264 the subpath in it leading to the respective directories. Q
5265 should have three times that much room because EMACSLOADPATH can
5266 have the value "<path to lisp dir>:<path to leim dir>:<path to
5268 p
= (char *) alloca (app_bundle_pathname_len
+ 50);
5269 q
= (char *) alloca (3 * app_bundle_pathname_len
+ 150);
5270 if (!getenv ("EMACSLOADPATH"))
5274 strcpy (p
, app_bundle_pathname
);
5275 strcat (p
, "/Contents/Resources/lisp");
5276 if (stat (p
, &st
) == 0 && (st
.st_mode
& S_IFMT
) == S_IFDIR
)
5279 strcpy (p
, app_bundle_pathname
);
5280 strcat (p
, "/Contents/Resources/leim");
5281 if (stat (p
, &st
) == 0 && (st
.st_mode
& S_IFMT
) == S_IFDIR
)
5288 strcpy (p
, app_bundle_pathname
);
5289 strcat (p
, "/Contents/Resources/site-lisp");
5290 if (stat (p
, &st
) == 0 && (st
.st_mode
& S_IFMT
) == S_IFDIR
)
5298 setenv ("EMACSLOADPATH", q
, 1);
5301 if (!getenv ("EMACSPATH"))
5305 strcpy (p
, app_bundle_pathname
);
5306 strcat (p
, "/Contents/MacOS/libexec");
5307 if (stat (p
, &st
) == 0 && (st
.st_mode
& S_IFMT
) == S_IFDIR
)
5310 strcpy (p
, app_bundle_pathname
);
5311 strcat (p
, "/Contents/MacOS/bin");
5312 if (stat (p
, &st
) == 0 && (st
.st_mode
& S_IFMT
) == S_IFDIR
)
5320 setenv ("EMACSPATH", q
, 1);
5323 if (!getenv ("EMACSDATA"))
5325 strcpy (p
, app_bundle_pathname
);
5326 strcat (p
, "/Contents/Resources/etc");
5327 if (stat (p
, &st
) == 0 && (st
.st_mode
& S_IFMT
) == S_IFDIR
)
5328 setenv ("EMACSDATA", p
, 1);
5331 if (!getenv ("EMACSDOC"))
5333 strcpy (p
, app_bundle_pathname
);
5334 strcat (p
, "/Contents/Resources/etc");
5335 if (stat (p
, &st
) == 0 && (st
.st_mode
& S_IFMT
) == S_IFDIR
)
5336 setenv ("EMACSDOC", p
, 1);
5339 if (!getenv ("INFOPATH"))
5341 strcpy (p
, app_bundle_pathname
);
5342 strcat (p
, "/Contents/Resources/info");
5343 if (stat (p
, &st
) == 0 && (st
.st_mode
& S_IFMT
) == S_IFDIR
)
5344 setenv ("INFOPATH", p
, 1);
5347 #endif /* MAC_OSX */
5353 Qundecoded_file_name
= intern ("undecoded-file-name");
5354 staticpro (&Qundecoded_file_name
);
5356 #if TARGET_API_MAC_CARBON
5357 Qstring
= intern ("string"); staticpro (&Qstring
);
5358 Qnumber
= intern ("number"); staticpro (&Qnumber
);
5359 Qboolean
= intern ("boolean"); staticpro (&Qboolean
);
5360 Qdate
= intern ("date"); staticpro (&Qdate
);
5361 Qdata
= intern ("data"); staticpro (&Qdata
);
5362 Qarray
= intern ("array"); staticpro (&Qarray
);
5363 Qdictionary
= intern ("dictionary"); staticpro (&Qdictionary
);
5365 Qxml
= intern ("xml");
5368 Qmime_charset
= intern ("mime-charset");
5369 staticpro (&Qmime_charset
);
5371 QNFD
= intern ("NFD"); staticpro (&QNFD
);
5372 QNFKD
= intern ("NFKD"); staticpro (&QNFKD
);
5373 QNFC
= intern ("NFC"); staticpro (&QNFC
);
5374 QNFKC
= intern ("NFKC"); staticpro (&QNFKC
);
5375 QHFS_plus_D
= intern ("HFS+D"); staticpro (&QHFS_plus_D
);
5376 QHFS_plus_C
= intern ("HFS+C"); staticpro (&QHFS_plus_C
);
5382 for (i
= 0; i
< sizeof (ae_attr_table
) / sizeof (ae_attr_table
[0]); i
++)
5384 ae_attr_table
[i
].symbol
= intern (ae_attr_table
[i
].name
);
5385 staticpro (&ae_attr_table
[i
].symbol
);
5389 defsubr (&Smac_coerce_ae_data
);
5390 #if TARGET_API_MAC_CARBON
5391 defsubr (&Smac_get_preference
);
5392 defsubr (&Smac_code_convert_string
);
5395 defsubr (&Smac_set_file_creator
);
5396 defsubr (&Smac_set_file_type
);
5397 defsubr (&Smac_get_file_creator
);
5398 defsubr (&Smac_get_file_type
);
5399 defsubr (&Sdo_applescript
);
5400 defsubr (&Smac_file_name_to_posix
);
5401 defsubr (&Sposix_file_name_to_mac
);
5403 DEFVAR_INT ("mac-system-script-code", &mac_system_script_code
,
5404 doc
: /* The system script code. */);
5405 mac_system_script_code
= (ScriptCode
) GetScriptManagerVariable (smSysScript
);
5407 DEFVAR_LISP ("mac-system-locale", &Vmac_system_locale
,
5408 doc
: /* The system locale identifier string.
5409 This is not a POSIX locale ID, but an ICU locale ID. So encoding
5410 information is not included. */);
5411 Vmac_system_locale
= mac_get_system_locale ();
5414 /* arch-tag: 29d30c1f-0c6b-4f88-8a6d-0558d7f9dbff
5415 (do not change this comment) */