]> gitweb.factorcode.org Git - factor.git/blob - basis/cocoa/plists/plists.factor
86b13b2ddc2e83341c83480bad3b81b16e20ea17
[factor.git] / basis / cocoa / plists / plists.factor
1 ! Copyright (C) 2007, 2009 Slava Pestov.
2 ! Copyright (C) 2008 Joe Groff.
3 ! See http://factorcode.org/license.txt for BSD license.
4 USING: strings arrays hashtables assocs sequences fry macros
5 cocoa.messages cocoa.classes cocoa.application cocoa kernel
6 namespaces io.backend math cocoa.enumeration byte-arrays
7 combinators alien.c-types alien.data words core-foundation
8 quotations core-foundation.data core-foundation.utilities ;
9 IN: cocoa.plists
10
11 : >plist ( value -- plist ) >cf -> autorelease ;
12
13 : write-plist ( assoc path -- )
14     [ >plist ] [ normalize-path <NSString> ] bi* 0 -> writeToFile:atomically:
15     [ "write-plist failed" throw ] unless ;
16
17 DEFER: plist>
18
19 <PRIVATE
20
21 : (plist-NSString>) ( NSString -- string )
22     -> UTF8String ;
23
24 : (plist-NSNumber>) ( NSNumber -- number )
25     dup -> doubleValue dup >integer =
26     [ -> longLongValue ] [ -> doubleValue ] if ;
27
28 : (plist-NSData>) ( NSData -- byte-array )
29     dup -> length <byte-array> [ -> getBytes: ] keep ;
30
31 : (plist-NSArray>) ( NSArray -- vector )
32     [ plist> ] NSFastEnumeration-map ;
33
34 : (plist-NSDictionary>) ( NSDictionary -- hashtable )
35     dup [ [ nip ] [ -> valueForKey: ] 2bi [ plist> ] bi@ 2array ] with
36     NSFastEnumeration-map >hashtable ;
37
38 : (read-plist) ( NSData -- id )
39     NSPropertyListSerialization swap kCFPropertyListImmutable f f <void*>
40     [ -> propertyListFromData:mutabilityOption:format:errorDescription: ] keep
41     *void* [ -> release "read-plist failed" throw ] when* ;
42
43 MACRO: objc-class-case ( alist -- quot )
44     [
45         dup callable?
46         [ first2 [ '[ dup _ execute -> isKindOfClass: c-bool> ] ] dip 2array ]
47         unless
48     ] map '[ _ cond ] ;
49
50 PRIVATE>
51
52 ERROR: invalid-plist-object object ;
53
54 : plist> ( plist -- value )
55     {
56         { NSString [ (plist-NSString>) ] }
57         { NSNumber [ (plist-NSNumber>) ] }
58         { NSData [ (plist-NSData>) ] }
59         { NSArray [ (plist-NSArray>) ] }
60         { NSDictionary [ (plist-NSDictionary>) ] }
61         { NSObject [ ] }
62         [ invalid-plist-object ]
63     } objc-class-case ;
64
65 : read-plist ( path -- assoc )
66     normalize-path <NSString>
67     NSData swap -> dataWithContentsOfFile:
68     [ (read-plist) plist> ] [ "read-plist failed" throw ] if* ;