]> gitweb.factorcode.org Git - factor.git/blob - basis/cocoa/plists/plists.factor
basis: ERROR: changes.
[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: alien.c-types alien.data arrays byte-arrays cocoa
5 cocoa.application cocoa.classes cocoa.enumeration combinators
6 core-foundation.data core-foundation.strings
7 core-foundation.utilities fry io.backend kernel macros math
8 quotations sequences ;
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-NSNumber>) ( NSNumber -- number )
22     dup -> doubleValue dup >integer =
23     [ -> longLongValue ] [ -> doubleValue ] if ;
24
25 : (plist-NSData>) ( NSData -- byte-array )
26     dup -> length <byte-array> [ -> getBytes: ] keep ;
27
28 : (plist-NSArray>) ( NSArray -- vector )
29     [ plist> ] NSFastEnumeration-map ;
30
31 : (plist-NSDictionary>) ( NSDictionary -- hashtable )
32     dup [ [ nip ] [ -> valueForKey: ] 2bi [ plist> ] bi@ ] with
33     NSFastEnumeration>hashtable ;
34
35 : (read-plist) ( NSData -- id )
36     NSPropertyListSerialization swap kCFPropertyListImmutable f
37     { void* }
38     [ -> propertyListFromData:mutabilityOption:format:errorDescription: ]
39     with-out-parameters
40     [ -> release "read-plist failed" throw ] when* ;
41
42 MACRO: objc-class-case ( alist -- quot )
43     [
44         dup callable?
45         [ first2 [ '[ dup _ execute -> isKindOfClass: c-bool> ] ] dip 2array ]
46         unless
47     ] map '[ _ cond ] ;
48
49 PRIVATE>
50
51 ERROR: invalid-plist-object object ;
52
53 : plist> ( plist -- value )
54     {
55         { NSString [ CF>string ] }
56         { NSNumber [ (plist-NSNumber>) ] }
57         { NSData [ (plist-NSData>) ] }
58         { NSArray [ (plist-NSArray>) ] }
59         { NSDictionary [ (plist-NSDictionary>) ] }
60         { NSObject [ ] }
61         [ throw-invalid-plist-object ]
62     } objc-class-case ;
63
64 : read-plist ( path -- assoc )
65     normalize-path <NSString>
66     NSData swap -> dataWithContentsOfFile:
67     [ (read-plist) plist> ] [ "read-plist failed" throw ] if* ;