1/*
2 * Copyright (C) 2010 Google Inc. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 * 1. Redistributions of source code must retain the above copyright
8 *    notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 *    notice, this list of conditions and the following disclaimer in the
11 *    documentation and/or other materials provided with the distribution.
12 *
13 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
17 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
20 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
21 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
22 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
23 */
24
25#include "config.h"
26#include "TextDocumentParser.h"
27
28#include "HTMLDocument.h"
29#include "HTMLTreeBuilder.h"
30
31namespace WebCore {
32
33using namespace HTMLNames;
34
35TextDocumentParser::TextDocumentParser(HTMLDocument& document)
36    : HTMLDocumentParser(document)
37    , m_haveInsertedFakePreElement(false)
38{
39}
40
41TextDocumentParser::~TextDocumentParser()
42{
43}
44
45void TextDocumentParser::append(PassRefPtr<StringImpl> text)
46{
47    if (!m_haveInsertedFakePreElement)
48        insertFakePreElement();
49    HTMLDocumentParser::append(text);
50}
51
52void TextDocumentParser::insertFakePreElement()
53{
54    // In principle, we should create a specialized tree builder for
55    // TextDocuments, but instead we re-use the existing HTMLTreeBuilder.
56    // We create a fake token and give it to the tree builder rather than
57    // sending fake bytes through the front-end of the parser to avoid
58    // distrubing the line/column number calculations.
59    Vector<Attribute> attributes;
60    attributes.append(Attribute(styleAttr, "word-wrap: break-word; white-space: pre-wrap;"));
61    AtomicHTMLToken fakePre(HTMLToken::StartTag, preTag.localName(), attributes);
62    treeBuilder()->constructTree(&fakePre);
63
64    // Normally we would skip the first \n after a <pre> element, but we don't
65    // want to skip the first \n for text documents!
66    treeBuilder()->setShouldSkipLeadingNewline(false);
67
68    // Although Text Documents expose a "pre" element in their DOM, they
69    // act like a <plaintext> tag, so we have to force plaintext mode.
70    forcePlaintextForTextDocument();
71
72    m_haveInsertedFakePreElement = true;
73}
74
75}
76