File: toc.cpp

package info (click to toggle)
khelpcenter 4:18.04.0-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 7,720 kB
  • sloc: cpp: 5,955; xml: 249; perl: 86; makefile: 5; sh: 3
file content (319 lines) | stat: -rw-r--r-- 9,943 bytes parent folder | download
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
/*
 *  This file is part of the KDE Help Center
 *
 *  Copyright (C) 2002 Frerich Raabe (raabe@kde.org)
 *
 *  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.
 */

#include "toc.h"

#include "docentry.h"
#include "khc_debug.h"

#include <KProcess>
#include <KXmlGuiWindow>
#include <kcoreaddons_version.h>
#if KCOREADDONS_VERSION >= QT_VERSION_CHECK(5, 36, 0)
#include <docbookxslt.h>
#endif

#include <QStatusBar>

#include <QFileInfo>
#include <QTextStream>

#include <sys/stat.h>
#include <QStandardPaths>
#include <QApplication>
#include <QIcon>

using namespace KHC;

class TOCItem : public NavigatorItem
{
    public:
        TOCItem( TOC *parent, QTreeWidgetItem *parentItem, QTreeWidgetItem *after, const QString &text );

        const TOC *toc() const { return m_toc; }

    private:
        TOC *m_toc;
};

class TOCChapterItem : public TOCItem
{
    public:
        TOCChapterItem( TOC *toc, NavigatorItem *parent, QTreeWidgetItem *after, const QString &title,
                const QString &name );

        virtual QString url();

    private:
        QString m_name;
};

class TOCSectionItem : public TOCItem
{
    public:
        TOCSectionItem( TOC *toc, TOCChapterItem *parent, QTreeWidgetItem *after, const QString &title,
                const QString &name );

        virtual QString url();

    private:
        QString m_name;
};

bool TOC::m_alreadyWarned = false;

TOC::TOC( NavigatorItem *parentItem )
{
    m_parentItem = parentItem;
}

void TOC::build( const QString &file )
{
    QFileInfo fileInfo( file );
    QString fileName = fileInfo.absoluteFilePath();
#if KCOREADDONS_VERSION >= QT_VERSION_CHECK(5, 36, 0)
    const QStringList resourceDirs = KDocTools::documentationDirs();
#else
    const QStringList resourceDirs = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, "doc/HTML", QStandardPaths::LocateDirectory);
#endif
    QStringList::ConstIterator it = resourceDirs.begin();
    QStringList::ConstIterator end = resourceDirs.end();
    for ( ; it != end; ++it ) {
        if ( fileName.startsWith( *it ) ) {
            fileName.remove( 0, ( *it ).length() );
            break;
        }
    }

    QString cacheFile = fileName.replace( '/', "__" );
#ifdef Q_WS_WIN
    cacheFile = cacheFile.replace( ':', "_" );
#endif
    m_cacheFile = QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + "/help/" + cacheFile ;
    m_sourceFile = file;

    if ( cacheStatus() == NeedRebuild )
        buildCache();
    else
        fillTree();
}

TOC::CacheStatus TOC::cacheStatus() const
{
    if ( !QFile::exists( m_cacheFile ) ||
         sourceFileCTime() != cachedCTime() )
        return NeedRebuild;

    return CacheOk;
}

int TOC::sourceFileCTime() const
{
    struct stat stat_buf;
    stat( QFile::encodeName( m_sourceFile ).data(), &stat_buf );

    return stat_buf.st_ctime;
}

int TOC::cachedCTime() const
{
    QFile f( m_cacheFile );
    if ( !f.open( QIODevice::ReadOnly ) )
        return 0;

    QDomDocument doc;
    if ( !doc.setContent( &f ) )
        return 0;

    QDomComment timestamp = doc.documentElement().lastChild().toComment();

    return timestamp.data().trimmed().toInt();
}

void TOC::buildCache()
{
    KXmlGuiWindow *mainWindow = dynamic_cast<KXmlGuiWindow *>( qobject_cast<QApplication*>(qApp)->activeWindow() );

    KProcess *meinproc = new KProcess;
    connect( meinproc, SIGNAL( finished( int, QProcess::ExitStatus) ),
             this, SLOT( meinprocExited( int, QProcess::ExitStatus) ) );

    *meinproc << QStandardPaths::findExecutable("meinproc5");
    *meinproc << "--stylesheet" << QStandardPaths::locate(QStandardPaths::GenericDataLocation, "khelpcenter/table-of-contents.xslt" );
    *meinproc << "--output" << m_cacheFile;
    *meinproc << m_sourceFile;

    meinproc->setOutputChannelMode(KProcess::OnlyStderrChannel);
    meinproc->start();
    if (!meinproc->waitForStarted()) {
        khcWarning() << "could not start process" << meinproc->program();
        if (mainWindow && !m_alreadyWarned) {
            ; // add warning message box with don't display again option 
              // http://api.kde.org/4.0-api/kdelibs-apidocs/kdeui/html/classKDialog.html
            m_alreadyWarned = true;
        }
        delete meinproc;
    }
}

void TOC::meinprocExited( int exitCode, QProcess::ExitStatus exitStatus)
{
    KProcess *meinproc = static_cast<KProcess *>(sender());
    KXmlGuiWindow *mainWindow = dynamic_cast<KXmlGuiWindow *>( qobject_cast<QApplication*>(qApp)->activeWindow() );

    if ( exitStatus == QProcess::CrashExit || exitCode != 0 ) {
        khcWarning() << "running" << meinproc->program() << "failed with exitCode" << exitCode;
        khcWarning() << "stderr output:" << meinproc->readAllStandardError();
        if (mainWindow && !m_alreadyWarned) {
            ; // add warning message box with don't display again option 
              // http://api.kde.org/4.0-api/kdelibs-apidocs/kdeui/html/classKDialog.html
            m_alreadyWarned = true;
        }
        delete meinproc;
        return;
    }

    delete meinproc;

    // add a timestamp to the meinproc4 created xml file
    QFile f( m_cacheFile );
    if ( !f.open( QIODevice::ReadWrite ) )
        return;

    QDomDocument doc;
    if ( !doc.setContent( &f ) )
        return;

    QDomComment timestamp = doc.createComment( QString::number( sourceFileCTime() ) );
    doc.documentElement().appendChild( timestamp );

    // write back updated xml content 
    f.seek( 0 );
    QTextStream stream( &f );
    stream.setCodec( "UTF-8" );
#ifdef Q_WS_WIN
    /*
      the problem that on german systems umlauts are displayed as '?' for unknown (Qt'r related ?) reasons
      is caused by wrong encoding type conversations and has been fixed in kdelibs/kdoctools
      To have propper encoding tags in the xml file, QXmlDocument::save() is used. 
    */
    doc.save(stream, 1, QDomNode::EncodingFromTextStream);

#else
    stream << doc.toString();
#endif
    f.close();
    fillTree();
}

void TOC::fillTree()
{
    QFile f( m_cacheFile );
    if ( !f.open( QIODevice::ReadOnly ) )
        return;

    QDomDocument doc;
    if ( !doc.setContent( &f ) )
        return;

    TOCChapterItem *chapItem = 0;
    QDomNodeList chapters = doc.documentElement().elementsByTagName( "chapter" );
    for ( int chapterCount = 0; chapterCount < chapters.count(); chapterCount++ ) {
        QDomElement chapElem = chapters.item( chapterCount ).toElement();
        QDomElement chapTitleElem = childElement( chapElem, QLatin1String( "title" ) );
        QString chapTitle = chapTitleElem.text().simplified();
        QDomElement chapRefElem = childElement( chapElem, QLatin1String( "anchor" ) );
        QString chapRef = chapRefElem.text().trimmed();

        chapItem = new TOCChapterItem( this, m_parentItem, chapItem, chapTitle, chapRef );

        TOCSectionItem *sectItem = 0;
        QDomNodeList sections = chapElem.elementsByTagName( "section" );
        for ( int sectCount = 0; sectCount < sections.count(); sectCount++ ) {
            QDomElement sectElem = sections.item( sectCount ).toElement();
            QDomElement sectTitleElem = childElement( sectElem, QLatin1String( "title" ) );
            QString sectTitle = sectTitleElem.text().simplified();
            QDomElement sectRefElem = childElement( sectElem, QLatin1String( "anchor" ) );
            QString sectRef = sectRefElem.text().trimmed();

            sectItem = new TOCSectionItem( this, chapItem, sectItem, sectTitle, sectRef );
        }
    }
}

QDomElement TOC::childElement( const QDomElement &element, const QString &name )
{
    QDomElement e;
    for ( e = element.firstChild().toElement(); !e.isNull(); e = e.nextSibling().toElement() )
        if ( e.tagName() == name )
            break;
    return e;
}

void TOC::slotItemSelected( QTreeWidgetItem *item )
{
    TOCItem *tocItem;
    if ( ( tocItem = dynamic_cast<TOCItem *>( item ) ) )
        emit itemSelected( tocItem->entry()->url() );

    item->setExpanded( !item->isExpanded() );
}

TOCItem::TOCItem( TOC *toc, QTreeWidgetItem *parentItem, QTreeWidgetItem *after, const QString &text )
    : NavigatorItem( new DocEntry( text ), parentItem, after )
{
        setAutoDeleteDocEntry( true );
    m_toc = toc;
}

TOCChapterItem::TOCChapterItem( TOC *toc, NavigatorItem *parent, QTreeWidgetItem *after,
                const QString &title, const QString &name )
    : TOCItem( toc, parent, after, title ),
    m_name( name )
{
    setExpanded( false );
    entry()->setUrl(url());
}

QString TOCChapterItem::url()
{
    return QLatin1String("help:") + toc()->application() + QLatin1Char('/') + m_name 
               + QLatin1String(".html");
}

TOCSectionItem::TOCSectionItem( TOC *toc, TOCChapterItem *parent, QTreeWidgetItem *after,
                const QString &title, const QString &name )
    : TOCItem( toc, parent, after, title ),
    m_name( name )
{
    setIcon( 0, QIcon::fromTheme( "text-plain" ) );
    entry()->setUrl(url());
}

QString TOCSectionItem::url()
{
    if ( static_cast<TOCSectionItem *>( parent()->child(0) ) == this )
        return static_cast<TOCChapterItem *>( parent() )->url() + '#' + m_name;

    return "help:" + toc()->application() + '/' + m_name + ".html";
}


// vim:ts=2:sw=2:et