File: EOKeyValueCoding.m

package info (click to toggle)
gnustep-dl2 0.11.0-1.1
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 4,152 kB
  • ctags: 743
  • sloc: objc: 61,254; makefile: 50
file content (1344 lines) | stat: -rw-r--r-- 36,590 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
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
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
/** 
   EOKeyValueCoding.m <title>EOKeyValueCoding</title>

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

   Author: Mircea Oancea <mircea@jupiter.elcom.pub.ro>
   Date: November 1996

   Author: Mirko Viviani <mirko.viviani@gmail.com>
   Date: February 2000

   Author: Manuel Guesdon <mguesdon@oxymium.net>
   Date: January 2002

   Author: David Ayers <ayers@fsfe.org>
   Date: February 2003


   <abstract></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 2 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"

RCS_ID("$Id: EOKeyValueCoding.m 24314 2007-01-04 22:51:31Z ayers $")

#ifdef GNUSTEP
#include <Foundation/NSObject.h>
#include <Foundation/NSArray.h>
#include <Foundation/NSDictionary.h>
#include <Foundation/NSString.h>
#include <Foundation/NSValue.h>
#include <Foundation/NSHashTable.h>
#include <Foundation/NSException.h>
#include <Foundation/NSObjCRuntime.h>
#include <Foundation/NSMapTable.h>
#include <Foundation/NSUtilities.h>
#include <Foundation/NSDecimalNumber.h>
#include <Foundation/NSDebug.h>
#else
#include <Foundation/Foundation.h>
#endif

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

#include <EOControl/EOKeyValueCoding.h>
#include <EOControl/EONSAddOns.h>
#include <EOControl/EODebug.h>
#include <EOControl/EONull.h>

#include <GNUstepBase/GSObjCRuntime.h>

#include "EOPrivate.h"

static BOOL    strictWO;
static BOOL initialized=NO;

static inline void
initialize(void)
{
  if (!initialized)
    {
      initialized=YES;
      strictWO = GSUseStrictWO451Compatibility(nil);
      GDL2_PrivateInit();
    }
}

/* This macro is only used locally in defined places so for the sake
   of efficiency, we don't use the do {} while (0) pattern.  */
#define INITIALIZE if (!initialized) initialize();


@implementation NSObject (_EOKeyValueCodingCompatibility)

- (void)GDL2KVCNSObjectICategoryID
{
}

+ (void)load
{
  GDL2_ActivateCategory("NSObject",
			@selector(GDL2KVCNSObjectICategoryID), YES);
}


/* This is what -base(add) will call.  It should invoke what the API
   specifies should be overridden.  */
- (void) setNilValueForKey: (NSString*)aKey
{
  [self unableToSetNilForKey: aKey];
}


/* This is what should be overridden according to the API.*/
- (void) unableToSetNilForKey: (NSString *)key
{
  [NSException raise: NSInvalidArgumentException
	       format: @"%@ -- %@ 0x%x: Given nil value to set for key \"%@\"",
	       NSStringFromSelector(_cmd), NSStringFromClass([self class]), 
	       self, key];
}

/* See EODeprecated.h. */
+ (void) flushClassKeyBindings
{
}

/* See header file for documentation. */
+ (void) flushAllKeyBindings
{
}

- (void) takeValue: (id)anObject forKey: (NSString*)aKey
{
  SEL		sel = 0;
  const char	*type = 0;
  int		off;
  unsigned	size = [aKey length];

  if (size > 0)
    {
      const char	*name;
      char		buf[size+6];
      char		lo;
      char		hi;

      strcpy(buf, "_set");
      [aKey getCString: &buf[4]];
      lo = buf[4];
      hi = islower(lo) ? toupper(lo) : lo;
      buf[4] = hi;
      buf[size+4] = ':';
      buf[size+5] = '\0';

      name = &buf[1];	// setKey:
      type = NULL;
      sel = GSSelectorFromName(name);
      if (sel == 0 || [self respondsToSelector: sel] == NO)
	{
	  name = buf;	// _setKey:
	  sel = GSSelectorFromName(name);
	  if (sel == 0 || [self respondsToSelector: sel] == NO)
	    {
	      sel = 0;
	      if ([[self class] accessInstanceVariablesDirectly] == YES)
		{
		  buf[size+4] = '\0';
		  buf[3] = '_';
		  buf[4] = lo;
		  name = &buf[4];	// key
		  if (GSObjCFindVariable(self, name, &type, &size, &off) == NO)
		    {
		      name = &buf[3];	// _key
		      GSObjCFindVariable(self, name, &type, &size, &off);
		    }
		}
	    }
	}
    }
  GSObjCSetVal(self, [aKey UTF8String], anObject, sel, type, size, off);
}


- (void) takeValue: (id)anObject forKeyPath: (NSString*)aKey
{
  NSRange	r = [aKey rangeOfString: @"."];

  if (r.length == 0)
    {
      [self takeValue: anObject forKey: aKey];
    }
  else
    {
      NSString	*key = [aKey substringToIndex: r.location];
      NSString	*path = [aKey substringFromIndex: NSMaxRange(r)];

      [[self valueForKey: key] takeValue: anObject forKeyPath: path];
    }
}


- (void) takeValuesFromDictionary: (NSDictionary*)aDictionary
{
  NSEnumerator	*enumerator = [aDictionary keyEnumerator];
  NSNull	*null = [NSNull null];
  NSString	*key;

  while ((key = [enumerator nextObject]) != nil)
    {
      id obj = [aDictionary objectForKey: key];

      if (obj == null)
	{
	  obj = nil;
	}
      [self takeValue: obj forKey: key];
    }
}

@end


/*
  This declaration is needed by the compiler to state that
  eventhough we know not all objects respond to -compare:,
  we want the compiler to generate code for the given
  prototype when calling -compare: in the following methods.
  We do not put this declaration in a header file to avoid
  the compiler seeing conflicting prototypes in user code.
*/
@interface NSObject (Comparison)
- (NSComparisonResult)compare: (id)other;
@end


@implementation NSArray (EOKeyValueCoding)

- (void)GDL2KVCNSArrayICategoryID
{
}

+ (void)load
{
  GDL2_ActivateCategory("NSArray",
			@selector(GDL2KVCNSArrayICategoryID), YES);
}

/**
 * EOKeyValueCoding protocol<br/>
 * This overrides NSObjects implementation of this method.
 * Generally this method returns an array of objects
 * returned by invoking [NSObject-valueForKey:]
 * for each item in the receiver, substituting EONull for nil.
 * Keys formated like "@function.someKey" are resolved by invoking
 * <code>NSArray compute<em>Function</em>WithKey:</code> "someKey" on the receiver.
 * If the key is omitted, the function will be called with nil.
 * The following functions are supported by default:
 * <list>
 *  <item>@sum   -> -computeSumForKey:</item>
 *  <item>@avg   -> -computeAvgForKey:</item>
 *  <item>@max   -> -computeMaxForKey:</item>
 *  <item>@min   -> -computeMinForKey:</item>
 *  <item>@count -> -computeCountForKey:</item>
 * </list>
 * Computational components generally expect a key to be passed to
 * the function.  This is not mandatory in which case 'nil' will be supplied.
 * (i.e. you may use "@myFuncWhichCanHandleNil" as a key.)
 * As a special case the key "count" does not actually invoke
 * computeCountForKey: on receiver but returns the number of objects of 
 * the receiver.<br/>
 * There is no special handling of EONull.  Therefore expect exceptions
 * on EONull not responding to decimalValue and compare: when the are
 * used with this mechanism. 
 */
- (id)valueForKey: (NSString *)key
{
  id result;

  INITIALIZE;

  EOFLOGObjectFnStartCond(@"EOKVC");
  if ([key isEqualToString: @"count"] || [key isEqualToString: @"@count"])
    {
      result = [NSDecimalNumber numberWithUnsignedInt: [self count]];
    }
  else if ([key hasPrefix:@"@"])
    {
      NSString *selStr;
      NSString *attrStr;
      SEL       sel;
      NSRange   r;

      r = [key rangeOfString:@"."];
      if (r.location == NSNotFound)
	{
	  r.length   = [key length] - 1; /* set length of key (w/o @) */
	  r.location = 1;                /* remove leading '@' */
	  attrStr = nil;
	}
      else
	{
	  r.length  = r.location - 1;    /* set length of key (w/o @) */
	  r.location = 1;                /* remove leading '@' */
                                         /* skip located '.' */
	  attrStr = [key substringFromIndex: NSMaxRange(r) + 1];
	}

      selStr = [NSString stringWithFormat: @"compute%@ForKey:",
		   [[key substringWithRange: r] initialCapitalizedString]];
      sel = NSSelectorFromString(selStr);
      NSAssert2(sel!=NULL,@"Invalid computational key: '%@' Selector: '%@'",
                key,
                selStr);

      result = [self performSelector: sel
		     withObject: attrStr];
    }
  else
    {
      result = [self resultsOfPerformingSelector: @selector(valueForKey:)
		     withObject: key
		     defaultResult: GDL2_EONull];
    }

  EOFLOGObjectFnStopCond(@"EOKVC");
  return result;
}

/**
 * EOKeyValueCoding protocol<br/>
 * Returns the object returned by invoking [NSObject-valueForKeyPath:]
 * on the object returned by invoking [NSObject-valueForKey:]
 * on the receiver with the first key component supplied by the key path,
 * with rest of the key path.<br/>
 * If the first component starts with "@", the first component includes the key
 * of the computational key component and as the form "@function.key".
 * If there is only one key component, this method invokes 
 * [NSObject-valueForKey:] in the receiver with that component.
 * Unlike the reference implementation GDL2 allows you to continue the keyPath
 * in a meaningful way after @count but the path must then contain a key as
 * the computational key structure implies.
 * (i.e. you may use "@count.self.decimalValue") The actual key "self" is
 * in fact ignored during the computation, but the formal structure must be
 * maintained.<br/>
 * It should be mentioned that the reference implementation
 * would return the result of "@count" independent
 * of any additional key paths, even if they were meaningless like
 * "@count.bla.strange".  GDL2 will raise, if the object returned by
 * valueForKey:@"count.bla" (which generally is an NSDecimalNumber) raises on
 * valueForKey:@"strange".
 */
- (id)valueForKeyPath: (NSString *)keyPath
{
  NSRange   r;
  id        result;

  EOFLOGObjectFnStartCond(@"EOKVC");
  r = [keyPath rangeOfString: @"."];
  if ([keyPath hasPrefix: @"@"] == YES
      && [keyPath isEqualToString: @"@count"] == NO
      && r.location != NSNotFound)
    {
      NSRange rr;
      unsigned length;

      length = [keyPath length];

      rr.location = NSMaxRange(r);
      rr.length   = length - rr.location;
      r = [keyPath rangeOfString: @"." 
		   options: 0
		   range: rr];
    }
    
  if (r.length == 0)
    {
      result = [self valueForKey: keyPath];
    }
  else
    {
      NSString *key  = [keyPath substringToIndex: r.location];
      NSString *path = [keyPath substringFromIndex: NSMaxRange(r)];

      result = [[self valueForKey: key] valueForKeyPath: path];
    }

  EOFLOGObjectFnStopCond(@"EOKVC");
  return result;
}

/**
 * Iterates over the objects of the receiver send each object valueForKey:
 * with the parameter.  The decimalValue of the returned object is accumalted.
 * An empty array returns NSDecimalNumber 0.
 */
- (id)computeSumForKey: (NSString *)key
{
  NSDecimalNumber *ret=nil;
  NSDecimal        result, left, right;
  NSRoundingMode   mode;
  unsigned int     count;

  INITIALIZE;

  EOFLOGObjectFnStartCond(@"EOKVC");

  mode = [[NSDecimalNumber defaultBehavior] roundingMode];
  count = [self count];
  NSDecimalFromComponents(&result, 0, 0, NO);

  if (count>0)
    {
      unsigned int i=0;
      IMP oaiIMP = [self methodForSelector: @selector(objectAtIndex:)];
      for (i=0; i<count; i++)
        {
          left = result;
          right = [[GDL2_ObjectAtIndexWithImp(self,oaiIMP,i) valueForKey: key] decimalValue];
          NSDecimalAdd(&result, &left, &right, mode);
        }
    };
        
  ret = [NSDecimalNumber decimalNumberWithDecimal: result];
  EOFLOGObjectFnStopCond(@"EOKVC");
  return ret;
}

/**
 * Iterates over the objects of the receiver send each object valueForKey:
 * with the parameter.  The decimalValue of the returned object is accumalted
 * and then divided by number of objects contained by the receiver as returned
 * by <code>NSArray count</code>.  An empty array returns NSDecimalNumber 0.
 */
- (id)computeAvgForKey: (NSString *)key
{
  NSDecimalNumber *ret = nil;
  NSDecimal        result, left, right;
  NSRoundingMode   mode;
  unsigned int     count = 0;

  INITIALIZE;

  EOFLOGObjectFnStartCond(@"EOKVC");
  mode = [[NSDecimalNumber defaultBehavior] roundingMode];
  count = [self count];
  NSDecimalFromComponents(&result, 0, 0, NO);

  if (count>0)
    {
      unsigned int i=0;
      IMP oaiIMP = [self methodForSelector: @selector(objectAtIndex:)];
      
      for (i=0; i<count; i++)
        {
          left = result;
          right = [[GDL2_ObjectAtIndexWithImp(self,oaiIMP,i) valueForKey: key] decimalValue];
          NSDecimalAdd(&result, &left, &right, mode);
        }
    }
  else
    {
      return [NSDecimalNumber zero];
    }

  left  = result;
  NSDecimalFromComponents(&right, (unsigned long long) count, 0, NO);

  NSDecimalDivide(&result, &left, &right, mode);
        
  ret = [NSDecimalNumber decimalNumberWithDecimal: result];
  EOFLOGObjectFnStopCond(@"EOKVC");
  return ret;
}

- (id)computeCountForKey: (NSString *)key
{
  id result;

  EOFLOGObjectFnStartCond(@"EOKVC");
  result = [NSDecimalNumber numberWithUnsignedInt: [self count]];

  EOFLOGObjectFnStopCond(@"EOKVC");
  return result;
}

- (id)computeMaxForKey: (NSString *)key
{
  id result=nil;
  id resultVal=nil;
  unsigned int count=0;

  INITIALIZE;

  EOFLOGObjectFnStartCond(@"EOKVC");
  count     = [self count];

  if (count > 0)
    {
      unsigned int i=0;
      id           current = nil;
      id	   currentVal = nil;
      IMP          oaiIMP = [self methodForSelector: @selector(objectAtIndex:)];

      for(i=0; i<count && (resultVal == nil || resultVal == GDL2_EONull); i++)
	{
	  result    = GDL2_ObjectAtIndexWithImp(self,oaiIMP,i);
	  resultVal = [result valueForKey: key];
	}          
      for (; i<count; i++)
	{
	  current    = GDL2_ObjectAtIndexWithImp(self,oaiIMP,i);
	  currentVal = [current valueForKey: key];

	  if (currentVal == nil || currentVal == GDL2_EONull)
            continue;
	  
	  if ([(NSObject *)resultVal compare: currentVal] == NSOrderedAscending)
	    {
	      result    = current;
	      resultVal = currentVal;
	    }
	}
    }

  EOFLOGObjectFnStopCond(@"EOKVC");
  return result;
}

- (id)computeMinForKey: (NSString *)key
{
  id result=nil;
  id resultVal=nil;
  unsigned int   count = 0;

  INITIALIZE;

  EOFLOGObjectFnStartCond(@"EOKVC");
  count     = [self count];

  if (count > 0)
    {
      id current=nil;
      id currentVal=nil;
      unsigned int i = 0;
      IMP oaiIMP = [self methodForSelector: @selector(objectAtIndex:)];

      for(i=0; i<count && (resultVal == nil || resultVal == GDL2_EONull); i++)
	{
	  result    = GDL2_ObjectAtIndexWithImp(self,oaiIMP,i);
	  resultVal = [result valueForKey: key];
	}          
      for (; i<count; i++)
	{
	  current    = GDL2_ObjectAtIndexWithImp(self,oaiIMP,i);
	  currentVal = [current valueForKey: key];

	  if (currentVal == nil || currentVal == GDL2_EONull) continue;

	  if ([(NSObject *)resultVal compare: currentVal] == NSOrderedDescending)
	    {
	      result    = current;
	      resultVal = currentVal;
	    }
	}
    }

  EOFLOGObjectFnStopCond(@"EOKVC");
  return result;
}

@end


@implementation NSDictionary (EOKeyValueCoding)

- (void)GDL2KVCNSDictionaryICategoryID
{
}

+ (void)load
{
  GDL2_ActivateCategory("NSDictionary",
			@selector(GDL2KVCNSDictionaryICategoryID), YES);
}

/**
 * Returns the object stored in the dictionary for this key.
 * Unlike Foundation, this method may return objects for keys other than
 * those explicitly stored in the receiver.  These special keys are
 * 'count', 'allKeys' and 'allValues'.
 * We override the implementation to account for these
 * special keys.
 */
- (id)valueForKey: (NSString *)key
{
  id value;

  EOFLOGObjectFnStartCond(@"EOKVC");
  //EOFLOGObjectLevelArgs(@"EOKVC", @"key=%@",
  //                      key);

  value = [self objectForKey: key];

  if (!value)
    {
      if ([key isEqualToString: @"allValues"])
	{
#ifndef GNUSTEP
          static BOOL warnedValuesKeys = NO;
          if (warnedValuesKeys == NO)
            {
              warnedValuesKeys = YES;
              NSWarnMLog(@"Foundation does not return a value for the special 'allValues' key", "");
            }
#endif
	  value = [self allValues];
	}
      else if ([key isEqualToString: @"allKeys"])
	{
#ifndef GNUSTEP
          static BOOL warnedAllKeys = NO;
          if (warnedAllKeys == NO)
            {
              warnedAllKeys = YES;
              NSWarnMLog(@"Foundation does not return a value for the special 'allKeys' key", "");
            }
#endif
	  value = [self allKeys];
	}
      else if ([key isEqualToString: @"count"])
	{
#ifndef GNUSTEP
          static BOOL warnedCount = NO;
          if (warnedCount == NO)
            {
              warnedCount = YES;
              NSWarnMLog(@"Foundation does not return a value for the special 'count' key", "");
            }
#endif
	  value = [NSNumber numberWithUnsignedInt: [self count]];
	}
    }

  //EOFLOGObjectLevelArgs(@"EOKVC", @"key=%@ value: %p (class=%@)",
  //                      key, value, [value class]);
  EOFLOGObjectFnStopCond(@"EOKVC");

  return value;
}

/**
 * Returns the object stored in the dictionary for this key.
 * Unlike Foundation, this method may return objects for keys other than
 * those explicitly stored in the receiver.  These special keys are
 * 'count', 'allKeys' and 'allValues'.
 * We do not simply invoke [NSDictionary-valueForKey:]
 * to avoid recursions in subclasses that might implement
 * [NSDictionary-valueForKey:] by calling [NSDictionary-storedValueForKey:]
 */
- (id)storedValueForKey: (NSString *)key
{
  id value;

  EOFLOGObjectFnStartCond(@"EOKVC");
  //EOFLOGObjectLevelArgs(@"EOKVC", @"key=%@",
  //                      key);

  value = [self objectForKey: key];

  if (!value)
    {
      if ([key isEqualToString: @"allValues"])
	{
	  value = [self allValues];
	}
      else if ([key isEqualToString: @"allKeys"])
	{
	  value = [self allKeys];
	}
      else if ([key isEqualToString: @"count"])
	{
	  value = [NSNumber numberWithUnsignedInt: [self count]];
	}
    }

  //EOFLOGObjectLevelArgs(@"EOKVC", @"key=%@ value: %p (class=%@)",
  //                      key, value, [value class]);
  EOFLOGObjectFnStopCond(@"EOKVC");

  return value;
}

/**
 * First checks whether the entire keyPath is contained as a key
 * in the receiver before invoking super's implementation.
 * (The special quoted key handling will probably be moved
 * to a GSWDictionary subclass to be used by GSWDisplayGroup.)
 */
- (id)valueForKeyPath: (NSString*)keyPath
{
  id  value = nil;

  INITIALIZE;

  EOFLOGObjectFnStartCond(@"EOKVC");
  //EOFLOGObjectLevelArgs(@"EOKVC", @"keyPath=\"%@\"",
  //                      keyPath);

  if ([keyPath hasPrefix: @"'"] && strictWO == NO) //user defined composed key 
    {
      NSMutableArray *keyPathArray = [[[[keyPath stringByDeletingPrefix: @"'"]
					 componentsSeparatedByString: @"."]
					mutableCopy] autorelease];
      NSMutableString *key = [NSMutableString string];

      //EOFLOGObjectLevelArgs(@"EOKVC", @"keyPathArray=%@", keyPathArray);

      while ([keyPathArray count] > 0)
        {
          id tmpKey;

          //EOFLOGObjectLevelArgs(@"EOKVC", @"keyPathArray=%@", keyPathArray);

          tmpKey = [keyPathArray objectAtIndex: 0];
          //EOFLOGObjectLevelArgs(@"EOKVC", @"tmpKey=%@", tmpKey);

          [keyPathArray removeObjectAtIndex: 0];

          if ([key length] > 0)
            [key appendString: @"."];
          if ([tmpKey hasSuffix: @"'"])
            {
              tmpKey = [tmpKey stringByDeletingSuffix: @"'"];
              [key appendString: tmpKey];
              break;
            }
          else
	    [key appendString: tmpKey];

          //EOFLOGObjectLevelArgs(@"EOKVC", @"key=%@", key);
        }

      //EOFLOGObjectLevelArgs(@"EOKVC", @"key=%@", key);

      value = [self valueForKey: key];

      //EOFLOGObjectLevelArgs(@"EOKVC",@"key=%@ tmpValue: %p (class=%@)",
      //             key,value,[value class]);

      if (value && [keyPathArray count] > 0)
        {
          NSString *rightKeyPath = [keyPathArray
				     componentsJoinedByString: @"."];

          //EOFLOGObjectLevelArgs(@"EOKVC", @"rightKeyPath=%@",
          //                      rightKeyPath);

          value = [value valueForKeyPath: rightKeyPath];
        }
    }
  else
    {
      /*
       * Return super valueForKeyPath: only 
       * if there's no object for entire key keyPath
       */
      value = [self objectForKey: keyPath];

      EOFLOGObjectLevelArgs(@"EOKVC",@"keyPath=%@ tmpValue: %p (class=%@)",
                   keyPath,value,[value class]);

      if (!value)
        value = [super valueForKeyPath: keyPath];
    }

  //EOFLOGObjectLevelArgs(@"EOKVC",@"keyPath=%@ value: %p (class=%@)",
  //             keyPath,value,[value class]);
  EOFLOGObjectFnStopCond(@"EOKVC");

  return value;
}

/**
 * First checks whether the entire keyPath is contained as a key
 * in the receiver before invoking super's implementation.
 * (The special quoted key handling will probably be moved
 * to a GSWDictionary subclass to be used by GSWDisplayGroup.)
 */
- (id)storedValueForKeyPath: (NSString*)keyPath
{
  id value = nil;

  INITIALIZE;

  EOFLOGObjectFnStartCond(@"EOKVC");
  //EOFLOGObjectLevelArgs(@"EOKVC",@"keyPath=\"%@\"",
  //                      keyPath);

  if ([keyPath hasPrefix: @"'"] && strictWO == NO) //user defined composed key 
    {
      NSMutableArray *keyPathArray = [[[[keyPath stringByDeletingPrefix: @"'"]
					 componentsSeparatedByString: @"."]
					mutableCopy] autorelease];
      NSMutableString *key = [NSMutableString string];

      //EOFLOGObjectLevelArgs(@"EOKVC", @"keyPathArray=%@", keyPathArray);

      while ([keyPathArray count] > 0)
        {
          id tmpKey;

          //EOFLOGObjectLevelArgs(@"EOKVC", @"keyPathArray=%@", keyPathArray);

          tmpKey = [keyPathArray objectAtIndex: 0];
          //EOFLOGObjectLevelArgs(@"EOKVC", @"tmpKey=%@", tmpKey);

          [keyPathArray removeObjectAtIndex: 0];

          if ([key length] > 0)
            [key appendString: @"."];
          if ([tmpKey hasSuffix: @"'"])
            {
              tmpKey = [tmpKey stringByDeletingSuffix: @"'"];
              [key appendString: tmpKey];
              break;
            }
          else
	    [key appendString: tmpKey];

          //EOFLOGObjectLevelArgs(@"EOKVC", @"key=%@", key);
        }

      //EOFLOGObjectLevelArgs(@"EOKVC", @"key=%@", key);

      value = [self storedValueForKey: key];

      //EOFLOGObjectLevelArgs(@"EOKVC",@"key=%@ tmpValue: %p (class=%@)",
      //             key,value,[value class]);

      if (value && [keyPathArray count] > 0)
        {
          NSString *rightKeyPath = [keyPathArray
				     componentsJoinedByString: @"."];

          EOFLOGObjectLevelArgs(@"EOKVC", @"rightKeyPath=%@",
				rightKeyPath);

          value = [value storedValueForKeyPath: rightKeyPath];
        }
    }
  else
    {
      /*
       * Return super valueForKeyPath: only 
       * if there's no object for entire key keyPath
       */
      value = [self objectForKey: keyPath];

      //EOFLOGObjectLevelArgs(@"EOKVC",@"keyPath=%@ tmpValue: %p (class=%@)",
      //             keyPath,value,[value class]);

      if (!value)
        value = [super storedValueForKeyPath: keyPath];
    }

  //EOFLOGObjectLevelArgs(@"EOKVC",@"keyPath=%@ value: %p (class=%@)",
  //             keyPath,value,[value class]);
  EOFLOGObjectFnStopCond(@"EOKVC");

  return value;
}

@end


@interface NSMutableDictionary(EOKeyValueCodingPrivate)
- (void)takeValue: (id)value
       forKeyPath: (NSString *)keyPath
          isSmart: (BOOL)smartFlag;
@end

@implementation NSMutableDictionary (EOKVCGNUstepExtensions)

- (void)GDL2KVCNSMutableDictionaryICategoryID
{
}

+ (void)load
{
  GDL2_ActivateCategory("NSMutableDictionary",
			@selector(GDL2KVCNSMutableDictionaryICategoryID), YES);
}

/**
 * Method to augment the NSKeyValueCoding implementation
 * to account for added functionality such as quoted key paths.
 * (The special quoted key handling will probably be moved
 * to a GSWDictionary subclass to be used by GSWDisplayGroup.
 * this method then becomes obsolete.)
 */
- (void)smartTakeValue: (id)value 
            forKeyPath: (NSString*)keyPath
{
  [self takeValue:value
        forKeyPath:keyPath
        isSmart:YES];
}

/**
 * Overrides gnustep-base and Foundations implementation
 * to account for added functionality such as quoted key paths.
 * (The special quoted key handling will probably be moved
 * to a GSWDictionary subclass to be used by GSWDisplayGroup.
 * this method then becomes obsolete.)
 */
- (void)takeValue: (id)value
       forKeyPath: (NSString *)keyPath
{
  [self takeValue:value
        forKeyPath:keyPath
        isSmart:NO];
}

/**
 * Support method to augment the NSKeyValueCoding implementation
 * to account for added functionality such as quoted key paths.
 * (The special quoted key handling will probably be moved
 * to a GSWDictionary subclass to be used by GSWDisplayGroup.
 * this method then becomes obsolete.)
 */
- (void)takeValue: (id)value
       forKeyPath: (NSString *)keyPath
          isSmart: (BOOL)smartFlag
{
  EOFLOGObjectFnStartCond(@"EOKVC");
  //EOFLOGObjectLevelArgs(@"EOKVC", @"keyPath=\"%@\"",
  //                      keyPath);

  INITIALIZE;

  if ([keyPath hasPrefix: @"'"] && strictWO == NO) //user defined composed key 
    {
      NSMutableArray *keyPathArray = [[[[keyPath stringByDeletingPrefix: @"'"]
					 componentsSeparatedByString: @"."]
					mutableCopy] autorelease];
      NSMutableString *key = [NSMutableString string];

      unsigned keyPathArrayCount = [keyPathArray count];

      //EOFLOGObjectLevelArgs(@"EOKVC", @"keyPathArray=%@", keyPathArray);

      while (keyPathArrayCount > 0)
        {
          id tmpKey;

          //EOFLOGObjectLevelArgs(@"EOKVC", @"keyPathArray=%@", keyPathArray);

          tmpKey = RETAIN([keyPathArray objectAtIndex: 0]);
          //EOFLOGObjectLevelArgs(@"EOKVC", @"tmpKey=%@", tmpKey);

          [keyPathArray removeObjectAtIndex: 0];
          keyPathArrayCount--;

          if ([key length] > 0)
            [key appendString: @"."];
          if ([tmpKey hasSuffix: @"'"])
            {
              ASSIGN(tmpKey, [tmpKey stringByDeletingSuffix: @"'"]);
              [key appendString: tmpKey];
              break;
            }
          else
	    [key appendString: tmpKey];

          RELEASE(tmpKey);

          //EOFLOGObjectLevelArgs(@"EOKVC", @"key=%@", key);
        }

      //EOFLOGObjectLevelArgs(@"EOKVC",@"key=%@",key);
      //EOFLOGObjectLevelArgs(@"EOKVC",@"left keyPathArray=\"%@\"",
      //             keyPathArray);

      if (keyPathArrayCount > 0)
        {
          id obj = [self objectForKey: key];

          if (obj)
            {
              NSString *rightKeyPath = [keyPathArray
					 componentsJoinedByString: @"."];

              //EOFLOGObjectLevelArgs(@"EOKVC",@"rightKeyPath=\"%@\"",
              //             rightKeyPath);

              if (smartFlag)
                [obj smartTakeValue: value
		     forKeyPath: rightKeyPath];
              else
                [obj takeValue: value
		     forKeyPath: rightKeyPath];
            }
        }
      else
        {
          if (value)
            [self setObject: value 
                  forKey: key];
          else
            [self removeObjectForKey: key];
        }
    }
  else
    {
      if (value == nil)
	{
	  [self removeObjectForKey: keyPath];
	}
      else
	{
	  [self setObject: value forKey: keyPath];
	}
     }

  EOFLOGObjectFnStopCond(@"EOKVC");
}

/**
 * Calls [NSMutableDictionary-setObject:forKey:] using the full keyPath
 * as a key, if the value is non nil.  Otherwise calls
 * [NSDictionary-removeObjectForKey:] with the full keyPath.
 * (The special quoted key handling will probably be moved
 * to a GSWDictionary subclass to be used by GSWDisplayGroup.)
 */
- (void)takeStoredValue: (id)value 
             forKeyPath: (NSString *)keyPath
{
  EOFLOGObjectFnStartCond(@"EOKVC");
  //EOFLOGObjectLevelArgs(@"EOKVC",@"keyPath=\"%@\"",
  //             keyPath);

  if ([keyPath hasPrefix: @"'"]) //user defined composed key 
    {
      NSMutableArray *keyPathArray = [[[[keyPath stringByDeletingPrefix: @"'"]
					 componentsSeparatedByString: @"."]
					mutableCopy] autorelease];
      NSMutableString *key = [NSMutableString string];

      int keyPathArrayCount=[keyPathArray count];

      //EOFLOGObjectLevelArgs(@"EOKVC", @"keyPathArray=%@", keyPathArray);

      while (keyPathArrayCount > 0)
        {
          id tmpKey;

          //EOFLOGObjectLevelArgs(@"EOKVC", @"keyPathArray=%@", keyPathArray);

          tmpKey = [keyPathArray objectAtIndex: 0];
          //EOFLOGObjectLevelArgs(@"EOKVC", @"tmpKey=%@", tmpKey);

          [keyPathArray removeObjectAtIndex: 0];
          keyPathArrayCount--;

          if ([key length] > 0)
            [key appendString: @"."];

          if ([tmpKey hasSuffix: @"'"])
            {
              tmpKey = [tmpKey stringByDeletingSuffix: @"'"];
              [key appendString: tmpKey];
              break;
            }
          else
	    [key appendString: tmpKey];

          //EOFLOGObjectLevelArgs(@"EOKVC", @"key=%@", key);
        }

      //EOFLOGObjectLevelArgs(@"EOKVC", @"key=%@", key);
      //EOFLOGObjectLevelArgs(@"EOKVC",@"left keyPathArray=\"%@\"",
      //             keyPathArray);

      if (keyPathArrayCount > 0)
        {
          id obj = [self objectForKey: key];

          if (obj)
            {
              NSString *rightKeyPath = [keyPathArray
					 componentsJoinedByString: @"."];

              //EOFLOGObjectLevelArgs(@"EOKVC",@"rightKeyPath=\"%@\"",
              //             rightKeyPath);

              [obj  takeStoredValue: value
                    forKeyPath: rightKeyPath];
            }
        }
      else
        {
          if (value)
            [self setObject: value 
                  forKey: key];
          else
            [self removeObjectForKey: key];
        }
    }
  else
    {
      if (value)
        [self setObject: value 
              forKey: keyPath];
      else
        [self removeObjectForKey: keyPath];
    }

  EOFLOGObjectFnStopCond(@"EOKVC");
}

@end

@implementation NSObject (EOKVCGNUstepExtensions)

/**
 * This is a GDL2 extension.  This convenience method iterates over
 * the supplied keyPaths and determines the corresponding values by invoking
 * valueForKeyPath: on the receiver.  The results are returned an NSDictionary
 * with the keyPaths as keys and the returned values as the dictionary's
 * values.  If valueForKeyPath: returns nil, it is replaced by the shared
 * EONull instance.
 */
- (NSDictionary *)valuesForKeyPaths: (NSArray *)keyPaths
{
  NSDictionary *values = nil;
  int i;
  int n;
  NSMutableArray *newKeyPaths;
  NSMutableArray *newVals;

  INITIALIZE;

  EOFLOGObjectFnStartCond(@"EOKVC");

  n = [keyPaths count];
  newKeyPaths = AUTORELEASE([[NSMutableArray alloc] initWithCapacity: n]);
  newVals = AUTORELEASE([[NSMutableArray alloc] initWithCapacity: n]);

  for (i = 0; i < n; i++)
    {
      id keyPath = [keyPaths objectAtIndex: i];
      id val = nil;

      NS_DURING //DEBUG Only ?
        {
          val = [self valueForKeyPath: keyPath];
        }
      NS_HANDLER
        {
          NSLog(@"KVC:%@ EXCEPTION %@",
		NSStringFromSelector(_cmd), localException);
          NSDebugMLog(@"KVC:%@ EXCEPTION %@",
		NSStringFromSelector(_cmd), localException);
          [localException raise];
        }
      NS_ENDHANDLER;

      if (val == nil)
	{
	  val = GDL2_EONull;
	}

      [newKeyPaths addObject: keyPath];
      [newVals addObject: val];
    }
  
  values = [NSDictionary dictionaryWithObjects: newVals
			 forKeys: newKeyPaths];

  EOFLOGObjectFnStopCond(@"EOKVC");

  return values;
}

/**
 * This is a GDL2 extension.  This convenience method retrieves the object
 * obtained by invoking valueForKey: on each path component until the one
 * next to the last.  It then invokes takeStoredValue:forKey: on that object
 * with the last path component as the key.
 */
- (void)takeStoredValue: value 
             forKeyPath: (NSString *)key
{
  NSArray *pathArray;
  NSString *path;
  id obj = self;
  int i, count;

  EOFLOGObjectFnStartCond(@"EOKVC");

  pathArray = [key componentsSeparatedByString:@"."];
  count = [pathArray count];

  for (i = 0; i < (count - 1); i++)
    {
      path = [pathArray objectAtIndex: i];
      obj = [obj valueForKey: path];
    }

  path = [pathArray lastObject];
  [obj takeStoredValue: value forKey: path];

  EOFLOGObjectFnStopCond(@"EOKVC");
}

/**
 * This is a GDL2 extension.  This convenience method retrieves the object
 * obtained by invoking valueForKey: on each path component until the one
 * next to the last.  It then invokes storedValue:forKey: on that object
 * with the last path component as the key, returning the result.
 */
- (id)storedValueForKeyPath: (NSString *)key
{
  NSArray *pathArray = nil;
  NSString *path;
  id obj = self;
  int i, count;
  EOFLOGObjectFnStartCond(@"EOKVC");
  pathArray = [key componentsSeparatedByString:@"."];
  count = [pathArray count];

  for(i=0; i < (count-1); i++)
    {
      path = [pathArray objectAtIndex:i];
      obj = [obj valueForKey:path];
    }

  path = [pathArray lastObject];
  obj=[obj storedValueForKey:path];
  EOFLOGObjectFnStopCond(@"EOKVC");
  return obj;
}

/**
 * This is a GDL2 extension.  This convenience method iterates over
 * the supplied keyPaths and determines the corresponding values by invoking
 * storedValueForKeyPath: on the receiver.  The results are returned an
 * NSDictionary with the keyPaths as keys and the returned values as the
 * dictionary's values.  If storedValueForKeyPath: returns nil, it is replaced
 * by the shared EONull instance.
 */
- (NSDictionary *)storedValuesForKeyPaths: (NSArray *)keyPaths
{
  NSDictionary *values = nil;
  int i, n;
  NSMutableArray *newKeyPaths = nil;
  NSMutableArray *newVals = nil;

  INITIALIZE;

  EOFLOGObjectFnStartCond(@"EOKVC");

  n = [keyPaths count];

  newKeyPaths = [[[NSMutableArray alloc] initWithCapacity: n] 
			      autorelease];
  newVals = [[[NSMutableArray alloc] initWithCapacity: n] 
			      autorelease];

  for (i = 0; i < n; i++)
    {
      id keyPath = [keyPaths objectAtIndex: i];
      id val = nil;

      NS_DURING //DEBUG Only ?
        {
          val = [self storedValueForKeyPath: keyPath];
        }
      NS_HANDLER
        {
          NSLog(@"EXCEPTION %@", localException);
          NSDebugMLog(@"EXCEPTION %@", localException);              
          [localException raise];
        }
      NS_ENDHANDLER;
        
      if (val == nil)
	val = GDL2_EONull;
      
      [newKeyPaths addObject: keyPath];
      [newVals addObject: val];
    }
  
  values = [NSDictionary dictionaryWithObjects: newVals
			 forKeys: newKeyPaths];
  EOFLOGObjectFnStopCond(@"EOKVC");

  return values;
}

/**
 * This is a GDL2 extension.  Simply invokes takeValue:forKey:.
 * This method provides a hook for EOGenericRecords KVC implementation,
 * which takes relationship definitions into account.
 */
- (void)smartTakeValue: (id)anObject 
                forKey: (NSString *)aKey
{
  [self takeValue: anObject
        forKey: aKey];
}

/**
 * This is a GDL2 extension.  This convenience method invokes
 * smartTakeValue:forKeyPath on the object returned by valueForKey: with
 * the first path component. 
 * obtained by invoking valueForKey: on each path component until the one
 * next to the last.  It then invokes storedValue:forKey: on that object
 * with the last path component as the key, returning the result.
 */
- (void)smartTakeValue: (id)anObject 
            forKeyPath: (NSString *)aKeyPath
{
  NSRange r = [aKeyPath rangeOfString: @"."];

  if (r.length == 0)
    {
      [self smartTakeValue: anObject 
            forKey: aKeyPath];
    }
  else
    {
      NSString *key = [aKeyPath substringToIndex: r.location];
      NSString *path = [aKeyPath substringFromIndex: NSMaxRange(r)];

      [[self valueForKey: key] smartTakeValue: anObject 
                               forKeyPath: path];
    }
}


@end