~ubuntu-branches/ubuntu/precise/kde4libs/precise-proposed

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
#include <config-kdoctools.h>
#include <config.h>
#include "xslt.h"
#include "meinproc_common.h"

#include <QCoreApplication>
#include <QtCore/QString>
#include <QtCore/QFile>
#include <QtCore/QDir>
#include <QtCore/QTextCodec>
#include <QtCore/QFileInfo>
#include <QtCore/QList>

#include <kaboutdata.h>
#include <kcomponentdata.h>
#include <kcmdlineargs.h>
#include <kdebug.h>
#include <klocale.h>
#include <kstandarddirs.h>
#include <kshell.h>
#include <kurl.h>

#include <libxml/xmlversion.h>
#include <libxml/xmlmemory.h>
#include <libxml/debugXML.h>
#include <libxml/HTMLtree.h>
#include <libxml/xmlIO.h>
#include <libxml/parserInternals.h>
#include <libxslt/xsltconfig.h>
#include <libxslt/xsltInternals.h>
#include <libxslt/transform.h>
#include <libxslt/xsltutils.h>
#include <libexslt/exslt.h>

#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <unistd.h>

#ifndef _WIN32
extern "C" int xmlLoadExtDtdDefaultValue;
#endif

class MyPair {
public:
    QString word;
    int base;};

typedef QList<MyPair> PairList;

void parseEntry(PairList &list, xmlNodePtr cur, int base)
{
    if ( !cur )
        return;

    base += atoi( ( const char* )xmlGetProp(cur, ( const xmlChar* )"header") );
    if ( base > 10 ) // 10 is the maximum
        base = 10;

    /* We don't care what the top level element name is */
    cur = cur->xmlChildrenNode;
    while (cur != NULL) {

        if ( cur->type == XML_TEXT_NODE ) {
            QString words = QString::fromUtf8( ( char* )cur->content );
            const QStringList wlist = words.simplified().split( ' ',QString::SkipEmptyParts );
            for ( QStringList::ConstIterator it = wlist.begin();
                  it != wlist.end(); ++it )
            {
                MyPair m;
                m.word = *it;
                m.base = base;
                list.append( m );
            }
        } else if ( !xmlStrcmp( cur->name, (const xmlChar *) "entry") )
            parseEntry( list, cur, base );

        cur = cur->next;
    }

}

int main(int argc, char **argv) {

    // xsltSetGenericDebugFunc(stderr, NULL);

    KCmdLineOptions options;
    options.add("stylesheet <xsl>", ki18n("Stylesheet to use"));
    options.add("stdout", ki18n("Output whole document to stdout"));
    options.add("o");
    options.add("output <file>", ki18n("Output whole document to file"));
    options.add("htdig", ki18n("Create a ht://dig compatible index"));
    options.add("check", ki18n("Check the document for validity"));
    options.add("cache <file>", ki18n("Create a cache file for the document"));
    options.add("srcdir <dir>", ki18n("Set the srcdir, for kdelibs"));
    options.add("param <key>=<value>", ki18n("Parameters to pass to the stylesheet"));
    options.add("+xml", ki18n("The file to transform"));

    KAboutData aboutData( "meinproc4", "kio_help4", ki18n("XML-Translator" ),
    "$Revision$",
    ki18n("KDE Translator for XML"));

    KCmdLineArgs::init(argc, argv, &aboutData, KCmdLineArgs::CmdLineArgKDE);
    KCmdLineArgs::addCmdLineOptions( options );

    QCoreApplication app( argc, argv );
    KComponentData ins("kio_help4");
    KGlobal::locale();

    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
    if ( args->count() != 1 ) {
        args->usage();
        return ( 1 );
    }

    exsltRegisterAll();

    // Need to set SRCDIR before calling fillInstance
    QString srcdir;
    if ( args->isSet( "srcdir" ) )
        srcdir = QDir( args->getOption( "srcdir" ) ).absolutePath();
    fillInstance(ins,srcdir);

    LIBXML_TEST_VERSION

    const QString checkFilename = args->arg( 0 );
    CheckFileResult ckr = checkFile( checkFilename );
    if ( ckr != CheckFileSuccess )
    {
        if ( ckr == CheckFileDoesNotExist ) kError() << "File '" << checkFilename << "' does not exist.";
        else if ( ckr == CheckFileIsNotFile ) kError() << "'" << checkFilename << "' is not a file.";
        else if ( ckr == CheckFileIsNotReadable ) kError() << "File '" << checkFilename << "' is not readable.";
        return ( 2 );
    }

    if ( args->isSet( "check" ) ) {

        QByteArray catalogs;
        catalogs += KUrl::fromLocalFile( KStandardDirs::locate( "dtd", "customization/catalog.xml" ) ).toEncoded();

        QString exe;
#if defined( XMLLINT )
        exe = XMLLINT;
#endif
        if ( !QFileInfo( exe ).isExecutable() ) {
            exe = KStandardDirs::findExe( "xmllint" );
            if (exe.isEmpty())
                exe = KStandardDirs::locate( "exe", "xmllint" );
        }

        CheckResult cr = check( checkFilename, exe, catalogs );
        if ( cr != CheckSuccess )
        {
            if ( cr == CheckNoXmllint ) kWarning() << "couldn't find xmllint";
            return 1;
        }
    }

    xmlSubstituteEntitiesDefault(1);
    xmlLoadExtDtdDefaultValue = 1;

    QVector<const char *> params;
#ifndef Q_WS_WIN
    // libxslt parses the path given to outputFile as XPath expression which fails
    // see libxslt/xsltEvalUserParams
    // this parameter is used only by share/apps/ksgmltools2/docbook/xsl/html/math.xsl
    // and is not supported on windows yet
    if (args->isSet( "output" ) ) {
        params.append( qstrdup( "outputFile" ) );
        params.append( qstrdup( args->getOption( "output" ).toLocal8Bit() ) );
    }
#endif
    {
        const QStringList paramList = args->getOptionList( "param" );
        QStringList::ConstIterator it = paramList.begin();
        QStringList::ConstIterator end = paramList.end();
        for ( ; it != end; ++it ) {
            const QString tuple = *it;
            const int ch = tuple.indexOf( '=' );
            if ( ch == -1 ) {
                kError() << "Key-Value tuple '" << tuple << "' lacks a '='!" << endl;
                return( 2 );
            }
            params.append( qstrdup( tuple.left( ch ).toUtf8() ) );
            params.append( qstrdup( tuple.mid( ch + 1 ).toUtf8() )  );
        }
    }
    params.append( NULL );

    bool index = args->isSet( "htdig" );
    QString tss = args->getOption( "stylesheet" );
    if ( tss.isEmpty() )
        tss =  "customization/kde-chunk.xsl";
    if ( index )
        tss = "customization/htdig_index.xsl" ;

    tss = KStandardDirs::locate( "dtd", tss );
    const QString cache = args->getOption( "cache" );
    const bool usingStdOut = args->isSet( "stdout" );
    const bool usingOutput = args->isSet("output");
    const QString outputOption = args->getOption( "output" );

    if ( index ) {
        xsltStylesheetPtr style_sheet =
            xsltParseStylesheetFile((const xmlChar *)tss.toLatin1().data());

        if (style_sheet != NULL) {

            xmlDocPtr doc = xmlParseFile( QFile::encodeName( checkFilename ).constData() );

            xmlDocPtr res = xsltApplyStylesheet(style_sheet, doc, &params[0]);

            xmlFreeDoc(doc);
            xsltFreeStylesheet(style_sheet);
            if (res != NULL) {
                xmlNodePtr cur = xmlDocGetRootElement(res);
                if (!cur || xmlStrcmp(cur->name, (const xmlChar *) "entry")) {
                    fprintf(stderr,"document of the wrong type, root node != entry");
                    xmlFreeDoc(res);
                    return(1);
                }
                PairList list;
                parseEntry( list, cur, 0 );
                int wi = 0;
                for ( PairList::ConstIterator it = list.constBegin(); it != list.constEnd();
                      ++it, ++wi )
                    fprintf( stdout, "w\t%s\t%d\t%d\n", ( *it ).word.toUtf8().data(),
                             1000*wi/list.count(), ( *it ).base );

                xmlFreeDoc(res);
            } else {
                kDebug() << "couldn't parse document " << checkFilename;
            }
        } else {
            kDebug() << "couldn't parse style sheet " << tss;
        }

    } else {
        QString output = transform(checkFilename , tss, params);
        if (output.isEmpty()) {
            fprintf(stderr, "unable to parse %s\n", checkFilename.toLocal8Bit().data());
            return(1);
        }

        if ( !cache.isEmpty() ) {
            if ( !saveToCache( output, cache ) ) {
                kError() << i18n( "Could not write to cache file %1." ,  cache ) << endl;
            }
            goto end;
        }

        doOutput(output, usingStdOut, usingOutput, outputOption, true /* replaceCharset */);
    }
 end:
    xmlCleanupParser();
    xmlMemoryDump();
    return(0);
}