summaryrefslogtreecommitdiffstats
path: root/kttsd/filters/xmltransformer/xmltransformerproc.cpp
blob: 8fa9e4b19a72200881b532690262dbd9b761ac60 (plain)
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
/***************************************************** vim:set ts=4 sw=4 sts=4:
  Generic XML Transformation Filter Processing class.
  -------------------
  Copyright:
  (C) 2005 by Gary Cramblitt <garycramblitt@comcast.net>
  -------------------
  Original author: Gary Cramblitt <garycramblitt@comcast.net>

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

  This program 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 General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 ******************************************************************************/

// TQt includes.
#include <tqfile.h>
#include <tqregexp.h>

// KDE includes.
#include <tdeversion.h>
#include <kconfig.h>
#include <ktempfile.h>
#include <kstandarddirs.h>
#include <kprocess.h>
#include <kdebug.h>

// KTTS includes.
#include "filterproc.h"
#include "utils.h"

// XmlTransformer includes.
#include "xmltransformerproc.h"
#include "xmltransformerproc.moc"

/**
 * Constructor.
 */
XmlTransformerProc::XmlTransformerProc( TQObject *parent, const char *name, const TQStringList& ) :
    KttsFilterProc(parent, name)
{
    m_xsltProc = 0;
}

/**
 * Destructor.
 */
/*virtual*/ XmlTransformerProc::~XmlTransformerProc()
{
    delete m_xsltProc;
    if (!m_inFilename.isEmpty()) TQFile::remove(m_inFilename);
    if (!m_outFilename.isEmpty()) TQFile::remove(m_outFilename);
}

/**
 * Initialize the filter.
 * @param config          Settings object.
 * @param configGroup     Settings Group.
 * @return                False if filter is not ready to filter.
 *
 * Note: The parameters are for reading from kttsdrc file.  Plugins may wish to maintain
 * separate configuration files of their own.
 */
bool XmlTransformerProc::init(KConfig* config, const TQString& configGroup)
{
    // kdDebug() << "XmlTransformerProc::init: Running." << endl;
    config->setGroup( configGroup );
    m_UserFilterName = config->readEntry( "UserFilterName" );
    m_xsltFilePath = config->readEntry( "XsltFilePath" );
    m_xsltprocPath = config->readEntry( "XsltprocPath" );
    m_rootElementList = config->readListEntry( "RootElement", ',' );
    m_doctypeList = config->readListEntry( "DocType", ',' );
    m_appIdList = config->readListEntry( "AppID", ',' );
    kdDebug() << "XmlTransformerProc::init: m_xsltprocPath = " << m_xsltprocPath << endl;
    kdDebug() << "XmlTransformerProc::init: m_xsltFilePath = " << m_xsltFilePath << endl;
    return ( m_xsltFilePath.isEmpty() || m_xsltprocPath.isEmpty() );
}

/**
 * Returns True if the plugin supports asynchronous processing,
 * i.e., supports asyncConvert method.
 * @return                        True if this plugin supports asynchronous processing.
 *
 * If the plugin returns True, it must also implement @ref getState .
 * It must also emit @ref filteringFinished when filtering is completed.
 * If the plugin returns True, it must also implement @ref stopFiltering .
 * It must also emit @ref filteringStopped when filtering has been stopped.
 */
/*virtual*/ bool XmlTransformerProc::supportsAsync() { return true; }

/**
 * Convert input, returning output.
 * @param inputText         Input text.
 * @param talkerCode        TalkerCode structure for the talker that KTTSD intends to
 *                          use for synthing the text.  Useful for extracting hints about
 *                          how to filter the text.  For example, languageCode.
 * @param appId             The DCOP appId of the application that queued the text.
 *                          Also useful for hints about how to do the filtering.
 */
/*virtual*/ TQString XmlTransformerProc::convert(const TQString& inputText, TalkerCode* talkerCode,
    const TQCString& appId)
{
    // kdDebug() << "XmlTransformerProc::convert: Running." << endl;
    // If not properly configured, do nothing.
    if ( m_xsltFilePath.isEmpty() || m_xsltprocPath.isEmpty() )
    {
        kdDebug() << "XmlTransformerProc::convert: not properly configured" << endl;
        return inputText;
    }
    // Asynchronously convert and wait for completion.
    if (asyncConvert(inputText, talkerCode, appId))
    {
        waitForFinished();
        m_state = fsIdle;
        return m_text;
    } else
        return inputText;
}

/**
 * Convert input.  Runs asynchronously.
 * @param inputText         Input text.
 * @param talkerCode        TalkerCode structure for the talker that KTTSD intends to
 *                          use for synthing the text.  Useful for extracting hints about
 *                          how to filter the text.  For example, languageCode.
 * @param appId             The DCOP appId of the application that queued the text.
 *                          Also useful for hints about how to do the filtering.
 * @return                  False if the filter cannot perform the conversion.
 *
 * When conversion is completed, emits signal @ref filteringFinished.  Calling
 * program may then call @ref getOutput to retrieve converted text.  Calling
 * program must call @ref ackFinished to acknowledge the conversion.
 */
/*virtual*/ bool XmlTransformerProc::asyncConvert(const TQString& inputText, TalkerCode* /*talkerCode*/,
    const TQCString& appId)
{
    m_wasModified = false;

    // kdDebug() << "XmlTransformerProc::asyncConvert: Running." << endl;
    m_text = inputText;
    // If not properly configured, do nothing.
    if ( m_xsltFilePath.isEmpty() || m_xsltprocPath.isEmpty() )
    {
        kdDebug() << "XmlTransformerProc::asyncConvert: not properly configured." << endl;
        return false;
    }

    bool found = false;
    // If not correct XML type, or DOCTYPE, do nothing.
    if ( !m_rootElementList.isEmpty() )
    {
        // kdDebug() << "XmlTransformerProc::asyncConvert:: searching for root elements " << m_rootElementList << endl;
        for ( uint ndx=0; ndx < m_rootElementList.count(); ++ndx )
        {
            if ( KttsUtils::hasRootElement( inputText, m_rootElementList[ndx] ) )
            {
                found = true;
                break;
            }
        }
        if ( !found && m_doctypeList.isEmpty() )
        {
            kdDebug() << "XmlTransformerProc::asyncConvert: Did not find root element(s)" << m_rootElementList << endl;
            return false;
        }
    }
    if ( !found && !m_doctypeList.isEmpty() )
    {
        for ( uint ndx=0; ndx < m_doctypeList.count(); ++ndx )
        {
            if ( KttsUtils::hasDoctype( inputText, m_doctypeList[ndx] ) )
            {
                found = true;
                break;
            }
        }
        if ( !found )
        {
            // kdDebug() << "XmlTransformerProc::asyncConvert: Did not find doctype(s)" << m_doctypeList << endl;
            return false;
        }
    }

    // If appId doesn't match, return input unmolested.
    if ( !m_appIdList.isEmpty() )
    {
        TQString appIdStr = appId;
        // kdDebug() << "XmlTransformrProc::convert: converting " << inputText << " if appId "
        //     << appId << " matches " << m_appIdList << endl;
        found = false;
        for ( uint ndx=0; ndx < m_appIdList.count(); ++ndx )
        {
            if ( appIdStr.contains(m_appIdList[ndx]) )
            {
                found = true;
                break;
            }
        }
        if ( !found )
        {
            // kdDebug() << "XmlTransformerProc::asyncConvert: Did not find appId(s)" << m_appIdList << endl;
            return false;
        }
    }

    /// Write @param text to a temporary file.
    KTempFile inFile(locateLocal("tmp", "kttsd-"), ".xml");
    m_inFilename = inFile.file()->name();
    TQTextStream* wstream = inFile.textStream();
    if (wstream == 0) {
        /// wtf...
        kdDebug() << "XmlTransformerProc::convert: Can't write to " << m_inFilename << endl;;
        return false;
    }
    // TODO: Is encoding an issue here?
    // If input does not have xml processing instruction, add it.
    if (!inputText.startsWith("<?xml")) *wstream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
    // FIXME: Temporary Fix until Konqi returns properly formatted xhtml with & coded as &amp;
    // This will change & inside a CDATA section, which is not good, and also within comments and
    // processing instructions, which is OK because we don't speak those anyway.
    TQString text = inputText;
    text.replace(TQRegExp("&(?!amp;)"),"&amp;");
    *wstream << text;
    inFile.close();
#if TDE_VERSION >= KDE_MAKE_VERSION (3,3,0)
    inFile.sync();
#endif

    // Get a temporary output file name.
    KTempFile outFile(locateLocal("tmp", "kttsd-"), ".output");
    m_outFilename = outFile.file()->name();
    outFile.close();
    // outFile.unlink();    // only activate this if necessary.

    /// Spawn an xsltproc process to apply our stylesheet to input file.
    m_xsltProc = new KProcess;
    *m_xsltProc << m_xsltprocPath;
    *m_xsltProc << "-o" << m_outFilename  << "--novalid"
            << m_xsltFilePath << m_inFilename;
    // Warning: This won't compile under KDE 3.2.  See FreeTTS::argsToStringList().
    // kdDebug() << "SSMLConvert::transform: executing command: " <<
    //     m_xsltProc->args() << endl;

    m_state = fsFiltering;
    connect(m_xsltProc, TQT_SIGNAL(processExited(KProcess*)),
            this, TQT_SLOT(slotProcessExited(KProcess*)));
    connect(m_xsltProc, TQT_SIGNAL(receivedStdout(KProcess*, char*, int)),
            this, TQT_SLOT(slotReceivedStdout(KProcess*, char*, int)));
    connect(m_xsltProc, TQT_SIGNAL(receivedStderr(KProcess*, char*, int)),
            this, TQT_SLOT(slotReceivedStderr(KProcess*, char*, int)));
    if (!m_xsltProc->start(KProcess::NotifyOnExit,
         static_cast<KProcess::Communication>(KProcess::Stdout | KProcess::Stderr)))
    {
        kdDebug() << "XmlTransformerProc::convert: Error starting xsltproc" << endl;
        m_state = fsIdle;
        return false;
    }
    return true;
}

// Process output when xsltproc exits.
void XmlTransformerProc::processOutput()
{
    TQFile::remove(m_inFilename);

    int exitStatus = 11;
    if (m_xsltProc->normalExit())
        exitStatus = m_xsltProc->exitStatus();
    else
        kdDebug() << "XmlTransformerProc::processOutput: xsltproc was killed." << endl;

    delete m_xsltProc;
    m_xsltProc = 0;

    if (exitStatus != 0)
    {
        kdDebug() << "XmlTransformerProc::processOutput: xsltproc abnormal exit.  Status = " << exitStatus << endl;
        m_state = fsFinished;
        TQFile::remove(m_outFilename);
        emit filteringFinished();
        return;
    }

    /// Read back the data that was written to /tmp/fileName.output.
    TQFile readfile(m_outFilename);
    if(!readfile.open(IO_ReadOnly)) {
        /// uhh yeah... Issues writing to the output file.
        kdDebug() << "XmlTransformerProc::processOutput: Could not read file " << m_outFilename << endl;
        m_state = fsFinished;
        emit filteringFinished();
    }
    TQTextStream rstream(&readfile);
    m_text = rstream.read();
    readfile.close();

    kdDebug() << "XmlTransformerProc::processOutput: Read file at " + m_inFilename + " and created " + m_outFilename + " based on the stylesheet at " << m_xsltFilePath << endl;

    // Clean up.
    TQFile::remove(m_outFilename);

    m_state = fsFinished;
    m_wasModified = true;
    emit filteringFinished();
}

/**
 * Waits for a previous call to asyncConvert to finish.
 */
/*virtual*/ void XmlTransformerProc::waitForFinished()
{
    if (m_xsltProc)
    {
        if (m_xsltProc->isRunning())
        {
            if ( !m_xsltProc->wait( 15 ) )
            {
                m_xsltProc->kill();
                kdDebug() << "XmlTransformerProc::waitForFinished: After waiting 15 seconds, xsltproc process seems to hung.  Killing it." << endl;
                processOutput();
            }
        }
    }
}

/**
 * Returns the state of the Filter.
 */
/*virtual*/ int XmlTransformerProc::getState() { return m_state; }

/**
 * Returns the filtered output.
 */
/*virtual*/ TQString XmlTransformerProc::getOutput() { return m_text; }

/**
 * Acknowledges the finished filtering.
 */
/*virtual*/ void XmlTransformerProc::ackFinished()
{
    m_state = fsIdle;
    m_text = TQString();
}

/**
 * Stops filtering.  The filteringStopped signal will emit when filtering
 * has in fact stopped and state returns to fsIdle;
 */
/*virtual*/ void XmlTransformerProc::stopFiltering()
{
    m_state = fsStopping;
    m_xsltProc->kill();
}

/**
 * Did this filter do anything?  If the filter returns the input as output
 * unmolested, it should return False when this method is called.
 */
/*virtual*/ bool XmlTransformerProc::wasModified() { return m_wasModified; }

void XmlTransformerProc::slotProcessExited(KProcess*)
{
    // kdDebug() << "XmlTransformerProc::slotProcessExited: xsltproc has exited." << endl;
    processOutput();
}

void XmlTransformerProc::slotReceivedStdout(KProcess*, char* /*buffer*/, int /*buflen*/)
{
    // TQString buf = TQString::fromLatin1(buffer, buflen);
    // kdDebug() << "XmlTransformerProc::slotReceivedStdout: Received from xsltproc: " << buf << endl;
}

void XmlTransformerProc::slotReceivedStderr(KProcess*, char* buffer, int buflen)
{
    TQString buf = TQString::fromLatin1(buffer, buflen);
    kdDebug() << "XmlTransformerProc::slotReceivedStderr: Received error from xsltproc: " << buf << endl;
}