]> gitweb.factorcode.org Git - factor.git/blob - basis/cocoa/plists/plists.factor
Updating code to use with-out-parameters
[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
40     { void* }
41     [ -> propertyListFromData:mutabilityOption:format:errorDescription: ] [ ]
42     with-out-parameters
43     [ -> release "read-plist failed" throw ] when* ;
44
45 MACRO: objc-class-case ( alist -- quot )
46     [
47         dup callable?
48         [ first2 [ '[ dup _ execute -> isKindOfClass: c-bool> ] ] dip 2array ]
49         unless
50     ] map '[ _ cond ] ;
51
52 PRIVATE>
53
54 ERROR: invalid-plist-object object ;
55
56 : plist> ( plist -- value )
57     {
58         { NSString [ (plist-NSString>) ] }
59         { NSNumber [ (plist-NSNumber>) ] }
60         { NSData [ (plist-NSData>) ] }
61         { NSArray [ (plist-NSArray>) ] }
62         { NSDictionary [ (plist-NSDictionary>) ] }
63         { NSObject [ ] }
64         [ invalid-plist-object ]
65     } objc-class-case ;
66
67 : read-plist ( path -- assoc )
68     normalize-path <NSString>
69     NSData swap -> dataWithContentsOfFile:
70     [ (read-plist) plist> ] [ "read-plist failed" throw ] if* ;