-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMarkup.cpp
More file actions
3022 lines (2820 loc) · 79.8 KB
/
Markup.cpp
File metadata and controls
3022 lines (2820 loc) · 79.8 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
// Markup.cpp: implementation of the CMarkup class.
//
// Markup Release 9.0
// Copyright (C) 1999-2007 First Objective Software, Inc. All rights reserved
// Go to www.firstobject.com for the latest CMarkup and EDOM documentation
// Use in commercial applications requires written permission
// This software is provided "as is", with no warranty.
//
#include <stdio.h>
#include "Markup.h"
#ifdef MCD_STRERROR
#include <string.h>
#include <errno.h>
#else
#include <windows.h>
#endif
#if defined(_DEBUG) && ! defined(MARKUP_STL) && ! defined(MARKUP_STDC)
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
#ifdef _MBCS
#pragma message( "Note: MBCS build (not UTF-8)" )
// For UTF-8, remove _MBCS from project settings C/C++ preprocessor definitions
#endif
// Customization
#define x_EOL _T("\r\n") // can be \r\n or \n or empty
#define x_EOLLEN (sizeof(x_EOL)/sizeof(MCD_CHAR)-1) // string length of x_EOL
#define x_ATTRIBQUOTE _T("\"") // can be double or single quote
void CMarkup::operator=( const CMarkup& markup )
{
m_iPosParent = markup.m_iPosParent;
m_iPos = markup.m_iPos;
m_iPosChild = markup.m_iPosChild;
m_iPosFree = markup.m_iPosFree;
m_iPosDeleted = markup.m_iPosDeleted;
m_nNodeType = markup.m_nNodeType;
m_nNodeOffset = markup.m_nNodeOffset;
m_nNodeLength = markup.m_nNodeLength;
m_strDoc = markup.m_strDoc;
m_strError = markup.m_strError;
m_nFlags = markup.m_nFlags;
// Copy used part of the index array
m_aPos.RemoveAll();
m_aPos.nSize = m_iPosFree;
if ( m_aPos.nSize < 8 )
m_aPos.nSize = 8;
m_aPos.nSegs = m_aPos.SegsUsed();
if ( m_aPos.nSegs )
{
m_aPos.pSegs = (ElemPos**)(new char[m_aPos.nSegs*sizeof(char*)]);
int nSegSize = 1 << m_aPos.PA_SEGBITS;
for ( int nSeg=0; nSeg < m_aPos.nSegs; ++nSeg )
{
if ( nSeg + 1 == m_aPos.nSegs )
nSegSize = m_aPos.GetSize() - (nSeg << m_aPos.PA_SEGBITS);
m_aPos.pSegs[nSeg] = (ElemPos*)(new char[nSegSize*sizeof(ElemPos)]);
memcpy( m_aPos.pSegs[nSeg], markup.m_aPos.pSegs[nSeg], nSegSize*sizeof(ElemPos) );
}
}
// Copy SavedPos map
m_mapSavedPos.RemoveAll();
if ( markup.m_mapSavedPos.pTable )
{
m_mapSavedPos.AllocMapTable();
for ( int nSlot=0; nSlot < SavedPosMap::SPM_SIZE; ++nSlot )
{
SavedPos* pCopySavedPos = markup.m_mapSavedPos.pTable[nSlot];
if ( pCopySavedPos )
{
int nCount = 0;
while ( pCopySavedPos[nCount].nSavedPosFlags & SavedPosMap::SPM_USED )
{
++nCount;
if ( pCopySavedPos[nCount-1].nSavedPosFlags & SavedPosMap::SPM_LAST )
break;
}
if ( nCount )
{
SavedPos* pNewSavedPos = new SavedPos[nCount];
for ( int nCopy=0; nCopy<nCount; ++nCopy )
pNewSavedPos[nCopy] = pCopySavedPos[nCopy];
pNewSavedPos[nCount-1].nSavedPosFlags |= SavedPosMap::SPM_LAST;
m_mapSavedPos.pTable[nSlot] = pNewSavedPos;
}
}
}
}
MARKUP_SETDEBUGSTATE;
}
bool CMarkup::SetDoc( MCD_PCSZ szDoc )
{
// Set document text
if ( szDoc )
m_strDoc = szDoc;
else
MCD_STRCLEAR(m_strDoc);
MCD_STRCLEAR(m_strError);
return x_ParseDoc();
};
bool CMarkup::SetDoc( const MCD_STR& strDoc )
{
m_strDoc = strDoc;
MCD_STRCLEAR(m_strError);
return x_ParseDoc();
}
bool CMarkup::IsWellFormed()
{
if ( m_aPos.GetSize()
&& ! (m_aPos[0].nFlags & MNF_ILLFORMED)
&& m_aPos[0].iElemChild
&& ! m_aPos[m_aPos[0].iElemChild].iElemNext )
return true;
return false;
}
bool CMarkup::Load( MCD_CSTR szFileName )
{
if ( ! ReadTextFile(szFileName, m_strDoc, &m_strError, &m_nFlags) )
return false;
return x_ParseDoc();
}
bool CMarkup::ReadTextFile( MCD_CSTR szFileName, MCD_STR& strDoc, MCD_STR* pstrError, int* pnFlags )
{
// Static utility method to load text file into strDoc
//
// Open file to read binary
FILE* fp = MCD_FOPEN( szFileName, _T("rb") );
if ( ! fp )
{
if ( pstrError )
*pstrError = x_GetLastError();
return false;
}
// Set flags to 0 unless flags argument provided
int nFlags = pnFlags?*pnFlags:0;
MCD_CHAR szDescBOM[20] = {0};
MCD_CHAR szResult[100];
MCD_STRCLEAR(strDoc);
// Get file length
fseek( fp, 0, SEEK_END );
int nFileByteLen = ftell( fp );
fseek( fp, 0, SEEK_SET );
#if defined(UNICODE) // convert file to wide char
int nWideLen = 0;
if ( nFileByteLen )
{
char* pBuffer = new char[nFileByteLen];
fread( pBuffer, nFileByteLen, 1, fp );
/*
// Alternative: use these 3 lines instead of 3 lines below using UTF8To16
// For ANSI files, replace CP_UTF8 with CP_ACP in both places
nWideLen = MultiByteToWideChar(CP_UTF8,0,pBuffer,nFileByteLen,NULL,0);
MCD_CHAR* pUTF16Buffer = MCD_GETBUFFER(strDoc,nWideLen);
MultiByteToWideChar(CP_UTF8,0,pBuffer,nFileByteLen,pUTF16Buffer,nWideLen);
*/
// For ANSI files, replace both UTF8To16 calls with mbstowcs (arguments are the same)
nWideLen = UTF8To16(NULL,pBuffer,nFileByteLen);
MCD_CHAR* pUTF16Buffer = MCD_GETBUFFER(strDoc,nWideLen);
UTF8To16(pUTF16Buffer,pBuffer,nFileByteLen);
MCD_RELEASEBUFFER( strDoc, pUTF16Buffer, nWideLen );
delete [] pBuffer;
}
MCD_SPRINTF( szResult, _T("%s%d bytes to %d wide chars"), szDescBOM, nFileByteLen, nWideLen );
if ( pstrError )
*pstrError = szResult;
#else // read file directly
if ( nFileByteLen )
{
MCD_CHAR* pUTF8Buffer = MCD_GETBUFFER(strDoc,nFileByteLen);
fread( pUTF8Buffer, nFileByteLen, 1, fp );
MCD_RELEASEBUFFER( strDoc, pUTF8Buffer, nFileByteLen );
#if defined(_MBCS) // needs to be in memory as MBCS
MCD_STR strEncoding = GetDeclaredEncoding( strDoc );
if ( MCD_STRISEMPTY(strEncoding) || MCD_PSZNICMP(MCD_2PCSZ(strEncoding),_T("UTF-8"),5)==0 )
strDoc = UTF8ToA( strDoc );
#endif
}
MCD_SPRINTF( szResult, _T("%s%d bytes"), szDescBOM, nFileByteLen );
if ( pstrError )
*pstrError = szResult;
#endif
fclose( fp );
if ( pnFlags )
*pnFlags = nFlags;
return true;
}
bool CMarkup::Save( MCD_CSTR szFileName )
{
return WriteTextFile( szFileName, m_strDoc, &m_strError, &m_nFlags );
}
bool CMarkup::WriteTextFile( MCD_CSTR szFileName, MCD_STR& strDoc, MCD_STR* pstrError, int* pnFlags )
{
// Static utility method to save strDoc to text file
//
// Open file to write binary
bool bSuccess = true;
FILE* fp = MCD_FOPEN( szFileName, _T("wb") );
if ( ! fp )
{
if ( pstrError )
*pstrError = x_GetLastError();
return false;
}
// Set flags to 0 unless flags argument provided
int nFlags = pnFlags?*pnFlags:0;
MCD_CHAR szDescBOM[20] = {0};
MCD_CHAR szResult[100];
// Get document length
int nDocLength = MCD_STRLENGTH(strDoc);
#if defined( UNICODE )
int nMBLen = 0;
if ( nDocLength )
{
/*
// Alternative: use these 3 lines instead of 3 lines below using UTF16To8
// For ANSI files, replace CP_UTF8 with CP_ACP in both places
nMBLen = WideCharToMultiByte(CP_UTF8,0,strDoc,nDocLength,NULL,0,NULL,NULL);
char* pBuffer = new char[nMBLen+1];
WideCharToMultiByte(CP_UTF8,0,strDoc,nDocLength,pBuffer,nMBLen+1,NULL,NULL);
*/
// For ANSI files, replace both UTF16To8 calls with wcstombs (arguments are the same)
nMBLen = UTF16To8(NULL,MCD_2PCSZ(strDoc),0);
char* pBuffer = new char[nMBLen+1];
UTF16To8(pBuffer,MCD_2PCSZ(strDoc),nMBLen);
bSuccess = ( fwrite( pBuffer, nMBLen, 1, fp ) == 1 );
delete [] pBuffer;
}
MCD_SPRINTF( szResult, _T("%d wide chars to %s%d bytes"), nDocLength, szDescBOM, nMBLen );
if ( pstrError )
*pstrError = szResult;
#else // MBCS or UTF-8
if ( nDocLength )
{
MCD_STR strDocWrite = strDoc; // reference unless converted
#if defined(_MBCS) // is in memory as MBCS
MCD_STR strEncoding = GetDeclaredEncoding( strDoc );
if ( MCD_STRISEMPTY(strEncoding) || MCD_PSZNICMP(MCD_2PCSZ(strEncoding),_T("UTF-8"),5)==0 )
strDocWrite = AToUTF8( strDoc );
#endif
nDocLength = MCD_STRLENGTH(strDocWrite);
bSuccess = ( fwrite( MCD_2PCSZ(strDocWrite), nDocLength, 1, fp ) == 1 );
}
MCD_SPRINTF( szResult, _T("%s%d bytes"), szDescBOM, nDocLength );
if ( pstrError )
*pstrError = szResult;
#endif
if ( ! bSuccess && pstrError )
*pstrError = x_GetLastError();
fclose(fp);
if ( pnFlags )
*pnFlags = nFlags;
return bSuccess;
}
bool CMarkup::FindElem( MCD_CSTR szName )
{
// Change current position only if found
//
if ( m_aPos.GetSize() )
{
int iPos = x_FindElem( m_iPosParent, m_iPos, szName );
if ( iPos )
{
// Assign new position
x_SetPos( m_aPos[iPos].iElemParent, iPos, 0 );
return true;
}
}
return false;
}
bool CMarkup::FindChildElem( MCD_CSTR szName )
{
// Change current child position only if found
//
// Shorthand: call this with no current main position
// means find child under root element
if ( ! m_iPos )
FindElem();
int iPosChild = x_FindElem( m_iPos, m_iPosChild, szName );
if ( iPosChild )
{
// Assign new position
int iPos = m_aPos[iPosChild].iElemParent;
x_SetPos( m_aPos[iPos].iElemParent, iPos, iPosChild );
return true;
}
return false;
}
MCD_STR CMarkup::EscapeText( MCD_CSTR szText, int nFlags )
{
// Convert text as seen outside XML document to XML friendly
// replacing special characters with ampersand escape codes
// E.g. convert "6>7" to "6>7"
//
// < less than
// & ampersand
// > greater than
//
// and for attributes:
//
// ' apostrophe or single quote
// " double quote
//
static MCD_PCSZ szaReplace[] = { _T("<"),_T("&"),_T(">"),_T("'"),_T(""") };
MCD_PCSZ pFind = (nFlags&MNF_ESCAPEQUOTES)?_T("<&>\'\""):_T("<&>");
MCD_STR strText;
MCD_PCSZ pSource = szText;
int nDestSize = MCD_PSZLEN(pSource);
nDestSize += nDestSize / 10 + 7;
MCD_BLDRESERVE(strText,nDestSize);
MCD_CHAR cSource = *pSource;
MCD_PCSZ pFound;
int nCharLen;
while ( cSource )
{
MCD_BLDCHECK(strText,nDestSize,6);
if ( (pFound=MCD_PSZCHR(pFind,cSource)) != NULL )
{
bool bIgnoreAmpersand = false;
if ( (nFlags&MNF_WITHREFS) && *pFound == _T('&') )
{
// Do not replace ampersand if it is start of any entity reference
// &[#_:A-Za-zU][_:-.A-Za-z0-9U]*; where U is > 0x7f
MCD_PCSZ pCheckEntity = pSource;
++pCheckEntity;
MCD_CHAR c = *pCheckEntity;
if ( (c>=_T('A')&&c<=_T('Z')) || (c>=_T('a')&&c<=_T('z'))
|| c==_T('#') || c==_T('_') || c==_T(':') || ((unsigned int)c)>0x7f )
{
while ( 1 )
{
pCheckEntity += MCD_CLEN( pCheckEntity );
c = *pCheckEntity;
if ( c == _T(';') )
{
int nEntityLen = (int)(pCheckEntity - pSource) + 1;
MCD_BLDAPPENDN(strText,pSource,nEntityLen);
pSource = pCheckEntity;
bIgnoreAmpersand = true;
}
else if ( (c>=_T('A')&&c<=_T('Z')) || (c>=_T('a')&&c<=_T('z')) || (c>=_T('0')&&c<=_T('9'))
|| c==_T('_') || c==_T(':') || c==_T('-') || c==_T('.') || ((unsigned int)c)>0x7f )
continue;
break;
}
}
}
if ( ! bIgnoreAmpersand )
{
pFound = szaReplace[pFound-pFind];
MCD_BLDAPPEND(strText,pFound);
}
++pSource; // ASCII, so 1 byte
}
else
{
nCharLen = MCD_CLEN( pSource );
MCD_BLDAPPENDN(strText,pSource,nCharLen);
pSource += nCharLen;
}
cSource = *pSource;
}
MCD_BLDRELEASE(strText);
return strText;
}
MCD_STR CMarkup::UnescapeText( MCD_CSTR szText, int nTextLength /*=-1*/ )
{
// Convert XML friendly text to text as seen outside XML document
// ampersand escape codes replaced with special characters e.g. convert "6>7" to "6>7"
// ampersand numeric codes replaced with character e.g. convert < to <
// Conveniently the result is always the same or shorter in byte length
//
static MCD_PCSZ szaCode[] = { _T("lt;"),_T("amp;"),_T("gt;"),_T("apos;"),_T("quot;") };
static int anCodeLen[] = { 3,4,3,5,5 };
static MCD_PCSZ szSymbol = _T("<&>\'\"");
MCD_STR strText;
MCD_PCSZ pSource = szText;
if ( nTextLength == -1 )
nTextLength = MCD_PSZLEN(szText);
MCD_BLDRESERVE(strText,nTextLength);
int nCharLen;
int nChar = 0;
while ( nChar < nTextLength )
{
if ( pSource[nChar] == _T('&') )
{
bool bCodeConverted = false;
// Is it a numeric character reference?
if ( pSource[nChar+1] == _T('#') )
{
// Is it a hex number?
int nBase = 10;
int nNumericChar = nChar + 2;
MCD_CHAR cChar = pSource[nNumericChar];
if ( cChar == _T('x') )
{
++nNumericChar;
cChar = pSource[nNumericChar];
nBase = 16;
}
// Look for terminating semi-colon within 7 characters
int nCodeLen = 0;
while ( nCodeLen < 7 && cChar && cChar != _T(';') )
{
// only ASCII digits 0-9, A-F, a-f expected
nCodeLen += MCD_CLEN( &pSource[nNumericChar+nCodeLen] );
cChar = pSource[nNumericChar + nCodeLen];
}
// Process unicode
if ( cChar == _T(';') )
{
int nUnicode = MCD_PSZTOL( &pSource[nNumericChar], NULL, nBase );
#if defined(UNICODE)
MCD_BLDAPPEND1(strText,nUnicode);
#elif defined(_MBCS)
MCD_CHAR szANSI[2];
int nMBLen = wctomb( szANSI, (wchar_t)nUnicode );
if ( nMBLen > 0 )
{
MCD_BLDAPPENDN(strText,szANSI,nMBLen);
}
else
nUnicode = 0;
#else
if ( nUnicode < 0x80 )
MCD_BLDAPPEND1(strText,nUnicode);
else if ( nUnicode < 0x800 )
{
// Convert to 2-byte UTF-8
MCD_BLDAPPEND1(strText,((nUnicode&0x7c0)>>6)|0xc0);
MCD_BLDAPPEND1(strText,(nUnicode&0x3f)|0x80);
}
else
{
// Convert to 3-byte UTF-8
MCD_BLDAPPEND1(strText,((nUnicode&0xf000)>>12)|0xe0);
MCD_BLDAPPEND1(strText,((nUnicode&0xfc0)>>6)|0x80);
MCD_BLDAPPEND1(strText,(nUnicode&0x3f)|0x80);
}
#endif
if ( nUnicode )
{
// Increment index past ampersand semi-colon
nChar = nNumericChar + nCodeLen + 1;
bCodeConverted = true;
}
}
}
else // does not start with #
{
// Look for matching &code;
for ( int nMatch = 0; nMatch < 5; ++nMatch )
{
if ( nChar < nTextLength - anCodeLen[nMatch]
&& MCD_PSZNCMP(szaCode[nMatch],&pSource[nChar+1],anCodeLen[nMatch]) == 0 )
{
// Insert symbol and increment index past ampersand semi-colon
MCD_BLDAPPEND1(strText,szSymbol[nMatch]);
nChar += anCodeLen[nMatch] + 1;
bCodeConverted = true;
break;
}
}
}
// If the code is not converted, leave it as is
if ( ! bCodeConverted )
{
MCD_BLDAPPEND1(strText,_T('&'));
++nChar;
}
}
else // not &
{
nCharLen = MCD_CLEN(&pSource[nChar]);
MCD_BLDAPPENDN(strText,&pSource[nChar],nCharLen);
nChar += nCharLen;
}
}
MCD_BLDRELEASE(strText);
return strText;
}
int CMarkup::UTF16To8( char* pszUTF8, const wchar_t* pwszUTF16, int nUTF8Count )
{
// Supports the same arguments as wcstombs
// the pwszUTF16 source must be a NULL-terminated UTF-16 string
// if pszUTF8 is NULL, the number of bytes required is returned and nUTF8Count is ignored
// otherwise pszUTF8 is filled with the result string and NULL-terminated if nUTF8Count allows
// nUTF8Count is the byte size of pszUTF8 and must be large enough for the NULL if NULL desired
// and the number of bytes (excluding NULL) is returned
//
int nUChar, nUTF8Len = 0;
while ( *pwszUTF16 )
{
// Decode UTF-16
nUChar = DecodeCharUTF16( pwszUTF16 );
if ( nUChar == -1 )
nUChar = '?';
// Encode UTF-8
if ( pszUTF8 && nUTF8Len + 4 > nUTF8Count )
{
int nUTF8LenSoFar = nUTF8Len;
EncodeCharUTF8( nUChar, NULL, nUTF8Len );
if ( nUTF8Len > nUTF8Count )
return nUTF8LenSoFar;
nUTF8Len = nUTF8LenSoFar;
}
EncodeCharUTF8( nUChar, pszUTF8, nUTF8Len );
}
if ( pszUTF8 && nUTF8Len < nUTF8Count )
pszUTF8[nUTF8Len] = 0;
return nUTF8Len;
}
int CMarkup::DecodeCharUTF8( const char*& pszUTF8 )
{
// Return Unicode code point and increment pszUTF8 past 1-4 bytes
int nUChar = (unsigned char)*pszUTF8;
++pszUTF8;
if ( nUChar & 0x80 )
{
int nExtraChars;
if ( ! (nUChar & 0x20) )
{
nExtraChars = 1;
nUChar &= 0x1f;
}
else if ( ! (nUChar & 0x10) )
{
nExtraChars = 2;
nUChar &= 0x0f;
}
else if ( ! (nUChar & 0x08) )
{
nExtraChars = 3;
nUChar &= 0x07;
}
else
return -1;
while ( nExtraChars-- )
{
if ( (*pszUTF8 & 0x80) )
{
nUChar = nUChar<<6;
nUChar |= *pszUTF8 & 0x3f;
}
else
return -1;
++pszUTF8;
}
}
return nUChar;
}
void CMarkup::EncodeCharUTF16( int nUChar, wchar_t* pwszUTF16, int& nWideLen )
{
// Write UTF-16 sequence to pwszUTF16 for Unicode code point nUChar and update nWideLen
// Be sure pwszUTF16 has room for up to 2 wide chars
//
if ( nUChar & ~0xffff )
{
if ( pwszUTF16 )
{
// Surrogate pair
nUChar -= 0x10000;
pwszUTF16[nWideLen++] = (wchar_t)(((nUChar>>10) & 0x3ff) | 0xd800); // W1
pwszUTF16[nWideLen++] = (wchar_t)((nUChar & 0x3ff) | 0xdc00); // W2
}
else
nWideLen += 2;
}
else
{
if ( pwszUTF16 )
pwszUTF16[nWideLen++] = (wchar_t)nUChar;
else
++nWideLen;
}
}
int CMarkup::UTF8To16( wchar_t* pwszUTF16, const char* pszUTF8, int nUTF8Count )
{
// Supports the same arguments as mbstowcs
// the pszUTF8 source must be a UTF-8 string which will be processed up to NULL-terminator or nUTF8Count
// if pwszUTF16 is NULL, the number of wide chars required is returned
// nUTF8Count is maximum UTF-8 bytes to convert and should include NULL if NULL desired in result
// if pwszUTF16 is not NULL it is filled with the result string and it must be large enough
// result will be NULL-terminated if NULL encountered in pszUTF8 before nUTF8Count
// and the number of UTF-8 bytes converted is returned
//
const char* pszPosUTF8 = pszUTF8;
int nUChar, nUTF8Len = 0, nWideLen = 0;
while ( nUTF8Len < nUTF8Count )
{
// Decode UTF-8
if ( nUTF8Len + 4 > nUTF8Count )
{
// Pre-examine UTF-8 character using temporary null-terminated copy
// to see if this UTF-8 character boundary is within nUTF8Count
char szUTF8Copy[5];
const char* pszPosUTF8Copy = szUTF8Copy;
int nUTF8EndCount = nUTF8Count - nUTF8Len;
strncpy( szUTF8Copy, pszPosUTF8, nUTF8EndCount );
szUTF8Copy[nUTF8EndCount] = '\0';
nUChar = DecodeCharUTF8( pszPosUTF8Copy );
int nUTF8EndLen = (int)(pszPosUTF8Copy - szUTF8Copy);
if ( nUTF8Len + nUTF8EndLen > nUTF8Count )
break;
}
nUChar = DecodeCharUTF8( pszPosUTF8 );
nUTF8Len = (int)(pszPosUTF8 - pszUTF8);
if ( ! nUChar )
{
if ( pwszUTF16 )
pwszUTF16[nWideLen] = 0;
break;
}
else if ( nUChar == -1 )
nUChar = '?';
// Encode UTF-16
EncodeCharUTF16( nUChar, pwszUTF16, nWideLen );
}
if ( ! pwszUTF16 )
return nWideLen;
return nUTF8Len;
}
int CMarkup::DecodeCharUTF16( const wchar_t*& pwszUTF16 )
{
// Return Unicode code point and increment pwszUTF16 past 1 or 2 (if surrogrates) wide chars
int nUChar = *pwszUTF16;
if ( (nUChar & ~0x000007ff) == 0xd800 ) // W1
{
++pwszUTF16;
if ( ! *pwszUTF16 ) // W2
return -1; // incorrect UTF-16
nUChar = (((nUChar & 0x3ff) << 10) | (*pwszUTF16 & 0x3ff)) + 0x10000;
}
++pwszUTF16;
return nUChar;
}
void CMarkup::EncodeCharUTF8( int nUChar, char* pszUTF8, int& nUTF8Len )
{
// Write UTF-8 sequence to pszUTF8 for Unicode code point nUChar and update nUTF8Len
// Be sure pszUTF8 has room for up to 4 bytes
//
if ( ! (nUChar & ~0x0000007f) ) // < 0x80
{
if ( pszUTF8 )
pszUTF8[nUTF8Len++] = (char)nUChar;
else
++nUTF8Len;
}
else if ( ! (nUChar & ~0x000007ff) ) // < 0x800
{
if ( pszUTF8 )
{
pszUTF8[nUTF8Len++] = (char)(((nUChar&0x7c0)>>6)|0xc0);
pszUTF8[nUTF8Len++] = (char)((nUChar&0x3f)|0x80);
}
else
nUTF8Len += 2;
}
else if ( ! (nUChar & ~0x0000ffff) ) // < 0x10000
{
if ( pszUTF8 )
{
pszUTF8[nUTF8Len++] = (char)(((nUChar&0xf000)>>12)|0xe0);
pszUTF8[nUTF8Len++] = (char)(((nUChar&0xfc0)>>6)|0x80);
pszUTF8[nUTF8Len++] = (char)((nUChar&0x3f)|0x80);
}
else
nUTF8Len += 3;
}
else // < 0x110000
{
if ( pszUTF8 )
{
pszUTF8[nUTF8Len++] = (char)(((nUChar&0x1c0000)>>18)|0xf0);
pszUTF8[nUTF8Len++] = (char)(((nUChar&0x3f000)>>12)|0x80);
pszUTF8[nUTF8Len++] = (char)(((nUChar&0xfc0)>>6)|0x80);
pszUTF8[nUTF8Len++] = (char)((nUChar&0x3f)|0x80);
}
else
nUTF8Len += 4;
}
}
#if ! defined( UNICODE )
MCD_STR CMarkup::UTF8ToA( MCD_CSTR pszUTF8, int* pnFailed/*=NULL*/ )
{
// Converts from UTF-8 directly to locale ANSI charset
// this uses wctomb which requires setlocale other than minimal "C" locale
// e.g. setlocale(LC_ALL, "") enables the OS system locale settings
MCD_STR strANSI;
int nBufferLen = (int)strlen( pszUTF8 ) + 4;
MCD_BLDRESERVE(strANSI,nBufferLen);
int nUChar, nCharLen;
MCD_CHAR szANSI[2];
if ( pnFailed )
*pnFailed = 0;
MCD_PCSZ pUTF8 = pszUTF8;
while ( *pUTF8 )
{
MCD_BLDCHECK(strANSI,nBufferLen,4); // was grow by (nBufferLen / 2 + 4)
nUChar = DecodeCharUTF8( pUTF8 );
if ( nUChar & ~0xffff )
nCharLen = -1;
else
nCharLen = wctomb( szANSI, (wchar_t)nUChar );
if ( nCharLen == -1 )
{
if ( pnFailed )
++(*pnFailed);
MCD_BLDAPPEND1(strANSI,_T('?'));
}
else
{
MCD_BLDAPPENDN(strANSI,szANSI,nCharLen);
}
}
MCD_BLDRELEASE(strANSI);
return strANSI;
}
MCD_STR CMarkup::AToUTF8( MCD_CSTR pszANSI )
{
// Converts locale ANSI charset directly to UTF-8
// this uses mbtowc which requires setlocale other than minimal "C" locale
// e.g. setlocale(LC_ALL, "") enables the OS system locale settings
MCD_STR strUTF8;
int nBufferLen = (int)strlen( pszANSI ) * 2 + 4;
MCD_BLDRESERVE(strUTF8,nBufferLen);
int nUChar, nCharLen;
wchar_t wcChar;
MCD_CHAR szUTF8Char[4];
MCD_PCSZ pANSI = pszANSI;
while ( *pANSI )
{
MCD_BLDCHECK(strUTF8,nBufferLen,4);
nCharLen = mbtowc( &wcChar, pANSI, 5 );
if ( nCharLen < 1 )
{
nCharLen = 1;
wcChar = (wchar_t)'?';
}
pANSI += nCharLen;
nUChar = (int)wcChar;
nCharLen = 0;
EncodeCharUTF8( nUChar, szUTF8Char, nCharLen );
MCD_BLDAPPENDN(strUTF8,szUTF8Char,nCharLen);
}
MCD_BLDRELEASE(strUTF8);
return strUTF8;
}
#endif
MCD_STR CMarkup::GetDeclaredEncoding( MCD_CSTR szDoc )
{
// Extract encoding attribute from XML Declaration
MCD_STR strEncoding;
MCD_PCSZ pStart = MCD_PSZCHR( szDoc, _T('<') );
if ( pStart && pStart[1] == _T('?') )
{
MCD_PCSZ pEnd = MCD_PSZSTR( szDoc, _T("?>") );
if ( pEnd )
{
MCD_STR strXMLDecl( pStart, (int)(pEnd-pStart)+2 );
CMarkup xmlDecl( strXMLDecl );
if ( xmlDecl.FindNode() )
strEncoding = xmlDecl.GetAttrib( _T("encoding") );
}
}
return strEncoding;
}
int CMarkup::FindNode( int nType )
{
// Change current node position only if a node is found
// If nType is 0 find any node, otherwise find node of type nType
// Return type of node or 0 if not found
// If found node is an element, change m_iPos
// Determine where in document to start scanning for node
int nTypeFound = 0;
int nNodeOffset = m_nNodeOffset;
if ( m_nNodeType > 1 )
{
// By-pass current node
nNodeOffset += m_nNodeLength;
}
else
{
// Set position to begin looking for node
nNodeOffset = 0; // default to start of document
if ( m_iPos )
{
// After element
nNodeOffset = m_aPos[m_iPos].StartAfter();
}
else if ( m_iPosParent )
{
// Immediately after start tag of parent
if ( m_aPos[m_iPosParent].IsEmptyElement() )
return 0;
else
nNodeOffset = m_aPos[m_iPosParent].StartContent();
}
}
// Get nodes until we find what we're looking for
int iPosNew = m_iPos;
TokenPos token( m_strDoc, m_nFlags );
NodePos node;
token.nNext = nNodeOffset;
do
{
nNodeOffset = token.nNext;
nTypeFound = x_ParseNode( token, node );
if ( nTypeFound == 0 )
{
// Check if we have reached the end of the parent element
// Otherwise it is a lone end tag
if ( m_iPosParent && nNodeOffset == m_aPos[m_iPosParent].StartContent()
+ m_aPos[m_iPosParent].ContentLen() )
return 0;
nTypeFound = MNT_LONE_END_TAG;
}
else if ( nTypeFound < 0 )
{
if ( nTypeFound == -2 )
return 0;
// -1 is node error
nTypeFound = MNT_NODE_ERROR;
}
else if ( nTypeFound == MNT_ELEMENT )
{
if ( iPosNew )
iPosNew = m_aPos[iPosNew].iElemNext;
else
iPosNew = m_aPos[m_iPosParent].iElemChild;
if ( ! iPosNew )
return 0;
if ( ! nType || (nType & nTypeFound) )
{
// Found element node, move position to this element
x_SetPos( m_iPosParent, iPosNew, 0 );
return m_nNodeType;
}
token.nNext = m_aPos[iPosNew].StartAfter();
}
}
while ( nType && ! (nType & nTypeFound) );
m_iPos = iPosNew;
m_iPosChild = 0;
m_nNodeOffset = nNodeOffset;
m_nNodeLength = token.nNext - nNodeOffset;
m_nNodeType = nTypeFound;
MARKUP_SETDEBUGSTATE;
return m_nNodeType;
}
bool CMarkup::RemoveNode()
{
if ( m_iPos || m_nNodeLength )
{
x_RemoveNode( m_iPosParent, m_iPos, m_nNodeType, m_nNodeOffset, m_nNodeLength );
m_iPosChild = 0;
MARKUP_SETDEBUGSTATE;
return true;
}
return false;
}
MCD_STR CMarkup::GetTagName() const
{
// Return the tag name at the current main position
MCD_STR strTagName;
// This method is primarily for elements, however
// it does return something for certain other nodes
if ( m_nNodeLength )
{
switch ( m_nNodeType )
{
case MNT_PROCESSING_INSTRUCTION:
case MNT_LONE_END_TAG:
{
// <?target or </tagname
TokenPos token( m_strDoc, m_nFlags );
token.nNext = m_nNodeOffset + 2;
if ( x_FindName(token) )
strTagName = x_GetToken( token );
}
break;
case MNT_COMMENT:
strTagName = _T("#comment");
break;
case MNT_CDATA_SECTION:
strTagName = _T("#cdata-section");
break;
case MNT_DOCUMENT_TYPE:
{
// <!DOCTYPE name
TokenPos token( m_strDoc, m_nFlags );
token.nNext = m_nNodeOffset + 2;
if ( x_FindName(token) && x_FindName(token) )
strTagName = x_GetToken( token );
}
break;
case MNT_TEXT:
case MNT_WHITESPACE:
strTagName = _T("#text");
break;
}
return strTagName;
}
if ( m_iPos )
strTagName = x_GetTagName( m_iPos );
return strTagName;
}
bool CMarkup::IntoElem()
{
// If there is no child position and IntoElem is called it will succeed in release 6.3
// (A subsequent call to FindElem will find the first element)
// The following short-hand behavior was never part of EDOM and was misleading
// It would find a child element if there was no current child element position and go into it
// It is removed in release 6.3, this change is NOT backwards compatible!
// if ( ! m_iPosChild )
// FindChildElem();
if ( m_iPos && m_nNodeType == MNT_ELEMENT )
{
x_SetPos( m_iPos, m_iPosChild, 0 );
return true;
}
return false;
}
bool CMarkup::OutOfElem()
{
// Go to parent element
if ( m_iPosParent )
{
x_SetPos( m_aPos[m_iPosParent].iElemParent, m_iPosParent, m_iPos );
return true;
}
return false;
}
MCD_STR CMarkup::GetAttribName( int n ) const
{
// Return nth attribute name of main position
TokenPos token( m_strDoc, m_nFlags );
if ( m_iPos && m_nNodeType == MNT_ELEMENT )
token.nNext = m_aPos[m_iPos].nStart + 1;
else if ( m_nNodeLength && m_nNodeType == MNT_PROCESSING_INSTRUCTION )