File: libxmlHTMLSAXDriver.m

package info (click to toggle)
sope 5.12.6-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 16,592 kB
  • sloc: objc: 169,229; sh: 3,823; ansic: 3,409; javascript: 446; python: 318; makefile: 185
file content (868 lines) | stat: -rw-r--r-- 23,131 bytes parent folder | download | duplicates (3)
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
/*
  Copyright (C) 2000-2005 SKYRIX Software AG

  This file is part of SOPE.

  SOPE is free software; you can redistribute it and/or modify it under
  the terms of the GNU Lesser General Public License as published by the
  Free Software Foundation; either version 2, or (at your option) any
  later version.

  SOPE 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 Lesser General Public
  License for more details.

  You should have received a copy of the GNU Lesser General Public
  License along with SOPE; see the file COPYING.  If not, write to the
  Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
  02111-1307, USA.
*/

#import "libxmlHTMLSAXDriver.h"
#import "libxmlSAXLocator.h"
#include "TableCallbacks.h"
#include <SaxObjC/SaxObjC.h>
#include <SaxObjC/SaxException.h>
#include "common.h"
#include <string.h>

#include <libxml/HTMLparser.h>
#include <libxml/HTMLtree.h>

@interface NSObject(contentHandlerExtensions)

- (xmlCharEncoding)contentEncoding;

@end

@interface libxmlHTMLSAXDriver(PrivateMethods)

- (void)tearDownParser;

- (BOOL)walkDocumentTree:(xmlDocPtr)_doc;
- (BOOL)processNode:(xmlNodePtr)_node;
- (BOOL)processChildren:(xmlNodePtr)children;

@end

static int _UTF8ToUTF16(unsigned char **sourceStart, unsigned char *sourceEnd, 
                        unichar **targetStart, const unichar *targetEnd);

static BOOL       logUnsupportedFeatures = NO;
static BOOL       reportInvalidTags      = NO;
static BOOL       reportUnclosedEntities = NO;
static NSMapTable *uniqueStrings = NULL; // THREAD
static Class      NSStringClass = Nil;

/* error string detection */
/*
  TODO: obviously this may change between libxml versions or even
        localisations ... why doesn't libxml support error codes ?
        (or does it ?)
*/
static const char *tagInvalidMsg = "tag %s invalid";
static const char *unclosedEntityInvalidMsg = 
  "htmlParseEntityRef: expecting ';'";
#if 0
static const char *unexpectedNobrCloseMsg = 
  "Unexpected end tag : %s";
#endif

static inline NSString *xmlCharsToString(const xmlChar *_s) {
  NSString *s;
  char *newkey;
  
  if (_s == NULL) return nil;
  
  if (uniqueStrings == NULL) {
    uniqueStrings = NSCreateMapTable(libxmlNonOwnedCStringMapKeyCallBacks,
                                     NSObjectMapValueCallBacks,
                                     128);
  }
  else if ((s = NSMapGet(uniqueStrings, _s))) {
    /* found a string in cache ... */
    return [s retain];
  }
  
  newkey = malloc(strlen((char *)_s) + 2);
  strcpy(newkey, (char *)_s);
  
  if (NSStringClass == Nil)
    NSStringClass = [NSString class];
  
  s = [[NSStringClass alloc] initWithUTF8String:(const char *)_s];
  NSMapInsert(uniqueStrings, newkey, s);
  return s;
}

static NSString *SaxDeclHandlerProperty =
  @"http://xml.org/sax/properties/declaration-handler";
static NSString *SaxLexicalHandlerProperty =
  @"http://xml.org/sax/properties/lexical-handler";

static NSString *XMLNS_XHTML = @"http://www.w3.org/1999/xhtml";

@implementation libxmlHTMLSAXDriver

static libxmlHTMLSAXDriver *activeDriver = nil;
static void warning(void *udata, const char *msg, ...);
static void error(void *udata, const char *msg, ...);
static void fatalError(void *udata, const char *msg, ...);
static void setLocator(void *udata, xmlSAXLocatorPtr _locator);

+ (void)initialize {
  NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
  
  reportInvalidTags  = [ud boolForKey:@"libxmlHTMLSAXDriverReportInvalidTags"];
  reportUnclosedEntities = 
    [ud boolForKey:@"libxmlHTMLSAXDriverReportUnclosedEntityRefs"];
}

- (id)init {
  if ((self = [super init])) {
    self->namespaceURI   = [XMLNS_XHTML copy];
    self->encodeEntities = NO;
  }
  return self;
}

- (void)dealloc {
  [self tearDownParser];
  
  [self->attributes     release];
  [self->namespaceURI   release];
  [self->lexicalHandler release];
  [self->declHandler    release];
  [self->contentHandler release];
  [self->dtdHandler     release];
  [self->errorHandler   release];
  [self->entityResolver release];
  [super dealloc];
}

/* features & properties */

- (void)setFeature:(NSString *)_name to:(BOOL)_value {
  if (logUnsupportedFeatures)
    NSLog(@"%s: don't know feature %@", __PRETTY_FUNCTION__, _name);
}
- (BOOL)feature:(NSString *)_name {
  if (logUnsupportedFeatures)
    NSLog(@"%s: don't know feature %@", __PRETTY_FUNCTION__, _name);
  return NO;
}

- (void)setProperty:(NSString *)_name to:(id)_value {
  if ([_name isEqualToString:SaxLexicalHandlerProperty]) {
    ASSIGN(self->lexicalHandler, _value);
    return;
  }
  if ([_name isEqualToString:SaxDeclHandlerProperty]) {
    ASSIGN(self->declHandler, _value);
    return;
  }
  
  [SaxNotRecognizedException raise:@"PropertyException"
                             format:@"don't know property %@", _name];
}
- (id)property:(NSString *)_name {
  if ([_name isEqualToString:SaxLexicalHandlerProperty])
    return self->lexicalHandler;
  if ([_name isEqualToString:SaxDeclHandlerProperty])
    return self->declHandler;
  
  [SaxNotRecognizedException raise:@"PropertyException"
                             format:@"don't know property %@", _name];
  return nil;
}

/* handlers */

- (void)setDTDHandler:(id<NSObject,SaxDTDHandler>)_handler {
  ASSIGN(self->dtdHandler, _handler);
}
- (id<NSObject,SaxDTDHandler>)dtdHandler {
  return self->dtdHandler;
}

- (void)setErrorHandler:(id<NSObject,SaxErrorHandler>)_handler {
  ASSIGN(self->errorHandler, _handler);
}
- (id<NSObject,SaxErrorHandler>)errorHandler {
  return self->errorHandler;
}

- (void)setEntityResolver:(id<NSObject,SaxEntityResolver>)_handler {
  ASSIGN(self->entityResolver, _handler);
}
- (id<NSObject,SaxEntityResolver>)entityResolver {
  return self->entityResolver;
}

- (void)setContentHandler:(id <NSObject,SaxContentHandler>)_handler {
  ASSIGN(self->contentHandler, _handler);
}
- (id <NSObject,SaxContentHandler>)contentHandler {
  return self->contentHandler;
}

/* libxml */

- (void)setupParserWithDocumentPath:(NSString *)_path {
  xmlSAXHandler   sax;
  xmlCharEncoding charEncoding;
  
  if (self->ctxt != NULL) {
    NSLog(@"WARNING(%s): HTML parser context already setup !",
          __PRETTY_FUNCTION__);
    [self tearDownParser];
  }
  
  memcpy(&sax, &htmlDefaultSAXHandler, sizeof(xmlSAXHandler));
  sax.error              = error;
  sax.warning            = warning;
  sax.fatalError         = fatalError;
  sax.setDocumentLocator = setLocator;
  
  if (activeDriver != nil) {
    NSLog(@"WARNING(%s): %@ there is an active driver set (%@), override !",
          __PRETTY_FUNCTION__, self, activeDriver);
  }
  activeDriver = self;
  
  // hh: thats really a very ugly hack. The content-handler is for handling
  //     content, not for dealing with the input data.
  // TBD: the charset should be derived from the input (and this method should
  //      probably take a charset)
  if ([self->contentHandler respondsToSelector:@selector(contentEncoding)])
    charEncoding = [self->contentHandler contentEncoding];
  else
    charEncoding = XML_CHAR_ENCODING_8859_1;
  
  // TBD: do not use cString (nor UTF8String) but NSFileManager to convert
  //      a string into a path
  self->ctxt = htmlCreatePushParserCtxt(&sax             /* sax      */,
                                        NULL /*self*/    /* userdata */,
                                        NULL             /* chunk    */,
                                        0                /* chunklen */,
                                        [_path cString]  /* filename */,
                                        charEncoding     /* encoding */);
  self->doc = NULL;
}
- (void)tearDownParser {
  if (activeDriver == self)
    activeDriver = nil;
  
  if (self->doc) {
    xmlFreeDoc(self->doc);
    self->doc = NULL;
  }
  if (self->ctxt) {
    htmlFreeParserCtxt(self->ctxt);
    self->ctxt = NULL;
  }
}

/* IO */

- (int)pushBytes:(const char *)_bytes count:(unsigned)_len {
  int r;
  r = 0;
  if (_len == 0) return r;
  NSAssert(self->ctxt, @"missing HTML parser context");
  r = htmlParseChunk(self->ctxt, _bytes, _len, 0);
  return r;
}
- (int)pushEOF {
  char dummyByte;
  int r;
  r = htmlParseChunk(self->ctxt, &dummyByte, 0, 1 /* terminate */);
  self->doc = ((xmlParserCtxtPtr)ctxt)->myDoc;
  return r;
}

/* parsing */

- (void)_handleEmptyDataInSystemId:(NSString *)_sysId {
  /*
     An empty HTML file _is_ valid?!
     I guess it equals to <html><body></body></html>, wrong? => hh
  */
  [self->contentHandler startDocument];
  [self->contentHandler startPrefixMapping:@"" uri:self->namespaceURI];

  [self->contentHandler
       startElement:@"html" namespace:XMLNS_XHTML
       rawName:@"html" attributes:nil];
  [self->contentHandler
       startElement:@"body" namespace:XMLNS_XHTML
       rawName:@"body" attributes:nil];
  
  [self->contentHandler
       endElement:@"body" namespace:XMLNS_XHTML rawName:@"body"];
  [self->contentHandler
       endElement:@"html" namespace:XMLNS_XHTML rawName:@"html"];
  
  [self->contentHandler endPrefixMapping:@""];
  [self->contentHandler endDocument];
}

- (void)_parseFromData:(NSData *)_data systemId:(NSString *)_sysId {
  NSAutoreleasePool *pool;
  SaxParseException *e;
  int errCode;

  if ([_data length] == 0) {
    [self _handleEmptyDataInSystemId:_sysId];
    return;
  }
  
  pool = [[NSAutoreleasePool alloc] init];

  /* parse into structure */
  [self setupParserWithDocumentPath:_sysId];
  errCode = [self pushBytes:[_data bytes] count:[_data length]];

  if (XML_ERR_INTERNAL_ERROR == errCode) {
    e = (id)[SaxParseException exceptionWithName:@"SaxIOException"
                                          reason:[NSString stringWithFormat: @"Error XML parsing : %i", errCode]
                                        userInfo:[NSDictionary dictionaryWithObject: [NSNumber numberWithInt: errCode] forKey:@"code"]];
    
    if (self->errorHandler)
      [self->errorHandler fatalError: e];
  }
  
  [self pushEOF];
  
  if (self->doc == NULL) {
    NSLog(@"Could not parse HTML file: %@", _sysId);
    [self tearDownParser];
  }
  else {
    [self walkDocumentTree:self->doc];
    [self tearDownParser];
  }
  
  [pool release];
}

- (void)parseFromSource:(id)_source systemId:(NSString *)_sysId {
  NSAutoreleasePool *pool;

  pool = [[NSAutoreleasePool alloc] init];
  
  if ([_source isKindOfClass:[NSData class]]) {
    [self _parseFromData:_source systemId:_sysId];
    return;
  }
  if ([_source isKindOfClass:[NSString class]]) {
    [self _parseFromData:[_source dataUsingEncoding:NSISOLatin1StringEncoding]
          systemId:_sysId];
    return;
  }
  if ([_source isKindOfClass:[NSURL class]]) {
    NSData *data;

    data = [_source isFileURL]
      ? (NSData *)[NSData dataWithContentsOfMappedFile:[_source path]]
      : [_source resourceDataUsingCache:YES];
    
    [self _parseFromData:data systemId:[_source absoluteString]];
    return;
  }

  {
    SaxParseException *e;
    NSDictionary      *ui;
    
    ui = [[NSDictionary alloc] initWithObjectsAndKeys:
				 _source ? _source : (id)@"<nil>", @"source",
			         self,                             @"parser",
			       nil];
    
    e = (id)[SaxParseException exceptionWithName:@"SaxIOException"
                               reason:@"can not handle data-source"
                               userInfo:ui];
    [ui release]; ui = nil;
    
    [self->errorHandler fatalError:e];
  }

  [self tearDownParser];
  
  [pool release];
}
- (void)parseFromSource:(id)_source {
  if ([_source isKindOfClass:[NSString class]])
    [self parseFromSource:_source systemId:@"<string>"];
  else if ([_source isKindOfClass:[NSData class]])
    [self parseFromSource:_source systemId:@"<data>"];
  else if ([_source isKindOfClass:[NSURL class]])
    [self parseFromSource:_source systemId:[_source absoluteString]];
  else
    [self parseFromSource:_source systemId:@"<memory>"];
}

- (void)parseFromSystemId:(NSString *)_sysId {
  NSAutoreleasePool *pool;
  NSData *data;
  
  if (![_sysId hasPrefix:@"file://"]) {
    /* exception */
    return;
  }
  
  pool = [[NSAutoreleasePool alloc] init];
  
  /* cut off file:// */
  _sysId = [_sysId substringFromIndex:7];
  
  /* load data */
  data = [NSData dataWithContentsOfFile:_sysId];

  [self _parseFromData:data systemId:_sysId];
  
  [pool release];
}

/* process attribute nodes */

- (void)processAttributes:(xmlAttrPtr)_attributes {
  xmlAttrPtr  attribute;
  
  /* setup or clear attribute cache */
  if (self->attributes == nil)
    attributes = [[SaxAttributes alloc] init];
  else
    [attributes clear];
  
  if (_attributes == NULL)
    /* nothing to process */
    return;

  /* add attributes */
  
  for (attribute = _attributes; attribute; attribute = attribute->next) {
    NSString *name, *xhtmlName;
    NSString *value;
#if 0
    printf("attr name '%s' has NS '%s'\n",
           attribute->name, attribute->ns ? "yes" : "no");
#endif
    
    name      = xmlCharsToString(attribute->name);
    xhtmlName = [name lowercaseString];
    value     = @"";
    
    if (attribute->children) {
      xmlChar  *t;
      
      if ((t = xmlNodeListGetString(doc, attribute->children, 0))) {
        value = xmlCharsToString(t);
	free(t); /* should be xmlFree ?? */
      }
    }
    
    [attributes addAttribute:xhtmlName
                uri:self->namespaceURI
                rawName:name
                type:@"CDATA" value:value];

    [name  release]; name  = nil;
    [value release]; value = nil;
  }
  
  return;
}

/* walking the tree, generating SAX events */

- (BOOL)processEntityRefNode:(xmlNodePtr)node {
  NSLog(@"Ignoring entity ref: '%s'\n", node->name);
  return YES;
}

- (BOOL)processDocumentNode:(xmlNodePtr)node {
  BOOL result;
  
  [self->contentHandler startDocument];
  [self->contentHandler startPrefixMapping:@"" uri:self->namespaceURI];
  result = [self processChildren:node->children];
  [self->contentHandler endPrefixMapping:@""];
  [self->contentHandler endDocument];
  
  return result;
}

- (BOOL)processTextNode:(xmlNodePtr)_node {
  static unichar c = '\0';
  xmlChar  *chars;
  NSUInteger len;
  
  if (self->contentHandler == nil)
    return YES;

  if (_node->content == NULL) {
    [self->contentHandler characters:&c length:0];
    return YES;
  }
  
  if (self->encodeEntities) {
    /* should use the HTML encoding routine (htmlEncodeEntities) ??? */
      
    chars = xmlEncodeEntitiesReentrant(self->doc, _node->content);
  }
  else
    chars = _node->content;
  
  if (chars == NULL) {
    [self->contentHandler characters:&c length:0];
    return YES;
  }
  if ((len = strlen((char *)chars)) == 0) {
    unichar c = '\0';
    [self->contentHandler characters:&c length:0];
    return YES;
  }
  
  {
    void *data, *ts;
    
    data = ts = calloc(len + 2, sizeof(unichar)); /* GC ?! */
  
    if (_UTF8ToUTF16((void *)&chars, (void *)(chars + len),
                     (void *)&ts, ts + (len * sizeof(unichar)))) {
      NSLog(@"ERROR(%s:%i): couldn't convert UTF8 to UTF16 !",
            __PRETTY_FUNCTION__, __LINE__);
      if (data) free(data);
      return NO;
    }

    len = (ts - data) / 2;
    [self->contentHandler characters:data length:len];
    
    if (data) free(data);
  }
  
  return YES;
}

- (BOOL)processCommentNode:(xmlNodePtr)_node {
  unichar c = '\0';
  
  if (self->lexicalHandler == nil)
    return YES;
  
  if (_node->content) {
    xmlChar  *chars;
    
    /* uses the HTML encoding routine !!!!!!!!!! */
    chars = xmlEncodeEntitiesReentrant(self->doc, _node->content);
    
    if (chars == NULL) {
      [self->lexicalHandler comment:&c length:0];
    }
    else {
      unsigned len;
      
      if ((len = strlen((char *)chars)) > 0) {
        void *data, *ts;
        
        data = ts = calloc(len + 1, sizeof(unichar)); /* GC ?! */
  
        if (_UTF8ToUTF16((void *)&chars, (void *)(chars + len),
                         (void *)&ts, ts + (len * sizeof(unichar)))) {
          free(data);
          NSLog(@"ERROR(%s:%i): couldn't convert UTF8 to UTF16 !",
                __PRETTY_FUNCTION__, __LINE__);
          return NO;
        }
        
        len = (ts - data) / 2;
        [self->lexicalHandler comment:data length:len];
        
        free(data);
      }
      else {
        unichar c = '\0';
        [self->lexicalHandler comment:&c length:0];
      }
    }
  }
  else
    [self->lexicalHandler comment:&c length:0];
  
  return YES;
}

- (BOOL)processDTDNode:(xmlNodePtr)node {
  /* do nothing with DTD nodes .. */
  return YES;
}
- (BOOL)processEntityNode:(xmlNodePtr)node {
  /* do nothing with entity nodes .. */
  NSLog(@"%s:%i: ignoring entity node ..", __PRETTY_FUNCTION__, __LINE__);
  return YES;
}
- (BOOL)processPINode:(xmlNodePtr)node {
  /* do nothing with PI nodes .. */
  return YES;
}

- (BOOL)processElementNode:(xmlNodePtr)node {
  NSString *tagName, *xhtmlName;
  BOOL     result;
  
  self->depth++;
  
  tagName   = xmlCharsToString(node->name);
  xhtmlName = [tagName lowercaseString];
  
  [self processAttributes:node->properties];
  
  [self->contentHandler
       startElement:xhtmlName
       namespace:self->namespaceURI
       rawName:tagName
       attributes:self->attributes];
  
  [self->attributes clear];
  
  result = [self processChildren:node->children];
  
  [self->contentHandler
       endElement:xhtmlName
       namespace:self->namespaceURI
       rawName:tagName];
  
  self->depth--;
  
  [tagName release];
  return result;
}

- (BOOL)processChildren:(xmlNodePtr)children {
  xmlNodePtr node;
  
  if (children == NULL)
    return YES;
  
  for (node = children; node; node = node->next) {
    [self processNode:node];
  }
  
  return YES;
}

- (BOOL)processNode:(xmlNodePtr)_node {
  switch(_node->type) {
    case XML_ELEMENT_NODE:
      return [self processElementNode:_node];

    case XML_ATTRIBUTE_NODE:
      NSLog(@"invalid place for attribute-node !");
      return NO;
      
    case HTML_TEXT_NODE:
      return [self processTextNode:_node];

    case XML_CDATA_SECTION_NODE:
      return [self processTextNode:_node];
      
    case HTML_ENTITY_REF_NODE:
      return [self processEntityRefNode:_node];

    case XML_ENTITY_NODE:
      return [self processEntityNode:_node];
      
    case XML_PI_NODE:
      return [self processPINode:_node];
      
    case HTML_COMMENT_NODE:
      return [self processCommentNode:_node];
      
    case XML_HTML_DOCUMENT_NODE:
      return [self processDocumentNode:_node];
      
    case XML_DTD_NODE:
      return [self processDTDNode:_node];
    
    default:
      NSLog(@"WARNING: UNKNOWN node type %i\n", _node->type);
      break;
  }
  return NO;
}

- (BOOL)walkDocumentTree:(xmlDocPtr)_doc {
  int  type;
  BOOL result;
  
  type = ((xmlDocPtr)self->doc)->type;
  ((xmlDocPtr)self->doc)->type = XML_HTML_DOCUMENT_NODE;
  
  result = [self processNode:(xmlNodePtr)self->doc];
  
  ((xmlDocPtr)self->doc)->type = type;
  
  return result;
}

/* callbacks */

static SaxParseException *
mkException(libxmlHTMLSAXDriver *self, NSString *key,
            const char *msg, va_list va)
{
  NSString          *s, *reason;
  NSDictionary      *ui;
  SaxParseException *e;
  int count = 0, i;
  id  keys[7], values[7];
  id  tmp;
  NSRange r;

  s = [NSString stringWithCString:msg];
  s = [[[NSString alloc]
                  initWithFormat:s arguments:va]
                  autorelease];

  r = [s rangeOfString:@"\n"];
  reason = (r.length > 0)
    ? [s substringToIndex:r.location]
    : s;
  
  if ([reason length] == 0)
    reason = @"unknown reason";
  
  keys[0] = @"parser"; values[0] = self; count++;
  keys[1] = @"depth";
  values[1] = [NSNumber numberWithInt:self->depth]; count++;
  
  if ([s length] > 0) {
    keys[count]   = @"errorMessage";
    values[count] = s;
    count++;
  }

  // NSLog(@"locator: %@", self->locator);
  
  if ((i = [self->locator lineNumber]) >= 0) {
    keys[count] = @"line";
    values[count] = [NSNumber numberWithInt:i];
    count++;
  }
  if ((i = [self->locator columnNumber]) >= 0) {
    keys[count] = @"column";
    values[count] = [NSNumber numberWithInt:i];
    count++;
  }
  if ((tmp = [self->locator publicId])) {
    keys[count]   = @"publicId";
    values[count] = tmp;
    count++;
  }
  if ((tmp = [self->locator systemId])) {
    keys[count]   = @"systemId";
    values[count] = tmp;
    count++;
  }
  
  ui = [NSDictionary dictionaryWithObjects:values forKeys:keys count:count];
  
  e = (id)[SaxParseException exceptionWithName:key
                             reason:reason
                             userInfo:ui];
  return e;
}

static void warning(void *udata, const char *msg, ...) {
  va_list           args;
  SaxParseException *e;
  
  if (activeDriver == nil) {
    NSLog(@"ERROR(%s): no driver is active !", __PRETTY_FUNCTION__);
    return;
  }
  
  va_start(args, msg);
  e = mkException(activeDriver, @"SAXWarning", msg, args);
  va_end(args);
  
  [activeDriver->errorHandler warning:e];
}

static void error(void *udata, const char *msg, ...) {
  va_list           args;
  SaxParseException *e;
  
  if (!reportInvalidTags && msg != NULL) {
    if (toupper((unsigned char) msg[0]) == 'T') {
      if (strncasecmp(tagInvalidMsg, msg, strlen(tagInvalidMsg)) == 0)
        return;
    }
#if 0
    else if (toupper((unsigned char) msg[0]) == 'U') {
      if (strncasecmp(unexpectedNobrCloseMsg, msg, 
                      strlen(unexpectedNobrCloseMsg)) == 0)
        return;
      printf("MSG: '%s'\n", msg);
    }
#endif
  }
  if (!reportUnclosedEntities && msg != NULL && toupper((unsigned char) msg[0]) == 'H') {
    if (strncasecmp(unclosedEntityInvalidMsg, msg, 
                    strlen(unclosedEntityInvalidMsg)) == 0)
      return;
  }
  
  if (activeDriver == nil) {
    NSLog(@"ERROR(%s): no driver is active !", __PRETTY_FUNCTION__);
    return;
  }
  
  /* msg is a format, eg 'tag %s is invalid' */
  
  va_start(args, msg);
  e = mkException(activeDriver, @"SAXError", msg, args);
  va_end(args);
  
  [activeDriver->errorHandler error:e];
}

static void fatalError(void *udata, const char *msg, ...) {
  va_list           args;
  SaxParseException *e;
  
  if (activeDriver == nil) {
    NSLog(@"ERROR(%s): no driver is active !", __PRETTY_FUNCTION__);
    return;
  }
  
  va_start(args, msg);
  e = mkException(activeDriver, @"SAXFatalError", msg, args);
  va_end(args);
  
  [activeDriver->errorHandler fatalError:e];
}

static void setLocator(void *udata, xmlSAXLocatorPtr _locator) {
  if (activeDriver == nil) {
    NSLog(@"ERROR(%s): no driver is active !", __PRETTY_FUNCTION__);
    return;
  }
  
  [activeDriver->locator release];
  
  activeDriver->locator = [[libxmlSAXLocator alloc]
                                             initWithSaxLocator:_locator
                                             parser:activeDriver];
  activeDriver->locator->ctx = activeDriver->ctxt;
  
  [activeDriver->contentHandler setDocumentLocator:activeDriver->locator];
}

@end /* libxmlHTMLSAXDriver */

#include "unicode.h"