-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathKeyValues.cpp
More file actions
2157 lines (1838 loc) · 51.9 KB
/
KeyValues.cpp
File metadata and controls
2157 lines (1838 loc) · 51.9 KB
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
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#ifdef _XBOX
#include "xbox/xbox_platform.h"
#include "xbox/xbox_win32stubs.h"
#endif
#if defined(_WIN32) && !defined(_XBOX)
#include <windows.h> // for WideCharToMultiByte and MultiByteToWideChar
#elif defined(_LINUX)
#include <wchar.h> // wcslen()
#define _alloca alloca
#endif
#include <KeyValues.h>
#include "filesystem.h"
#include <vstdlib/IKeyValuesSystem.h>
#include <Color.h>
#include <stdlib.h>
#include "tier0/dbg.h"
#include "tier0/mem.h"
#include "utlvector.h"
#include "utlbuffer.h"
// memdbgon must be the last include file in a .cpp file!!!
#include <tier0/memdbgon.h>
static char * s_LastFileLoadingFrom = "unknown"; // just needed for error messages
#define KEYVALUES_TOKEN_SIZE 1024
static char s_pTokenBuf[KEYVALUES_TOKEN_SIZE];
#define INTERNALWRITE( pData, len ) InternalWrite( filesystem, f, pBuf, pData, len )
// a simple class to keep track of a stack of valid parsed symbols
const int MAX_ERROR_STACK = 64;
class CKeyValuesErrorStack
{
public:
CKeyValuesErrorStack() : m_pFilename("NULL"), m_errorIndex(0), m_maxErrorIndex(0) {}
void SetFilename( const char *pFilename )
{
m_pFilename = pFilename;
m_maxErrorIndex = 0;
}
// entering a new keyvalues block, save state for errors
// Not save symbols instead of pointers because the pointers can move!
int Push( int symName )
{
if ( m_errorIndex < MAX_ERROR_STACK )
{
m_errorStack[m_errorIndex] = symName;
}
m_errorIndex++;
m_maxErrorIndex = max( m_maxErrorIndex, (m_errorIndex-1) );
return m_errorIndex-1;
}
// exiting block, error isn't in this block, remove.
void Pop()
{
m_errorIndex--;
Assert(m_errorIndex>=0);
}
// Allows you to keep the same stack level, but change the name as you parse peers
void Reset( int stackLevel, int symName )
{
Assert( stackLevel >= 0 && stackLevel < m_errorIndex );
m_errorStack[stackLevel] = symName;
}
// Hit an error, report it and the parsing stack for context
void ReportError( const char *pError )
{
DevMsg( 1, "KeyValues Error: %s in file %s\n", pError, m_pFilename );
for ( int i = 0; i < m_maxErrorIndex; i++ )
{
if ( m_errorStack[i] != INVALID_KEY_SYMBOL )
{
if ( i < m_errorIndex )
{
DevMsg( 1, "%s, ", KeyValuesSystem()->GetStringForSymbol(m_errorStack[i]) );
}
else
{
DevMsg( 1, "(*%s*), ", KeyValuesSystem()->GetStringForSymbol(m_errorStack[i]) );
}
}
}
DevMsg( 1, "\n" );
}
private:
int m_errorStack[MAX_ERROR_STACK];
const char *m_pFilename;
int m_errorIndex;
int m_maxErrorIndex;
} g_KeyValuesErrorStack;
// a simple helper that creates stack entries as it goes in & out of scope
class CKeyErrorContext
{
public:
CKeyErrorContext( KeyValues *pKv )
{
Init( pKv->GetNameSymbol() );
}
~CKeyErrorContext()
{
g_KeyValuesErrorStack.Pop();
}
CKeyErrorContext( int symName )
{
Init( symName );
}
void Reset( int symName )
{
g_KeyValuesErrorStack.Reset( m_stackLevel, symName );
}
private:
void Init( int symName )
{
m_stackLevel = g_KeyValuesErrorStack.Push( symName );
}
int m_stackLevel;
};
// Uncomment this line to hit the ~CLeakTrack assert to see what's looking like it's leaking
// #define LEAKTRACK
#ifdef LEAKTRACK
class CLeakTrack
{
public:
CLeakTrack()
{
}
~CLeakTrack()
{
if ( keys.Count() != 0 )
{
Assert( 0 );
}
}
struct kve
{
KeyValues *kv;
char name[ 256 ];
};
void AddKv( KeyValues *kv, char const *name )
{
kve k;
Q_strncpy( k.name, name ? name : "NULL", sizeof( k.name ) );
k.kv = kv;
keys.AddToTail( k );
}
void RemoveKv( KeyValues *kv )
{
int c = keys.Count();
for ( int i = 0; i < c; i++ )
{
if ( keys[i].kv == kv )
{
keys.Remove( i );
break;
}
}
}
CUtlVector< kve > keys;
};
static CLeakTrack track;
#define TRACK_KV_ADD( ptr, name ) track.AddKv( ptr, name )
#define TRACK_KV_REMOVE( ptr ) track.RemoveKv( ptr )
#else
#define TRACK_KV_ADD( ptr, name )
#define TRACK_KV_REMOVE( ptr )
#endif
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
KeyValues::KeyValues( const char *setName )
{
TRACK_KV_ADD( this, setName );
Init();
SetName ( setName );
}
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
KeyValues::KeyValues( const char *setName, const char *firstKey, const char *firstValue )
{
TRACK_KV_ADD( this, setName );
Init();
SetName( setName );
SetString( firstKey, firstValue );
}
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
KeyValues::KeyValues( const char *setName, const char *firstKey, const wchar_t *firstValue )
{
TRACK_KV_ADD( this, setName );
Init();
SetName( setName );
SetWString( firstKey, firstValue );
}
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
KeyValues::KeyValues( const char *setName, const char *firstKey, int firstValue )
{
TRACK_KV_ADD( this, setName );
Init();
SetName( setName );
SetInt( firstKey, firstValue );
}
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
KeyValues::KeyValues( const char *setName, const char *firstKey, const char *firstValue, const char *secondKey, const char *secondValue )
{
TRACK_KV_ADD( this, setName );
Init();
SetName( setName );
SetString( firstKey, firstValue );
SetString( secondKey, secondValue );
}
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
KeyValues::KeyValues( const char *setName, const char *firstKey, int firstValue, const char *secondKey, int secondValue )
{
TRACK_KV_ADD( this, setName );
Init();
SetName( setName );
SetInt( firstKey, firstValue );
SetInt( secondKey, secondValue );
}
//-----------------------------------------------------------------------------
// Purpose: Initialize member variables
//-----------------------------------------------------------------------------
void KeyValues::Init()
{
m_iKeyName = INVALID_KEY_SYMBOL;
m_iDataType = TYPE_NONE;
m_pSub = NULL;
m_pPeer = NULL;
m_pChain = NULL;
m_sValue = NULL;
m_wsValue = NULL;
m_pValue = NULL;
m_bHasEscapeSequences = false;
// Needed for backward compatibility
memset( reserved, 0, sizeof(reserved) );
}
//-----------------------------------------------------------------------------
// Purpose: Destructor
//-----------------------------------------------------------------------------
KeyValues::~KeyValues()
{
TRACK_KV_REMOVE( this );
RemoveEverything();
}
//-----------------------------------------------------------------------------
// Purpose: remove everything
//-----------------------------------------------------------------------------
void KeyValues::RemoveEverything()
{
KeyValues *dat;
KeyValues *datNext = NULL;
for ( dat = m_pSub; dat != NULL; dat = datNext )
{
datNext = dat->m_pPeer;
dat->m_pPeer = NULL;
delete dat;
}
for ( dat = m_pPeer; dat && dat != this; dat = datNext )
{
datNext = dat->m_pPeer;
dat->m_pPeer = NULL;
delete dat;
}
delete [] m_sValue;
m_sValue = NULL;
delete [] m_wsValue;
m_wsValue = NULL;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *f -
//-----------------------------------------------------------------------------
void KeyValues::RecursiveSaveToFile( CUtlBuffer& buf, int indentLevel )
{
RecursiveSaveToFile( NULL, FILESYSTEM_INVALID_HANDLE, &buf, indentLevel );
}
//-----------------------------------------------------------------------------
// Adds a chain... if we don't find stuff in this keyvalue, we'll look
// in the one we're chained to.
//-----------------------------------------------------------------------------
void KeyValues::ChainKeyValue( KeyValues* pChain )
{
m_pChain = pChain;
}
//-----------------------------------------------------------------------------
// Purpose: Get the name of the current key section
//-----------------------------------------------------------------------------
const char *KeyValues::GetName( void ) const
{
return KeyValuesSystem()->GetStringForSymbol(m_iKeyName);
}
//-----------------------------------------------------------------------------
// Purpose: Get the symbol name of the current key section
//-----------------------------------------------------------------------------
int KeyValues::GetNameSymbol() const
{
return m_iKeyName;
}
//-----------------------------------------------------------------------------
// Purpose: Read a single token from buffer (0 terminated)
//-----------------------------------------------------------------------------
#pragma warning (disable:4706)
const char *KeyValues::ReadToken( CUtlBuffer &buf, bool &wasQuoted )
{
wasQuoted = false;
if ( !buf.IsValid() )
return NULL;
// eating white spaces and remarks loop
while ( true )
{
buf.EatWhiteSpace();
if ( !buf.IsValid() )
return NULL; // file ends after reading whitespaces
// stop if it's not a comment; a new token starts here
if ( !buf.EatCPPComment() )
break;
}
const char *c = (const char*)buf.PeekGet( sizeof(char), 0 );
if ( !c )
return NULL;
// read quoted strings specially
if ( *c == '\"' )
{
wasQuoted = true;
buf.GetDelimitedString( m_bHasEscapeSequences ? GetCStringCharConversion() : GetNoEscCharConversion(),
s_pTokenBuf, KEYVALUES_TOKEN_SIZE );
return s_pTokenBuf;
}
if ( *c == '{' || *c == '}' )
{
// it's a control char, just add this one char and stop reading
s_pTokenBuf[0] = *c;
s_pTokenBuf[1] = 0;
buf.SeekGet( CUtlBuffer::SEEK_CURRENT, 1 );
return s_pTokenBuf;
}
// read in the token until we hit a whitespace or a control character
bool bReportedError = false;
int nCount = 0;
while ( c = (const char*)buf.PeekGet( sizeof(char), 0 ) )
{
// end of file
if ( *c == 0 )
break;
// break if any control character appears in non quoted tokens
if ( *c == '"' || *c == '{' || *c == '}' )
break;
// break on whitespace
if ( isspace(*c) )
break;
if (nCount < (KEYVALUES_TOKEN_SIZE-1) )
{
s_pTokenBuf[nCount++] = *c; // add char to buffer
}
else if ( !bReportedError )
{
bReportedError = true;
g_KeyValuesErrorStack.ReportError(" ReadToken overflow" );
}
buf.SeekGet( CUtlBuffer::SEEK_CURRENT, 1 );
}
s_pTokenBuf[ nCount ] = 0;
return s_pTokenBuf;
}
#pragma warning (default:4706)
//-----------------------------------------------------------------------------
// Purpose: if parser should translate escape sequences ( /n, /t etc), set to true
//-----------------------------------------------------------------------------
void KeyValues::UsesEscapeSequences(bool state)
{
m_bHasEscapeSequences = state;
}
//-----------------------------------------------------------------------------
// Purpose: Load keyValues from disk
//-----------------------------------------------------------------------------
bool KeyValues::LoadFromFile( IBaseFileSystem *filesystem, const char *resourceName, const char *pathID )
{
Assert(filesystem);
Assert( IsXbox() || ( IsPC() && _heapchk() == _HEAPOK ) );
FileHandle_t f = filesystem->Open(resourceName, "rb", pathID);
if (!f)
return false;
s_LastFileLoadingFrom = (char*)resourceName;
// load file into a null-terminated buffer
int fileSize = filesystem->Size(f);
unsigned bufSize = ((IFileSystem *)filesystem)->GetOptimalReadSize( f, fileSize + 1 );
char *buffer = (char*)((IFileSystem *)filesystem)->AllocOptimalReadBuffer( f, bufSize );
Assert(buffer);
((IFileSystem *)filesystem)->ReadEx(buffer, bufSize, fileSize, f); // read into local buffer
buffer[fileSize] = 0; // null terminate file as EOF
filesystem->Close( f ); // close file after reading
bool retOK = LoadFromBuffer( resourceName, buffer, filesystem );
((IFileSystem *)filesystem)->FreeOptimalReadBuffer( buffer );
return retOK;
}
//-----------------------------------------------------------------------------
// Purpose: Save the keyvalues to disk
// Creates the path to the file if it doesn't exist
//-----------------------------------------------------------------------------
bool KeyValues::SaveToFile( IBaseFileSystem *filesystem, const char *resourceName, const char *pathID )
{
// create a write file
FileHandle_t f = filesystem->Open(resourceName, "wb", pathID);
if ( f == FILESYSTEM_INVALID_HANDLE )
{
DevMsg(1, "KeyValues::SaveToFile: couldn't open file \"%s\" in path \"%s\".\n",
resourceName?resourceName:"NULL", pathID?pathID:"NULL" );
return false;
}
RecursiveSaveToFile(filesystem, f, NULL, 0);
filesystem->Close(f);
return true;
}
//-----------------------------------------------------------------------------
// Purpose: Write out a set of indenting
//-----------------------------------------------------------------------------
void KeyValues::WriteIndents( IBaseFileSystem *filesystem, FileHandle_t f, CUtlBuffer *pBuf, int indentLevel )
{
for ( int i = 0; i < indentLevel; i++ )
{
INTERNALWRITE( "\t", 1 );
}
}
//-----------------------------------------------------------------------------
// Purpose: Write out a string where we convert the double quotes to backslash double quote
//-----------------------------------------------------------------------------
void KeyValues::WriteConvertedString( IBaseFileSystem *filesystem, FileHandle_t f, CUtlBuffer *pBuf, const char *pszString )
{
// handle double quote chars within the string
// the worst possible case is that the whole string is quotes
int len = Q_strlen(pszString);
char *convertedString = (char *) _alloca ((len + 1) * sizeof(char) * 2);
int j=0;
for (int i=0; i <= len; i++)
{
if (pszString[i] == '\"')
{
convertedString[j] = '\\';
j++;
}
else if ( m_bHasEscapeSequences && pszString[i] == '\\' )
{
convertedString[j] = '\\';
j++;
}
convertedString[j] = pszString[i];
j++;
}
INTERNALWRITE(convertedString, strlen(convertedString));
}
void KeyValues::InternalWrite( IBaseFileSystem *filesystem, FileHandle_t f, CUtlBuffer *pBuf, const void *pData, int len )
{
if ( filesystem )
{
filesystem->Write( pData, len, f );
}
if ( pBuf )
{
pBuf->Put( pData, len );
}
}
//-----------------------------------------------------------------------------
// Purpose: Save keyvalues from disk, if subkey values are detected, calls
// itself to save those
//-----------------------------------------------------------------------------
void KeyValues::RecursiveSaveToFile( IBaseFileSystem *filesystem, FileHandle_t f, CUtlBuffer *pBuf, int indentLevel )
{
// write header
WriteIndents( filesystem, f, pBuf, indentLevel );
INTERNALWRITE("\"", 1);
WriteConvertedString(filesystem, f, pBuf, GetName());
INTERNALWRITE("\"\n", 2);
WriteIndents( filesystem, f, pBuf, indentLevel );
INTERNALWRITE("{\n", 2);
// loop through all our keys writing them to disk
for ( KeyValues *dat = m_pSub; dat != NULL; dat = dat->m_pPeer )
{
if ( dat->m_pSub )
{
dat->RecursiveSaveToFile( filesystem, f, pBuf, indentLevel + 1 );
}
else
{
// only write non-empty keys
switch (dat->m_iDataType)
{
case TYPE_STRING:
{
if (dat->m_sValue && *(dat->m_sValue))
{
WriteIndents(filesystem, f, pBuf, indentLevel + 1);
INTERNALWRITE("\"", 1);
WriteConvertedString(filesystem, f, pBuf, dat->GetName());
INTERNALWRITE("\"\t\t\"", 4);
WriteConvertedString(filesystem, f, pBuf, dat->m_sValue);
INTERNALWRITE("\"\n", 2);
}
break;
}
case TYPE_WSTRING:
{
#ifdef _WIN32
if ( dat->m_wsValue )
{
static char buf[KEYVALUES_TOKEN_SIZE];
// make sure we have enough space
Assert(::WideCharToMultiByte(CP_UTF8, 0, dat->m_wsValue, -1, NULL, 0, NULL, NULL) < KEYVALUES_TOKEN_SIZE);
int result = ::WideCharToMultiByte(CP_UTF8, 0, dat->m_wsValue, -1, buf, KEYVALUES_TOKEN_SIZE, NULL, NULL);
if (result)
{
WriteIndents(filesystem, f, pBuf, indentLevel + 1);
INTERNALWRITE("\"", 1);
INTERNALWRITE(dat->GetName(), Q_strlen(dat->GetName()));
INTERNALWRITE("\"\t\t\"", 4);
WriteConvertedString(filesystem, f, pBuf, buf);
INTERNALWRITE("\"\n", 2);
}
}
#endif
break;
}
case TYPE_INT:
{
WriteIndents(filesystem, f, pBuf, indentLevel + 1);
INTERNALWRITE("\"", 1);
INTERNALWRITE(dat->GetName(), Q_strlen(dat->GetName()));
INTERNALWRITE("\"\t\t\"", 4);
char buf[32];
Q_snprintf(buf, sizeof( buf ), "%d", dat->m_iValue);
INTERNALWRITE(buf, Q_strlen(buf));
INTERNALWRITE("\"\n", 2);
break;
}
case TYPE_UINT64:
{
WriteIndents(filesystem, f, pBuf, indentLevel + 1);
INTERNALWRITE("\"", 1);
INTERNALWRITE(dat->GetName(), Q_strlen(dat->GetName()));
INTERNALWRITE("\"\t\t\"", 4);
char buf[32];
Q_binarytohex((byte *)dat->m_sValue, sizeof(uint64), buf, sizeof(buf));
INTERNALWRITE(buf, Q_strlen(buf));
INTERNALWRITE("\"\n", 2);
break;
}
case TYPE_FLOAT:
{
WriteIndents(filesystem, f, pBuf, indentLevel + 1);
INTERNALWRITE("\"", 1);
INTERNALWRITE(dat->GetName(), Q_strlen(dat->GetName()));
INTERNALWRITE("\"\t\t\"", 4);
char buf[48];
Q_snprintf(buf, sizeof( buf ), "%f", dat->m_flValue);
INTERNALWRITE(buf, Q_strlen(buf));
INTERNALWRITE("\"\n", 2);
break;
}
case TYPE_COLOR:
DevMsg(1, "KeyValues::RecursiveSaveToFile: TODO, missing code for TYPE_COLOR.\n");
break;
default:
break;
}
}
}
// write tail
WriteIndents(filesystem, f, pBuf, indentLevel);
INTERNALWRITE("}\n", 2);
}
//-----------------------------------------------------------------------------
// Purpose: looks up a key by symbol name
//-----------------------------------------------------------------------------
KeyValues *KeyValues::FindKey(int keySymbol) const
{
for (KeyValues *dat = m_pSub; dat != NULL; dat = dat->m_pPeer)
{
if (dat->m_iKeyName == keySymbol)
return dat;
}
return NULL;
}
//-----------------------------------------------------------------------------
// Purpose: Find a keyValue, create it if it is not found.
// Set bCreate to true to create the key if it doesn't already exist
// (which ensures a valid pointer will be returned)
//-----------------------------------------------------------------------------
KeyValues *KeyValues::FindKey(const char *keyName, bool bCreate)
{
// return the current key if a NULL subkey is asked for
if (!keyName || !keyName[0])
return this;
// look for '/' characters deliminating sub fields
char szBuf[256];
const char *subStr = strchr(keyName, '/');
const char *searchStr = keyName;
// pull out the substring if it exists
if (subStr)
{
int size = subStr - keyName;
Q_memcpy( szBuf, keyName, size );
szBuf[size] = 0;
searchStr = szBuf;
}
// lookup the symbol for the search string
HKeySymbol iSearchStr = KeyValuesSystem()->GetSymbolForString(searchStr);
KeyValues *lastItem = NULL;
KeyValues *dat;
// find the searchStr in the current peer list
for (dat = m_pSub; dat != NULL; dat = dat->m_pPeer)
{
lastItem = dat; // record the last item looked at (for if we need to append to the end of the list)
// symbol compare
if (dat->m_iKeyName == iSearchStr)
{
break;
}
}
if ( !dat && m_pChain )
{
dat = m_pChain->FindKey(keyName, false);
}
// make sure a key was found
if (!dat)
{
if (bCreate)
{
// we need to create a new key
dat = new KeyValues( searchStr );
// Assert(dat != NULL);
// insert new key at end of list
if (lastItem)
{
lastItem->m_pPeer = dat;
}
else
{
m_pSub = dat;
}
dat->m_pPeer = NULL;
// a key graduates to be a submsg as soon as it's m_pSub is set
// this should be the only place m_pSub is set
m_iDataType = TYPE_NONE;
}
else
{
return NULL;
}
}
// if we've still got a subStr we need to keep looking deeper in the tree
if ( subStr )
{
// recursively chain down through the paths in the string
return dat->FindKey(subStr + 1, bCreate);
}
return dat;
}
//-----------------------------------------------------------------------------
// Purpose: Create a new key, with an autogenerated name.
// Name is guaranteed to be an integer, of value 1 higher than the highest
// other integer key name
//-----------------------------------------------------------------------------
KeyValues *KeyValues::CreateNewKey()
{
int newID = 1;
// search for any key with higher values
for (KeyValues *dat = m_pSub; dat != NULL; dat = dat->m_pPeer)
{
// case-insensitive string compare
int val = atoi(dat->GetName());
if (newID <= val)
{
newID = val + 1;
}
}
char buf[12];
Q_snprintf( buf, sizeof(buf), "%d", newID );
return CreateKey( buf );
}
//-----------------------------------------------------------------------------
// Create a key
//-----------------------------------------------------------------------------
KeyValues* KeyValues::CreateKey( const char *keyName )
{
// key wasn't found so just create a new one
KeyValues* dat = new KeyValues( keyName );
dat->UsesEscapeSequences( m_bHasEscapeSequences != 0 ); // use same format as parent does
// add into subkey list
AddSubKey( dat );
return dat;
}
//-----------------------------------------------------------------------------
// Adds a subkey. Make sure the subkey isn't a child of some other keyvalues
//-----------------------------------------------------------------------------
void KeyValues::AddSubKey( KeyValues *pSubkey )
{
// Make sure the subkey isn't a child of some other keyvalues
Assert( pSubkey->m_pPeer == NULL );
// add into subkey list
if ( m_pSub == NULL )
{
m_pSub = pSubkey;
}
else
{
KeyValues *pTempDat = m_pSub;
while ( pTempDat->GetNextKey() != NULL )
{
pTempDat = pTempDat->GetNextKey();
}
pTempDat->SetNextKey( pSubkey );
}
}
//-----------------------------------------------------------------------------
// Purpose: Remove a subkey from the list
//-----------------------------------------------------------------------------
void KeyValues::RemoveSubKey(KeyValues *subKey)
{
if (!subKey)
return;
// check the list pointer
if (m_pSub == subKey)
{
m_pSub = subKey->m_pPeer;
}
else
{
// look through the list
KeyValues *kv = m_pSub;
while (kv->m_pPeer)
{
if (kv->m_pPeer == subKey)
{
kv->m_pPeer = subKey->m_pPeer;
break;
}
kv = kv->m_pPeer;
}
}
subKey->m_pPeer = NULL;
}
//-----------------------------------------------------------------------------
// Purpose: Return the first subkey in the list
//-----------------------------------------------------------------------------
KeyValues *KeyValues::GetFirstSubKey()
{
return m_pSub;
}
//-----------------------------------------------------------------------------
// Purpose: Return the next subkey
//-----------------------------------------------------------------------------
KeyValues *KeyValues::GetNextKey()
{
return m_pPeer;
}
//-----------------------------------------------------------------------------
// Purpose: Sets this key's peer to the KeyValues passed in
//-----------------------------------------------------------------------------
void KeyValues::SetNextKey( KeyValues *pDat )
{
m_pPeer = pDat;
}
KeyValues* KeyValues::GetFirstTrueSubKey()
{
KeyValues *pRet = m_pSub;
while ( pRet && pRet->m_iDataType != TYPE_NONE )
pRet = pRet->m_pPeer;
return pRet;
}
KeyValues* KeyValues::GetNextTrueSubKey()
{
KeyValues *pRet = m_pPeer;
while ( pRet && pRet->m_iDataType != TYPE_NONE )
pRet = pRet->m_pPeer;
return pRet;
}
KeyValues* KeyValues::GetFirstValue()
{
KeyValues *pRet = m_pSub;
while ( pRet && pRet->m_iDataType == TYPE_NONE )
pRet = pRet->m_pPeer;
return pRet;
}
KeyValues* KeyValues::GetNextValue()
{
KeyValues *pRet = m_pPeer;
while ( pRet && pRet->m_iDataType == TYPE_NONE )
pRet = pRet->m_pPeer;
return pRet;
}
//-----------------------------------------------------------------------------
// Purpose: Get the integer value of a keyName. Default value is returned
// if the keyName can't be found.
//-----------------------------------------------------------------------------
int KeyValues::GetInt( const char *keyName, int defaultValue )
{
KeyValues *dat = FindKey( keyName, false );
if ( dat )
{
switch ( dat->m_iDataType )
{
case TYPE_STRING:
return atoi(dat->m_sValue);
case TYPE_WSTRING:
#ifdef _WIN32
return _wtoi(dat->m_wsValue);
#else
DevMsg( "TODO: implement _wtoi\n");
return 0;
#endif
case TYPE_FLOAT:
return (int)dat->m_flValue;
case TYPE_UINT64:
// can't convert, since it would lose data
Assert(0);
return 0;
case TYPE_INT:
case TYPE_PTR:
default:
return dat->m_iValue;
};
}