File: WrapperDocument.m

package info (click to toggle)
wrapperfactory.app 0.1.0-6
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 580 kB
  • sloc: objc: 3,094; sh: 176; makefile: 33
file content (1192 lines) | stat: -rw-r--r-- 38,488 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
 /* Copyright (C) 2004 Raffael Herzog
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.

 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * $Id: WrapperDocument.m 103 2004-08-09 16:30:51Z rherzog $
 * $HeadURL: file:///home/rherzog/Subversion/GNUstep/GSWrapper/tags/release-0.1.0/WrapperFactory/WrapperDocument.m $
 */

#include <sys/types.h>
#include <sys/stat.h>

#include <AppKit/AppKit.h>

#include "WrapperDocument.h"
#include "IconView.h"


static const int currentVersion = 1;

NSString * const ApplicationType = @"Application";
NSString * const WrapperChangedNotification = @"WrapperChangedNotification";
NSString * const WrapperChangedAttributeName = @"AttributeName";
NSString * const WrapperChangedAttributeValue = @"AttributeValue";

NSString * const WrapperAggregateChangedNotification = @"WrapperAggregateChangedNotification";
NSString * const WrapperAggregateChangedObject = @"Object";
NSString * const WrapperAggregateChangedAttributeName = @"AttributeName";
NSString * const WrapperAggregateChangedAttributeValue = @"AttributeValue";

static NSString *emptyString = @"";
static NSString *launcherName = @"GSWrapper_Launcher";
#ifdef FREEDESKTOP
static NSString *FreedesktopApplicationType = @"Freedesktop Application";
#endif

static NSString *actionRunScript = @"RunScript";
static NSString *actionFail = @"Fail";
static NSString *actionIgnore = @"Ignore";



/*
 * AppFileWrapper
 */

@interface AppFileWrapper : NSFileWrapper
{
    BOOL flattened;
    NSData *script;
    NSData *executable;
    NSString *executablePath;
}

- (void)setFlattened: (BOOL)f;
- (BOOL)flattened;

- (void)setScript: (NSData *)s;
- (NSData *)script;

- (void)setExecutable: (NSData *)exe;
 - (NSData *)executable;

- (void)setExecutablePath: (NSString *)exep;
- (NSString *)executablePath;

- (BOOL)writeToFile: (NSString *)path
         atomically:(BOOL)atomicFlag
    updateFilenames:(BOOL)updateNamesFlag;

@end

/* Obtain a variable's value with gnustep-config.  Assumes that
 * gnustep-config is in PATH which should be the case for all
 * installations.  */
static NSString *
getVar(NSString *var)
{
    NSPipe *pipe = [NSPipe pipe];
    NSFileHandle *handle = [pipe fileHandleForReading];
    NSTask *task = [NSTask new];
    NSString *output, *value;

    [task setLaunchPath: @"gnustep-config"];
    [task setArguments: [NSArray arrayWithObjects:
                                 [NSString stringWithFormat: @"--variable=%@",
                                          var], nil]];
    [task setStandardOutput: pipe];
    [task launch];
    output = [[NSString alloc] initWithData: [handle readDataToEndOfFile]
                                   encoding: NSUTF8StringEncoding];
    value = [output stringByTrimmingCharactersInSet:
                      [NSCharacterSet newlineCharacterSet]];
    [handle closeFile];

    if ( [value isEqualToString: @""] || [task terminationStatus] != 0 )
        [NSException raise: NSParseErrorException
                    format: @"Could not obtain the %@ variable", var];

    RELEASE(task);
    RELEASE(output);

    return value;
}

@implementation AppFileWrapper

- (void)dealloc
{
    TEST_RELEASE(script);
    TEST_RELEASE(executable);
    TEST_RELEASE(executablePath);
    [super dealloc];
}

- (void)setFlattened: (BOOL)f
{
    flattened = f;
}

- (BOOL)flattened
{
    return flattened;
}

- (void)setScript: (NSData *)s
{
    ASSIGN(script, s);
}

- (NSData *)script
{
    return script;
}

- (void)setExecutable: (NSData *)exe
{
    ASSIGN(executable, exe);
}

- (NSData *)executable
{
    return executable;
}

- (void)setExecutablePath: (NSString *)exep
{
    ASSIGN(executablePath, exep);
}

- (NSString *)executablePath
{
    return executablePath;
}

- (BOOL)writeToFile: (NSString *)path
         atomically: (BOOL)atomicFlag
    updateFilenames: (BOOL)updateNamesFlag
{
    BOOL result = [super writeToFile: path
                         atomically: (atomicFlag)
                         updateFilenames: (updateNamesFlag)];
    if ( result ) {
        NSString *basename = [[path lastPathComponent] stringByDeletingPathExtension];
        NSString *p = [path stringByAppendingPathComponent: basename];
        if ( flattened ) {
            [executable writeToFile: p atomically: NO];
        }
        else {
            [script writeToFile: p atomically: NO];
        }
        NSFileManager *fm = [NSFileManager defaultManager];
        NSDictionary *attrs = [fm fileAttributesAtPath: p traverseLink: NO];
        NSNumber *perms = [attrs objectForKey: NSFilePosixPermissions];
        perms = [NSNumber numberWithInt: [perms intValue]|0111];
        attrs = [NSDictionary dictionaryWithObject: perms forKey: NSFilePosixPermissions];
        [fm changeFileAttributes: attrs atPath: p];
        if ( !flattened ) {
            NSString *exe = [path stringByAppendingPathComponent: [executablePath stringByAppendingPathComponent: basename]];
            [executable writeToFile: exe atomically: YES];
            [fm changeFileAttributes: attrs atPath: exe];
        }
    }
    return result;
}

@end



/*
 * WrapperDocument
 */

@interface WrapperDocument (Private)

- (void)attributeChangedName: (NSString *)n
                       value: (id)v;

- (void)documentChanged;

- (void)aggregateChanged: (NSNotification *)not;

- (NSArray *)arrayFromCommaSeparatedString: (NSString *)string;

- (BOOL)loadWrapper: (NSFileWrapper *)file;
- (NSFileWrapper *)saveWrapper;

- (BOOL)loadFreedesktopApplication: (NSFileWrapper *)file;
- (NSFileWrapper *)saveFreedesktopApplication;

+ (ScriptAction)stringToScriptAction: (NSString *)str;
+ (NSString *)scriptActionToString: (ScriptAction)action;

@end


@implementation WrapperDocument

/*
 * document
 */

- (id)init
{
    self = [super init];
    if ( self ) {
        NSImage *img = [[NSImage alloc] initByReferencingFile: [[NSBundle mainBundle] pathForImageResource: @"DefaultAppIcon"]];
        appIcon = RETAIN([Icon iconWithImage: img]);
        name = _(@"Untitled.app");
        version = @"1.0";
        fullVersion = @"1.0/1.0";
        description = _(@"A wrapped application");
        url = emptyString;
        authors = emptyString;
        role = NoneRole;

        startScript = emptyString;
        startScriptShell = @"/bin/sh";
        startScriptAction = RunScriptAction;
        startOpenScript = emptyString;
        startOpenScriptShell = startScriptShell;
        startOpenScriptAction = RunScriptAction;
        openScript = emptyString;
        openScriptShell = startScriptShell;
        openScriptAction = IgnoreAction;

        types = [[NSMutableArray alloc] init];
    }
    return self;
}

- (void)dealloc
{
    RELEASE(types);
    [super dealloc];
}

- (BOOL)loadFileWrapperRepresentation: (NSFileWrapper *)file
                               ofType: (NSString *)type
{
    NSLog(@"Loading wrapper: %@", [file filename]);
    if ( [type isEqualToString: ApplicationType]  ) {
        return [self loadWrapper: file];
    }
#ifdef FREEDESKTOP
    else if ( [type isEqualToString: FreedesktopApplicationType] ) {
        if ( [self loadFreedesktopApplication: file] ) {
            [self setFileType: ApplicationType];
            [self setFileName: nil];
            return YES;
        }
        else {
            return NO;
        }
    }
#endif
    else {
        NSLog(@"Type %@ of %@ is not known", type, [file filename]);
        return NO;
    }
}

- (NSFileWrapper *)fileWrapperRepresentationOfType: (NSString *)type
{
    if ( [type isEqualToString: ApplicationType]  ) {
        return [self saveWrapper];
    }
    else {
        NSLog(@"Type %@ is not known", type);
        return nil;
    }
}

- (NSString *)windowNibName
{
    return @"WrapperDocument";
}


- (int)runModalSavePanel: (NSSavePanel *)savePanel
       withAccessoryView: (NSView *)accessoryView
{
    NSString *directory;
    NSString *file;

    if ([self fileName]) {
        directory = [savePanel directory];
        file = [[[self fileName] lastPathComponent] stringByDeletingPathExtension];
    }
    else {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationDirectory, NSUserDomainMask, YES);
        if ( [paths count] > 0 ) {
            directory = [paths objectAtIndex: 0];
        }
        else {
            directory = [[NSDocumentController sharedDocumentController] currentDirectory];
        }
        file = [self name];
        if ( [[file pathExtension] isEqualToString: [savePanel requiredFileType]] ) {
            file = [file stringByDeletingPathExtension];
        }
    }

    [savePanel setAccessoryView: accessoryView];
    return [savePanel runModalForDirectory: directory file: file];
}


/*
 * attributes
 */

- (Icon *)appIcon
{
    return appIcon;
}
- (void)setAppIcon: (Icon *)i
{
    ASSIGN(appIcon, i);
    [self attributeChangedName: @"appIcon" value: i];
}

- (NSString *)name
{
    return name;
}
- (void)setName: (NSString *)n
{
    ASSIGN(name, n);
    [self attributeChangedName: @"name" value: n];
}

- (NSString *)version
{
    return version;
}
- (void)setVersion: (NSString *)v
{
    ASSIGN(version, v);
    [self attributeChangedName: @"version" value: v];
}

- (NSString *)fullVersion
{
    return fullVersion;
}
- (void)setFullVersion: (NSString *)v
{
    ASSIGN(fullVersion, v);
    [self attributeChangedName: @"fullVersion" value: v];
}

- (NSString *)description
{
    return description;
}
- (void)setDescription: (NSString *)d
{
    ASSIGN(description, d);
    [self attributeChangedName: @"description" value: d];
}

- (NSString *)url
{
    return url;
}
- (void)setUrl: (NSString *)u
{
    ASSIGN(url, u);
    [self attributeChangedName: @"url" value: u];
}

- (NSString *)authors
{
    return authors;
}
- (void)setAuthors: (NSString *)a
{
    ASSIGN(authors, a);
    [self attributeChangedName: @"authors" value: a];
}

- (ApplicationRole)role
{
    return role;
}
- (void)setRole: (ApplicationRole)r
{
    role = r;
    [self attributeChangedName: @"role"
          value: [NSNumber numberWithInt: r]];
}

- (NSString *)startScript
{
    return startScript;
}
- (void)setStartScript: (NSString *)s
{
    ASSIGN(startScript, s);
    [self attributeChangedName: @"startScript" value: s];
}

- (NSString *)startScriptShell
{
    return startScriptShell;
}
- (void)setStartScriptShell: (NSString *)s
{
    ASSIGN(startScriptShell, s);
    [self attributeChangedName: @"startScriptShell" value: s];
}

- (ScriptAction)startScriptAction
{
    return startScriptAction;
}
- (void)setStartScriptAction: (ScriptAction)action
{
    startScriptAction = action;
    [self attributeChangedName: @"startScriptAction" value: [NSNumber numberWithInt: action]];
}

- (NSString *)startOpenScript
{
    return startOpenScript;
}
- (void)setStartOpenScript: (NSString *)s
{
    ASSIGN(startOpenScript, s);
    [self attributeChangedName: @"startOpenScript" value: s];
}

- (NSString *)startOpenScriptShell
{
    return startOpenScriptShell;
}
- (void)setStartOpenScriptShell: (NSString *)s
{
    ASSIGN(startOpenScriptShell, s);
    [self attributeChangedName: @"startOpenScriptShell" value: s];
}

- (ScriptAction)startOpenScriptAction
{
    return startOpenScriptAction;
}
- (void)setStartOpenScriptAction: (ScriptAction)action
{
    startOpenScriptAction = action;
    [self attributeChangedName: @"startOpenScriptAction" value: [NSNumber numberWithInt: action]];
}

- (NSString *)openScript
{
    return openScript;
}
- (void)setOpenScript: (NSString *)s
{
    ASSIGN(openScript, s);
    [self attributeChangedName: @"openScript" value: s];
}

- (NSString *)openScriptShell
{
    return openScriptShell;
}
- (void)setOpenScriptShell: (NSString *)s
{
    ASSIGN(openScriptShell, s);
    [self attributeChangedName: @"openScriptShell" value: s];
}

- (ScriptAction)openScriptAction
{
    return openScriptAction;
}
- (void)setOpenScriptAction: (ScriptAction)action
{
    openScriptAction = action;
    [self attributeChangedName: @"openScriptAction" value: [NSNumber numberWithInt: action]];
}


/*
 * types
 */

- (void)addType: (Type *)type
{
    if ( ! [types containsObject: type] ) {
        [types addObject: type];
        [[NSNotificationCenter defaultCenter] addObserver: self
                                              selector: @selector(aggregateChanged:)
                                              name: (WrapperAggregateChangedNotification)
                                              object: (type)];
        [self documentChanged];
    }
    else {
        NSLog(@"Type %@ already in document, not added", type);
    }
}

- (void)removeType: (Type *)type
{
    if ( [types containsObject: type] ) {
        [types removeObject: type];
        [[NSNotificationCenter defaultCenter] removeObserver: self
                                              name: (WrapperAggregateChangedNotification)
                                              object: (type)];
        [self documentChanged];
    }
    else {
        NSLog(@"Type %@ not in document, not removed", type);
    }
}

- (int)typeCount
{
    return [types count];
}

- (Type *)typeAtIndex: (unsigned)index
{
    return [types objectAtIndex: index];
}

- (unsigned)indexOfType: (Type *)type
{
    return [types indexOfObject: type];
}


@end



/*
 * category Private
 */

@implementation WrapperDocument (Private)


- (void)attributeChangedName: (NSString *)n
                       value: (id)v;
{
    NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
                                           n, WrapperChangedAttributeName,
                                           v, WrapperChangedAttributeValue,
                                           nil];
    [[NSNotificationCenter defaultCenter] postNotificationName: WrapperChangedNotification
                                          object: (self)
                                          userInfo: (userInfo)];
    [self documentChanged];
}

- (void)documentChanged
{
    if ( ! [self isDocumentEdited] ) {
        [self updateChangeCount: NSChangeDone];
    }
}

- (void)aggregateChanged: (NSNotification *)not
{
    //NSLog(@"Aggregate changed: %@", not);
    [self documentChanged];
}

- (NSArray *)arrayFromCommaSeparatedString: (NSString *)string
{
    NSArray *array = [string componentsSeparatedByString: @","];
    int count = [array count];
    if ( count <= 0 ) {
        return nil;
    }
    NSMutableArray *result = [NSMutableArray arrayWithCapacity: [array count]];
    NSString *element;
    int i;
    for ( i=0; i<count; i++ ) {
        element = [array objectAtIndex: i];
        // the use of stringByTrimmingCharactersInSet: is discouraged by apple and probably buggy in GNUstep, too
        // element = [element stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
#ifdef GNUSTEP
        element = [element stringByTrimmingSpaces];
#else
#error -stringByTrimmingSpaces: is only supported under GNUstep
#endif
        if ( [element length] > 0 ) {
            [result addObject: element];
        }
    }
    if ( [result count] > 0 ) {
        return result;
    }
    else {
        return nil;
    }
}

- (BOOL)loadWrapper: (NSFileWrapper *)file
{
    if ( [file isRegularFile] ) {
        NSLog(@"%@ is a regular file -> not an application wrapper", [file filename]);
        return NO;
    }
    NS_DURING {
        NSString *value;
        NSDictionary *dict;

        NSFileWrapper *resourcesFile = [[file fileWrappers] objectForKey: @"Resources"];
        if ( !resourcesFile ) {
            NSLog(@"Resources directory not found");
            return NO;
        }
        NSDictionary *resources = [resourcesFile fileWrappers];
        NSFileWrapper *infoFile = [resources objectForKey: @"Info-gnustep.plist"];
        if ( !infoFile ) {
            NSLog(@"Resources/Info-gnustep.plist not found");
            return NO;
        }


        // Load GSWrapper.plist
        NSFileWrapper *gsWrapperInfoFile = [resources objectForKey: @"GSWrapper.plist"];
        if ( !gsWrapperInfoFile ) {
            NSLog(@"Resources/GSWrapper.plist not found");
            return NO;
        }
        NSDictionary *gsWrapperInfo = [NSDictionary dictionaryWithContentsOfFile: [gsWrapperInfoFile filename]];
        NSNumber *v = [gsWrapperInfo objectForKey: @"Version"];
        if ( [v intValue] > currentVersion ) {
            NSLog(@"Version %d too new, don't know how to load this", [v intValue]);
            return NO;
        }
        dict = [gsWrapperInfo objectForKey: @"Start"];
        if ( dict ) {
            value = [dict objectForKey: @"Shell"];
            if ( value ) {
                [self setStartScriptShell: value];
            }
            else {
                NSLog(@"No shell for Start script set");
            }
            value = [dict objectForKey: @"Action"];
            if ( value ) {
                [self setStartScriptAction: [WrapperDocument stringToScriptAction: value]];
            }
            else {
                NSLog(@"No action for Start script set");
                [self setStartScriptAction: RunScriptAction];
            }
        }
        else {
            NSLog(@"No info for Start script");
        }
        dict = [gsWrapperInfo objectForKey: @"StartOpen"];
        if ( dict ) {
            value = [dict objectForKey: @"Shell"];
            if ( value ) {
                [self setStartOpenScriptShell: value];
            }
            else {
                NSLog(@"No shell for StartOpen script set");
            }
            value = [dict objectForKey: @"Action"];
            if ( value ) {
                [self setStartOpenScriptAction: [WrapperDocument stringToScriptAction: value]];
            }
            else {
                NSLog(@"No action for StartOpen script set");
                [self setStartOpenScriptAction: RunScriptAction];
            }
        }
        else {
            NSLog(@"No info for StartOpen script");
        }
        dict = [gsWrapperInfo objectForKey: @"Open"];
        if ( dict ) {
            value = [dict objectForKey: @"Shell"];
            if ( value ) {
                [self setOpenScriptShell: value];
            }
            else {
                NSLog(@"No shell for Open script set");
            }
            value = [dict objectForKey: @"Action"];
            if ( value ) {
                [self setOpenScriptAction: [WrapperDocument stringToScriptAction: value]];
            }
            else {
                NSLog(@"No action for Open script set");
                [self setOpenScriptAction: RunScriptAction];
            }
        }
        else {
            NSLog(@"No info for Open script");
        }

        // Load Info-gnustep.plist
        NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile: [infoFile filename]];
        value = [info objectForKey: @"ApplicationName"];
        if ( value ) {
            [self setName: value];
        }
        else {
            NSLog(@"ApplicationName not set");
        }
        value = [info objectForKey: @"ApplicationRelease"];
        if ( value ) {
            [self setVersion: value];
        }
        else {
            NSLog(@"ApplicationRelease not set");
        }
        value = [info objectForKey: @"FullVersionID"];
        if ( value ) {
            [self setFullVersion: value];
        }
        else {
            NSLog(@"FullVersionID not set");
        }
        value = [info objectForKey: @"ApplicationDescription"];
        if ( value ) {
            [self setDescription: value];
        }
        else {
            NSLog(@"ApplicationDescription not set");
        }
        value = [info objectForKey: @"ApplicationURL"];
        if ( value ) {
            [self setUrl: value];
        }
        else {
            NSLog(@"ApplicationURL not set");
        }
        NSArray *authorsArray = [info objectForKey: @"Authors"];
        if ( authorsArray ) {
            [self setAuthors: [authorsArray componentsJoinedByString: @", "]];
        }
        else {
            NSLog(@"Authors not set");
        }

        // types
        NSArray *typeDicts = [info objectForKey: @"NSTypes"];
        if ( typeDicts ) {
            int typeCount = [typeDicts count];
            int i;
            for ( i=0; i<typeCount; i++ ) {
                NSDictionary *typeDict = [typeDicts objectAtIndex: i];
                Type *type = AUTORELEASE([[Type alloc] init]);
                value = [typeDict objectForKey: @"NSName"];
                if ( value ) {
                    [type setName: value];
                }
                else {
                    NSLog(@"NSName not set for type #%d", i);
                }
                NSArray *extArray = [typeDict objectForKey: @"NSUnixExtensions"];
                if ( extArray ) {
                    [type setExtensions: [extArray componentsJoinedByString: @", "]];
                }
                else {
                    NSLog(@"NSUnixExtensions not set for type #%d", i);
                }
                NSString *typeIconFileName = [typeDict objectForKey: @"NSIcon"];
                if ( typeIconFileName ) {
                    NSFileWrapper *typeIconFile = [resources objectForKey: typeIconFileName];
                    if ( typeIconFile ) {
                        [type setIcon: [Icon iconWithImage: AUTORELEASE([[NSImage alloc] initByReferencingFile: [typeIconFile filename]])]];
                    }
                    else {
                        NSLog(@"Icon named %@ not found", typeIconFileName);
                    }
                }
                else {
                    NSLog(@"NSIcon not set for type #%d", i);
                }
                [self addType: type];
            }
        }
        else {
            NSLog(@"NSTypes not set");
        }

        // Load other resources
        NSFileWrapper *appIconFile = [resources objectForKey: @"AppIcon.tiff"];
        if ( appIconFile ) {
            //[self setAppIcon: [IconView imageWithData: [appIconFile regularFileContents]]];
            [self setAppIcon: [Icon iconWithImage: AUTORELEASE([[NSImage alloc] initByReferencingFile: [appIconFile filename]])]];
        }
        else {
            NSLog(@"AppIcon.tiff not found");
        }
        NSFileWrapper *startFile = [resources objectForKey: @"Start"];
        if ( startFile ) {
            [self setStartScript: [NSString stringWithContentsOfFile: [startFile filename]]];
        }
        else {
            NSLog(@"No Start script");
        }
        NSFileWrapper *startOpenFile = [resources objectForKey: @"StartOpen"];
        if ( startOpenFile ) {
            [self setStartOpenScript: [NSString stringWithContentsOfFile: [startOpenFile filename]]];
        }
        else {
            NSLog(@"No StartOpen script");
        }
        NSFileWrapper *openFile = [resources objectForKey: @"Open"];
        if ( openFile ) {
            [self setOpenScript: [NSString stringWithContentsOfFile: [openFile filename]]];
        }
        else {
            NSLog(@"No Open script");
        }

        // done
        [self updateChangeCount: NSChangeCleared];
        return YES;
    }
    NS_HANDLER {
        NSLog(@"Exception loading wrapper: %@", localException);
        return NO;
    } NS_ENDHANDLER;
}

- (NSFileWrapper *)saveWrapper
{
    /* Try to obtain GNUSTEP_IS_FLATTENED from the environment, in
     * case GNUSTEP_SH_EXPORT_ALL_VARIABLES is defined.  Resort to the
     * slower method if it's not exported.  */
    NSString *flattenedString = [[[NSProcessInfo processInfo] environment] objectForKey: @"GNUSTEP_IS_FLATTENED"];
    BOOL flattened;
    if ( flattenedString == nil ) {
        flattenedString = getVar(@"GNUSTEP_IS_FLATTENED");
            if ( [flattenedString isEqualToString: @""] )
                NSLog(@"GNUSTEP_IS_FLATTENED not set");
    }

    flattened = [flattenedString isEqualToString: @"yes"];

    //NSSize iconSize = NSMakeSize(48, 48);
    NSData *data;
    NSDictionary *dict;
    int i;

    // Info-gnustep.plist
    NSMutableDictionary *infoDict =
        [NSMutableDictionary dictionaryWithObjectsAndKeys:
                             @"AppIcon.tiff", @"NSIcon",
                             name, @"ApplicationName",
                             version, @"ApplicationRelease",
                             fullVersion, @"FullVersionID",
                             description, @"ApplicationDescription",
                             url, @"ApplicationURL",
                             @"NSApplication", @"NSPrincipalClass",
                             nil];
    switch ( role ) {
    case NoneRole:
        [infoDict setObject: @"None" forKey: @"NSRole"];
        break;
    case ViewerRole:
        [infoDict setObject: @"Viewer" forKey: @"NSRole"];
        break;
    case EditorRole:
        [infoDict setObject: @"Editor" forKey: @"NSRole"];
        break;
    }
    NSArray *authorArray = [self arrayFromCommaSeparatedString: [self authors]];
    if ( authorArray ) {
        [infoDict setObject: authorArray forKey: @"Authors"];
    }
    // types
    int typeCount = [types count];
    if ( typeCount ) {
        NSMutableArray *typeArray = [NSMutableArray arrayWithCapacity: typeCount];
        for ( i=0; i<typeCount; i++ ) {
            Type *type = [types objectAtIndex: i];
            NSString *iconFile = [NSString stringWithFormat: @"FileType_%03d.tiff", i];
            NSMutableDictionary *typeDict = [NSMutableDictionary dictionaryWithCapacity: 4];
            [typeDict setObject: iconFile forKey: @"NSIcon"];
            NSArray *extensions = [self arrayFromCommaSeparatedString: [type extensions]];
            if ( extensions ) {
                [typeDict setObject: extensions forKey: @"NSUnixExtensions"];
            }
            [typeDict setObject: [type name] forKey: @"NSName"];
            [typeArray addObject: typeDict];
        }
        [infoDict setObject: typeArray forKey: @"NSTypes"];
    }

    data = [[infoDict description] dataUsingEncoding: NSNonLossyASCIIStringEncoding];
    NSFileWrapper *info = AUTORELEASE([[NSFileWrapper alloc] initRegularFileWithContents: data]);
    [info setPreferredFilename: @"Info-gnustep.plist"];

    // GSWrapper.plist
    dict = [NSDictionary dictionaryWithObjectsAndKeys:
                         [NSNumber numberWithInt: 1], @"Version",
                         [NSDictionary dictionaryWithObjectsAndKeys:
                                       startScriptShell, @"Shell",
                                       [WrapperDocument scriptActionToString: startScriptAction], @"Action",
                                       nil], @"Start",
                         [NSDictionary dictionaryWithObjectsAndKeys:
                                       startOpenScriptShell, @"Shell",
                                       [WrapperDocument scriptActionToString: startOpenScriptAction], @"Action",
                                       nil], @"StartOpen",
                         [NSDictionary dictionaryWithObjectsAndKeys:
                                       openScriptShell, @"Shell",
                                       [WrapperDocument scriptActionToString: openScriptAction], @"Action",
                                       nil], @"Open",
                         nil];
    data = [[dict description] dataUsingEncoding: NSNonLossyASCIIStringEncoding];
    NSFileWrapper *gsWrapper = AUTORELEASE([[NSFileWrapper alloc] initRegularFileWithContents: data]);
    [gsWrapper setPreferredFilename: @"GSWrapper.plist"];

    NSFileWrapper *icon = AUTORELEASE([[NSFileWrapper alloc] initRegularFileWithContents: [[appIcon imageForOriginalSizeCopy: NO] TIFFRepresentation]]);
    //NSFileWrapper *icon = AUTORELEASE([[NSFileWrapper alloc] initRegularFileWithContents: [appIcon scaledTIFFRepresentation: iconSize]]);
    //NSLog(@"Icon: %@", [appIcon scaledTIFFRepresentation: iconSize]);
    [icon setPreferredFilename: @"AppIcon.tiff"];

    data = [startScript dataUsingEncoding: [NSString defaultCStringEncoding]];
    NSFileWrapper *start = AUTORELEASE([[NSFileWrapper alloc] initRegularFileWithContents: data]);
    [start setPreferredFilename: @"Start"];

    data = [startOpenScript dataUsingEncoding: [NSString defaultCStringEncoding]];
    NSFileWrapper *startOpen = AUTORELEASE([[NSFileWrapper alloc] initRegularFileWithContents: data]);
    [startOpen setPreferredFilename: @"StartOpen"];

    data = [openScript dataUsingEncoding: [NSString defaultCStringEncoding]];
    NSFileWrapper *open = AUTORELEASE([[NSFileWrapper alloc] initRegularFileWithContents: data]);
    [open setPreferredFilename: @"Open"];

    NSFileWrapper *resources = [[NSFileWrapper alloc] initDirectoryWithFileWrappers:
                                                          [NSDictionary dictionaryWithObjectsAndKeys:
                                                                        info, [info preferredFilename],
                                                                        gsWrapper, [gsWrapper preferredFilename],
                                                                        icon, [icon preferredFilename],
                                                                        start, [start preferredFilename],
                                                                        startOpen, [startOpen preferredFilename],
                                                                        open, [open preferredFilename],
                                                                        nil]];
    // file type icons
    for ( i=0; i<typeCount; i++ ) {
        Type *type = [types objectAtIndex: i];
        NSFileWrapper *typeIcon = AUTORELEASE([[NSFileWrapper alloc] initRegularFileWithContents: [[[type icon] imageForOriginalSizeCopy: NO] TIFFRepresentation]]);
        //NSFileWrapper *typeIcon = AUTORELEASE([[NSFileWrapper alloc] initRegularFileWithContents: [[type icon] scaledTIFFRepresentation: iconSize]]);
        [typeIcon setPreferredFilename: [NSString stringWithFormat: @"FileType_%03d.tiff", i]];
        [resources addFileWrapper: typeIcon];
    }

    [resources setPreferredFilename: @"Resources"];
    AUTORELEASE(resources);

    NSDictionary *environment = [[NSProcessInfo processInfo] environment];
    NSArray *exePathComponents = [NSArray arrayWithObjects:
                                          [environment objectForKey: @"GNUSTEP_HOST_CPU"],
                                          [environment objectForKey: @"GNUSTEP_HOST_OS"],
                                          [environment objectForKey: @"LIBRARY_COMBO"],
                                          nil];

    if ( [exePathComponents count] < 3 )
        exePathComponents = [NSArray arrayWithObjects:
                                     getVar(@"GNUSTEP_HOST_CPU"),
                                     getVar(@"GNUSTEP_HOST_OS"),
                                     getVar(@"LIBRARY_COMBO"),
                                     nil];

    NSData *script;
    if ( flattened ) {
        script = nil;
    }
    else {
        script = [NSData dataWithContentsOfFile: [NSString pathWithComponents:
                                                               [NSArray arrayWithObjects:
                                                                        [[NSBundle mainBundle] bundlePath],
                                                                        @"WrapperFactory",
                                                                        nil]]];
    }

    NSData *exe;
    if ( flattened ) {
        exe = [NSData dataWithContentsOfFile: [[NSBundle mainBundle] pathForResource: launcherName
                                                                     ofType: (nil)]];

    }
    else {
        NSString *path = [NSString pathWithComponents:
                                       [exePathComponents arrayByAddingObject:
                                                              launcherName]];
        exe = [NSData dataWithContentsOfFile: [[NSBundle mainBundle] pathForResource: path
                                                                     ofType: (nil)]];
    }

    NSFileWrapper *exedir = nil;
    for ( i=[exePathComponents count]-1; i>=0; i-- ) {
        //dir = [[NSFileWrapper alloc] initWithPath: ];app
        if ( exedir ) {
            exedir = [[NSFileWrapper alloc] initDirectoryWithFileWrappers:
                                                [NSDictionary dictionaryWithObjectsAndKeys: exedir, [exedir preferredFilename], nil]];
        }
        else {
            exedir = [[NSFileWrapper alloc] initDirectoryWithFileWrappers: [NSDictionary dictionary]];
        }
        [exedir setPreferredFilename: [exePathComponents objectAtIndex: i]];
        AUTORELEASE(exedir);
    }

    AppFileWrapper *app = [[AppFileWrapper alloc] initDirectoryWithFileWrappers:
                                                      [NSDictionary dictionaryWithObjectsAndKeys:
                                                                    exedir, [exedir preferredFilename],
                                                                    resources, [resources preferredFilename],
                                                                    nil]];
    AUTORELEASE(app);
    [app setFlattened: flattened];
    [app setScript: script];
    [app setExecutable: exe];
    [app setExecutablePath: [NSString pathWithComponents: exePathComponents]];
    return app;
}

- (BOOL)loadFreedesktopApplication: (NSFileWrapper *)file
{
    if ( ![file isRegularFile] ) {
        NSLog(@"%@ is not a regular file");
        return NO;
    }

    NSString *fdentry = [[NSString alloc] initWithData: [file regularFileContents] encoding: NSUTF8StringEncoding];
    AUTORELEASE(fdentry);
    NSArray *lines = [fdentry componentsSeparatedByString: @"\n"];

    int lineCount = [lines count];
    int i;
    NSString *exec = nil;
    NSString *path = nil;
    NSString *section = nil;
    for ( i=0; i<lineCount; i++ ) {
        NSString *l = (NSString *)[lines objectAtIndex: i];
#ifdef GNUSTEP
        l = [l stringByTrimmingSpaces];
#else
#error -stringByTrimmingSpaces is only supported under GNUstep
#endif
        if ( ([l length] <= 0) || ([l hasPrefix: @"#"]) ) {
            // comment/blank: skip$
            continue;
        }
        else if ( [l hasPrefix: @"["] ) {
            if ( ![l hasSuffix: @"]"] ) {
                NSLog(@"Invalid section header: ] expected");
                return NO;
            }
            section = [l substringWithRange: NSMakeRange(1, [l length]-2)];
            NSLog(@"Section: \"%@\"", section);
        }
        else {
            if ( !section ) {
                NSLog(@"No section");
                return NO;
            }
            NSRange split = [l rangeOfString: @"="];
            NSString *key = [[l substringToIndex: split.location] stringByTrimmingSpaces];
            NSString *value = [[l substringFromIndex: split.location+1] stringByTrimmingSpaces];
            if ( [key length] <= 0 ) {
                NSLog(@"No key: %@", l);
                return NO;
            }
            NSLog(@"Entry: %@=%@", key, value);

            if ( [section isEqualToString: @"Desktop Entry"] ) {
                if ( [key isEqualToString: @"Type"] ) {
                    // FIXME: Only apps?
                }
                else if ( [key isEqualToString: @"Name"] ) {
                    [self setName: value];
                }
                else if ( [key isEqualToString: @"Comment"] ) {
                    [self setDescription: value];
                }
                else if ( [key isEqualToString: @"Icon"] ) {
                    // FIXME: load the icon
                }
                else if ( [key isEqualToString: @"Exec"] ) {
                    NSLog(@"fjsaail");
                    exec = value;
                }
                else if ( [key isEqualToString: @"Path"] ) {
                    path = value;
                }
                else if ( [key isEqualToString: @"Terminal"] ) {
                    // FIXME: run in terminal -> Terminal.app?
                }
                else {
                    NSLog(@"Ignoring entry in section %@: %@=%@", section, key, value);
                }
            }
            else {
                NSLog(@"Ignoring entry in section %@: %@=%@", section, key, value);
            }
        }
    }
    if ( exec == nil ) {
        NSLog(@"No executable specified");
        return NO;
    }
    if ( path ) {
        path = [NSString stringWithFormat: @"cd \"%@\"\n", path];
    }
    else {
        path = @"";
    }
    // FIXME: actions
    [self setStartScript: [NSString stringWithFormat: @"%@exec \"%@\"\n", path, exec]];
    [self setStartOpenScript: [NSString stringWithFormat: @"%@exec \"%@\" \"$@\"\n", path, exec]];
    [self setOpenScript: @"exit 1\n"];
    return YES;
}

- (NSFileWrapper *)saveFreedesktopApplication
{
    NSLog(@"Saving freedesktop desktop entries not supported yet");
    return nil;
}

+ (ScriptAction)stringToScriptAction: (NSString *)str
{
    if ( [str isEqualToString: actionRunScript] ) {
        return RunScriptAction;
    }
    else if ( [str isEqualToString: actionFail] ) {
        return FailAction;
    }
    else if ( [str isEqualToString: actionIgnore] ) {
        return IgnoreAction;
    }
    else {
        NSLog(@"Invalid action string: %@; defaulting to %@", str, actionRunScript);
        return RunScriptAction;
    }
}

+ (NSString *)scriptActionToString: (ScriptAction)action
{
    switch ( action ) {
    case RunScriptAction:
        return actionRunScript;
    case FailAction:
        return actionFail;
    case IgnoreAction:
        return actionIgnore;
    default:
        NSLog(@"Invalid action constant: %d; defaulting to 0 (RunScript)", action);
        return actionRunScript;
    }
}

@end