File: EOKeyValueArchiver.m

package info (click to toggle)
gnustep-dl2 0.12.0%2Bgit20250112-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 7,092 kB
  • sloc: objc: 68,223; makefile: 60; sh: 48
file content (868 lines) | stat: -rw-r--r-- 18,249 bytes parent folder | download
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
/** 
   EOKeyValueArchiver.m <title>EOKeyValueArchiver Class</title>

   Copyright (C) 2000-2002,2003,2004,2005 Free Software Foundation, Inc.

   Author: Manuel Guesdon <mguesdon@orange-concept.com>
   Date: September 2000

   $Revision$
   $Date$

   <abstract>
   EOKeyValueArchiver object is used to archive a tree of objects into a 
   	key/value propertyList.
   EOKeyValueUnarchiver object is used to unarchive from a propertyList a 
	tree of objects archived with a EOKeyValueArchiver.

   Example:

   // Archiving:
   EOKeyValueArchiver* archive=AUTORELEASE([EOKeyValueArchiver new]);
   [archive setDelegate:MyArchivingDelegate];
   [archiver encodeObject:anObject
   forKey:@"anObjectKey"];
   [archiver encodeInt:125
   forKey:@"aKey"];
   ...

   NSDictionary* archivePropertyList=[archiver dictionary];

   // Now unarchive archivePropertyList

   EOKeyValueUnarchiver* unarchiver=AUTORELEASE([[EOKeyValueUnarchiver alloc]initWith:archivePropertyList]);
   [archive setDelegate:MyUnarchivingDelegate];
   id anObject=[unarchiver decodeObjectForKey:@"anObjectKey"];
   int anInt=[unarchiver decodeIntForKey:@"anKey"];
   [unarchiver finishInitializationOfObjects];
   [unarchiver awakeObjects]
   </abstract>

   This file is part of the GNUstep Database Library.

   <license>
   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License as published by the Free Software Foundation; either
   version 3 of the License, or (at your option) any later version.

   This library 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
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public
   License along with this library; see the file COPYING.LIB.
   If not, write to the Free Software Foundation,
   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
   </license>
**/

#include "config.h"

#ifdef GNUSTEP
#include <Foundation/NSArray.h>
#include <Foundation/NSDebug.h>
#include <Foundation/NSDictionary.h>
#include <Foundation/NSEnumerator.h>
#include <Foundation/NSException.h>
#include <Foundation/NSString.h>
#include <Foundation/NSValue.h>
#else
#include <Foundation/Foundation.h>
#endif

#ifndef GNUSTEP
#include <GNUstepBase/GNUstep.h>
#include <GNUstepBase/NSDebug+GNUstepBase.h>
#endif

#include <EOControl/EOKeyValueArchiver.h>
#include <EOControl/EODebug.h>
#include <EOControl/EOPrivate.h>


@interface EOKeyValueArchivingContainer : NSObject
{
  id _object;
  id _parent;
  NSDictionary * _propertyList;
}

+ (EOKeyValueArchivingContainer*)keyValueArchivingContainer;
- (void) setPropertyList: (id)propList;
- (id) propertyList;
- (void) setParent: (id)parent;
- (id) parent;
- (void) setObject: (id)object;
- (id) object;

@end


@implementation EOKeyValueArchivingContainer

+ (void)initialize
{
  static BOOL initialized=NO;
  if (!initialized)
    {
      initialized=YES;

      GDL2_PrivateInit();
    }
}

+ (EOKeyValueArchivingContainer *)keyValueArchivingContainer
{
  return [[[self alloc] init] autorelease];
}

- (void) setPropertyList: (id)propList
{
  ASSIGN(_propertyList, propList);
}

- (id) propertyList
{
  return _propertyList;
}

- (void) setParent: (id)parent
{
  _parent = parent;
}

- (id) parent
{
  return _parent;
}

- (void) setObject: (id)object
{
  ASSIGN(_object, object);
}

- (id) object
{
  return _object;
}

- (void) dealloc
{
  DESTROY(_object);
  _parent = nil;
  DESTROY(_propertyList);

  [super dealloc];
}

@end

@implementation EOKeyValueArchiver

+ (void)initialize
{
  static BOOL initialized=NO;
  if (!initialized)
    {
      initialized=YES;

      GDL2_PrivateInit();
    }
}

/** Init method **/
- (id) init
{
  if ((self=[super init]))
    {
      _propertyList=[NSMutableDictionary new];
    };
  return self;
}

- (void) dealloc
{
  DESTROY(_propertyList);
  [super dealloc];
}

/** Returns archived object/tree as propertList **/
- (NSDictionary*) dictionary
{


  return _propertyList;
}

/** Archives integer 'intValue' as 'key' **/
- (void) encodeInt: (int)intValue
	    forKey: (NSString*)key
{



  NSAssert(key,@"No key");

  [_propertyList setObject: [NSNumber numberWithInt: intValue]
                 forKey: key];




}

/** Archives boolean 'yn' as 'key' **/
- (void) encodeBool: (BOOL)yn
	     forKey: (NSString*)key
{  



  NSAssert(key,@"No key");

  [_propertyList setObject: [NSNumber numberWithBool: yn]
                 forKey: key];




}

/** Archives a dictionary for 'key' **/
- (void) _encodeDictionary: (NSDictionary*)dictionary
		    forKey: (NSString*)key
{



  NSAssert(key,@"No key");

  if ([dictionary count]>0)
    {
      NSEnumerator* keyEnumerator=nil;
      NSString* tmpKey=nil;
      NSMutableDictionary* currentPropertyList=nil;

      // Save current propertyList
      currentPropertyList=AUTORELEASE(_propertyList);


      // Set new empty propertyList to encode each object
      _propertyList=[NSMutableDictionary new];

      keyEnumerator=[dictionary keyEnumerator];
      while((tmpKey=[keyEnumerator nextObject]))
        {
          id object=[dictionary valueForKey:tmpKey];
          
          [self encodeObject:object
                forKey:tmpKey];          
        };

      // add _propertyList into current propertyList 
      // for the key
      [currentPropertyList setObject:_propertyList
                           forKey:key];

      // put back current propertyList
      ASSIGN(_propertyList,currentPropertyList);      
    }
  else
    {
      [_propertyList setObject:[NSDictionary dictionary]
                     forKey:key];
    };


}

/** Archives an array objects for 'key' **/
- (void) _encodeObjects: (NSArray*)objects
		 forKey: (NSString*)key
{
  unsigned int count=0;




  NSAssert(key,@"No key");

  count=[objects count];
  if (count>0)
    {
      unsigned int i=0;
      NSMutableDictionary* currentPropertyList=nil;
      NSMutableArray* archiveArray=(NSMutableArray*)[NSMutableArray array];

      // Save current propertyList
      currentPropertyList=AUTORELEASE(_propertyList);


      // Set new empty propertyList to encode each object
      _propertyList=[NSMutableDictionary new];

      for(i=0;i<count;i++)
        {
          id object=[objects objectAtIndex:i];
          id encodedObject=nil;
          
          [self encodeObject:object
                forKey:@"voidKey"];
          
          encodedObject=[_propertyList objectForKey:@"voidKey"];          

          NSAssert1(encodedObject,@"No encodedObject for %@",object);

          [archiveArray addObject:encodedObject];

          [_propertyList removeObjectForKey:@"voidKey"];
        };

      // add archiveArray into current propertyList 
      // for the key
      [currentPropertyList setObject:archiveArray
                           forKey:key];

      // put back current propertyList
      ASSIGN(_propertyList,currentPropertyList);      
    }
  else
    {
      [_propertyList setObject:[NSArray array]
                     forKey:key];
    };


}

- (void) _encodeValue: (id)value
	       forKey: (NSString*)key
{
  //Private EO methods. Not currently used
  [self notImplemented: _cmd];	//TODOFN
}


/** Archives the object 'object' reference as 'key'
The receiver gets the reference object by calling 
its delegate method -archiver:referenceToEncodeForObject:
**/
- (void) encodeReferenceToObject: (id)object
			  forKey: (NSString*)key
{



  NSAssert(key,@"No key");

  // object is nil ?
  if (!object)
    {
      //Hum, what to do for nil object ? //TODO
    }
  else
    {
      // First get object reference
      if ([_delegate 
            respondsToSelector:@selector(archiver:referenceToEncodeForObject:)])
      object = [_delegate archiver:self
                          referenceToEncodeForObject:object];
      



      //TODO
      // What should we do when delegate returns no reference ?
      // Here we decide to encode it directly...
     
      [self encodeObject:object
            forKey:key];
    };




}

/** Archives the object 'object' as 'key'.
'object' should be a NSString, a NSData, NSArray or NSDictionary or conforms to 
EOKeyValueArchiving protocol. Raise an exception otherwise.
**/
- (void) encodeObject: (id)object
	       forKey: (NSString*)key
{



  NSAssert(key,@"No key");

  // object is nil ?
  if (!object)
    {
      //Hum, what to do for nil object ? //TODO
    }
  else if ([object isKindOfClass:GDL2_NSStringClass]
           || [object isKindOfClass:GDL2_NSDataClass]
           || [object isKindOfClass:GDL2_NSNumberClass])
    {
      // Add NSString & NSData directly (or a copy if it is mutable)

      id objectCopy=[object copy];
      [_propertyList setObject:objectCopy
                     forKey:key];
      DESTROY(objectCopy);
    }
  else if ([object isKindOfClass:GDL2_NSDictionaryClass])
    {
      [self _encodeDictionary:object
            forKey:key];
    }
  else if ([object isKindOfClass:GDL2_NSArrayClass])
    {
      [self _encodeObjects:object
            forKey:key];
    }
  else if ([object conformsToProtocol:@protocol(EOKeyValueArchiving)])
    {
      // Object conforms to protocol EOKeyValueArchiving ?
      
      // We will encode it in self empty propertyList and put this 
      // propertyList back and the current propertyList

      // Save current propertyList
      NSMutableDictionary* currentPropertyList=nil;
      currentPropertyList=AUTORELEASE(_propertyList);


      // Set new empty one as current one
      _propertyList=[NSMutableDictionary new];

      // add object class name to object propertyList
      [_propertyList setObject:NSStringFromClass([object class])
                     forKey:@"class"];

      // Encode object
      [object encodeWithKeyValueArchiver:self];



      // add object propertyList into current propertyList 
      // for the key
      [currentPropertyList setObject:_propertyList
                           forKey:key];

      // put back current propertyList
      ASSIGN(_propertyList,currentPropertyList);      
    }
  else
    {
       [NSException raise:NSInvalidArgumentException
                    format:@"Don't know how to keyValue archive object %@ for key %@",
                    object,key];
                    
    };




}

/** Returns receiver's delegate **/
- (id) delegate
{
  return _delegate;
}

/** Set receiver's delegate **/
- (void) setDelegate: (id)delegate
{


  _delegate=delegate;


}

@end


@implementation NSObject (EOKeyValueArchiverDelegation)

/** Returns an object to be used as reference for 'archiver' 
to archive 'object'.
Should be overriden by EOKeyValueArchiver's delegates 
**/
- (id)archiver: (EOKeyValueArchiver *)archiver 
referenceToEncodeForObject: (id)object
{
  [self subclassResponsibility:_cmd];
  return nil;
}

@end


@implementation EOKeyValueUnarchiver

/** Inits unarchiver with propertyList 'dictionary' **/
- (id) initWithDictionary: (NSDictionary*)dictionary
{
  if ((self = [super init]))
    {
      ASSIGN(_propertyList, dictionary);
      _allUnarchivedObjects = [NSMutableArray array];

      RETAIN(_allUnarchivedObjects);
    }

  return self;
}

/** Finalize unarchiving by calling finishInitializationWithKeyValueUnarchiver:
on all unarchived objects **/
- (void) finishInitializationOfObjects
{
  int i;
  int count = [_allUnarchivedObjects count];

  for (i = 0; i < count; i++)
    {
      EOKeyValueArchivingContainer *container;
      id object;

      container = [_allUnarchivedObjects objectAtIndex: i];
      object = [container object];



      [object finishInitializationWithKeyValueUnarchiver: self];
    }
}

- (void) dealloc
{
  DESTROY(_propertyList);
  DESTROY(_allUnarchivedObjects);

  if (_awakenedObjects)
    NSFreeHashTable(_awakenedObjects);

  [super dealloc];
}

/** Finalize unarchiving by calling awakeFromKeyValueUnarchiver: 
on all unarchived objects **/
- (void) awakeObjects
{
  int i;
  int count = [_allUnarchivedObjects count];

  if (!_awakenedObjects)
    _awakenedObjects = NSCreateHashTable(NSNonRetainedObjectHashCallBacks,
					 count);

  for (i = 0; i < count; i++)
    {
      EOKeyValueArchivingContainer *container;
      id object;



      container = [_allUnarchivedObjects objectAtIndex: i];
      object = [container object];

      [self ensureObjectAwake:object];
    }
}

/** ensure 'object' is awake 
(has received -awakeFromKeyValueUnarchiver: message) **/
- (void) ensureObjectAwake: (id)object
{
  if (object)
    {
      if (!NSHashInsertIfAbsent(_awakenedObjects, object))
        {


          [object awakeFromKeyValueUnarchiver: self];
        }
    }
}

/** Returns unarchived integer which was archived as 'key'.
0 if no object is found **/
- (int) decodeIntForKey: (NSString*)key
{
  id object = nil;



  object = [_propertyList objectForKey: key];

  return (object ? [object intValue] : 0);
}

/** Returns unarchived boolean which was archived as 'key'.
NO if no object is found **/
- (BOOL) decodeBoolForKey: (NSString*)key
{
  id object=nil;



  object = [_propertyList objectForKey: key];

  return (object ? [[_propertyList objectForKey: key] boolValue] : NO);
}

/** Returns unarchived object for the reference archived as 'key'. 
The receiver gets the object for reference by calling 
its delegate method -unarchiver:objectForReference: **/
- (id) decodeObjectReferenceForKey: (NSString*)key
{
  id objectReference = nil;
  id object;



  object = [self decodeObjectForKey: key];

  if (object)
    {
      objectReference = [_delegate unarchiver: self
				   objectForReference: object];
    }

  return objectReference;
}

/** Returns unarchived object for key. 
The object should be a NSString, NSData, NSArray or NSDictionary or its 
class instances should implements -initWithKeyValueUnarchiver: **/
- (id) decodeObjectForKey: (NSString*)key
{
  id propListObject;
  id obj = nil;



  propListObject = [_propertyList objectForKey: key];


  if (propListObject)
    {
      obj = [self _findTypeForPropertyListDecoding: propListObject];
    }



  return obj;
}

/** Returns YES if there's a value for key 'key' **/
- (BOOL) isThereValueForKey: (NSString *)key
{
  return ([_propertyList objectForKey: key] != nil);
}

- (id) _findTypeForPropertyListDecoding: (id)obj
{
  id retVal = nil;



  if ([obj isKindOfClass: GDL2_NSDictionaryClass])
    {
      NSString *className = [obj objectForKey: @"class"];

      if (className)
        retVal = [self _objectForPropertyList: obj];
      else
        retVal = [self _dictionaryForPropertyList: obj];

      if (!retVal)
        {
          //TODO

        }
    }
  else if ([obj isKindOfClass: GDL2_NSArrayClass])
    retVal = [self _objectsForPropertyList: obj];
  else
    retVal=obj;



  return retVal;
}

- (id) _dictionaryForPropertyList: (NSDictionary*)propList
{
  NSMutableDictionary *dict = [NSMutableDictionary dictionary];
  NSEnumerator *enumerator = [propList keyEnumerator];
  id key;

  while ((key = [enumerator nextObject]))
    {
      id object;
      id retObject;



      object = [propList objectForKey: key];


      retObject = [self _findTypeForPropertyListDecoding: object];


      if (!retObject)
        {

          //TODO
        }
      else
        [dict setObject: retObject
              forKey: key];
    }

  return dict;
}

- (id) _objectsForPropertyList: (NSArray*)propList
{
  NSMutableArray *newObjects = [NSMutableArray array];
  id              object = nil;
  NSEnumerator	 *propListEnum;
  id		  propListObject;



  if (propList && (propListEnum = [propList objectEnumerator]))
    {
      while ((propListObject = [propListEnum nextObject]))
	{
	  object = [self _findTypeForPropertyListDecoding: propListObject];

	  if (object)
	    {
	      [newObjects addObject: object];
	    }
	}
    }



  return newObjects;
}

- (id) _objectForPropertyList: (NSDictionary*)propList
{
  EOKeyValueArchivingContainer *container = nil;
  NSString *className = nil;
  Class objectClass = Nil;
  id object = nil;
  NSDictionary *oldPropList = AUTORELEASE(_propertyList);

  _propertyList = RETAIN(propList); //Because dealloc may try to release it



  NS_DURING
    {
      className = [propList objectForKey: @"class"];
      objectClass = NSClassFromString(className);  

      NSAssert1(objectClass, @"ERROR: No class named '%@'", className);

      object = [[[objectClass alloc] initWithKeyValueUnarchiver: self]
		 autorelease];
      container = [EOKeyValueArchivingContainer keyValueArchivingContainer];

      [container setObject: object];
      [container setParent: nil]; //TODO VERIFY
      [container setPropertyList: propList];

      [_allUnarchivedObjects addObject: container];
    }
  NS_HANDLER
    {
      NSDebugMLLog(@"gsdb", @"EOKeyValueUnarchiver, EXCEPTION:%@ (%@) [%s %d]",
                   localException,
                   [localException reason],
                   __FILE__,
                   __LINE__);

      //Restaure the original propertyList
      _propertyList = RETAIN(oldPropList);

      AUTORELEASE(propList);
      [localException raise];
    }
  NS_ENDHANDLER;

  _propertyList = RETAIN(oldPropList);

  AUTORELEASE(propList);




  return object;
}

/** Returns the parent object for the currently unarchiving object. 
**/
- (id) parent
{
  return _parent;
}

/** Returns receiver's delegate **/
- (id) delegate
{
  return _delegate;
}

/** Set the receiver's delegate **/
- (void) setDelegate:(id)delegate
{
  _delegate=delegate;
}

@end


@implementation NSObject (EOKeyValueUnarchiverDelegation)

/** 
 * Returns an object for archived 'reference'.
 * Implemented by EOKeyValueUnarchiver's delegate.
 */
- (id)unarchiver: (EOKeyValueUnarchiver*)archiver 
objectForReference: (id)keyPath
{
  [self subclassResponsibility:_cmd];
  return nil;
}

@end


@implementation NSObject(EOKeyValueArchivingAwakeMethods) 
                    
- (void)finishInitializationWithKeyValueUnarchiver: (EOKeyValueUnarchiver *)unarchiver
{
  //Does nothing ?
  return;
}

- (void)awakeFromKeyValueUnarchiver: (EOKeyValueUnarchiver *)unarchiver
{
  //Does nothing ?
  return;
}

@end