summaryrefslogtreecommitdiffstats
path: root/tools/assistant/lib/qhelpsearchindexreader_default.cpp
blob: 1ec0a212ec17833aadf46a82bbae5789df2ffc08 (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
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
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Assistant of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qhelpenginecore.h"
#include "qhelpsearchindexreader_default_p.h"

#include <QtCore/QDir>
#include <QtCore/QUrl>
#include <QtCore/QFile>
#include <QtCore/QVariant>
#include <QtCore/QFileInfo>
#include <QtCore/QDataStream>
#include <QtCore/QTextStream>

QT_BEGIN_NAMESPACE

namespace qt {
    namespace fulltextsearch {
        namespace std {

namespace {
    QStringList split( const QString &str )
    {
        QStringList lst;
        int j = 0;
        int i = str.indexOf(QLatin1Char('*'), j );

        if (str.startsWith(QLatin1String("*")))
            lst << QLatin1String("*");

        while ( i != -1 ) {
            if ( i > j && i <= (int)str.length() ) {
                lst << str.mid( j, i - j );
                lst << QLatin1String("*");
            }
            j = i + 1;
            i = str.indexOf(QLatin1Char('*'), j );
        }

        int l = str.length() - 1;
        if ( str.mid( j, l - j + 1 ).length() > 0 )
            lst << str.mid( j, l - j + 1 );

        return lst;
    }
}


Reader::Reader()
    : indexPath(QString())
    , indexFile(QString())
    , documentFile(QString())
{
    termList.clear();
    indexTable.clear();
    searchIndexTable.clear();
}

Reader::~Reader()
{
    reset();
    searchIndexTable.clear();
}

bool Reader::readIndex()
{
    if (indexTable.contains(indexFile))
        return true;

    QFile idxFile(indexFile);
    if (!idxFile.open(QFile::ReadOnly))
        return false;

    QString key;
    int numOfDocs;
    EntryTable entryTable;
    QVector<Document> docs;
    QDataStream dictStream(&idxFile);
    while (!dictStream.atEnd()) {
        dictStream >> key;
        dictStream >> numOfDocs;
        docs.resize(numOfDocs);
        dictStream >> docs;
        entryTable.insert(key, new Entry(docs));
    }
    idxFile.close();

    if (entryTable.isEmpty())
        return false;

    QFile docFile(documentFile);
    if (!docFile.open(QFile::ReadOnly))
        return false;

    QString title, url;
    DocumentList documentList;
    QDataStream docStream(&docFile);
    while (!docStream.atEnd()) {
        docStream >> title;
        docStream >> url;
        documentList.append(QStringList(title) << url);
    }
    docFile.close();

    if (documentList.isEmpty()) {
        cleanupIndex(entryTable);
        return false;
    }

    indexTable.insert(indexFile, Index(entryTable, documentList));
    return true;
}

bool Reader::initCheck() const
{
    return !searchIndexTable.isEmpty();
}

void Reader::setIndexPath(const QString &path)
{
    indexPath = path;
}

void Reader::filterFilesForAttributes(const QStringList &attributes)
{
    searchIndexTable.clear();
    for(IndexTable::ConstIterator it = indexTable.begin(); it != indexTable.end(); ++it) {
        const QString fileName = it.key();
        bool containsAll = true;
        QStringList split = fileName.split(QLatin1String("@"));
        foreach (const QString attribute, attributes) {
            if (!split.contains(attribute, Qt::CaseInsensitive)) {
                containsAll = false;
                break;
            }
        }

        if (containsAll)
            searchIndexTable.insert(fileName, it.value());
    }
}

void Reader::setIndexFile(const QString &namespaceName, const QString &attributes)
{
    QString extention = namespaceName + QLatin1String("@") + attributes;
    indexFile = indexPath + QLatin1String("/indexdb40.") + extention;
    documentFile = indexPath + QLatin1String("/indexdoc40.") + extention;
}

bool Reader::splitSearchTerm(const QString &searchTerm, QStringList *terms,
                                  QStringList *termSeq, QStringList *seqWords)
{
    QString term = searchTerm;

    term = term.simplified();
    term = term.replace(QLatin1String("\'"), QLatin1String("\""));
    term = term.replace(QLatin1String("`"), QLatin1String("\""));
    term = term.replace(QLatin1String("-"), QLatin1String(" "));
    term = term.replace(QRegExp(QLatin1String("\\s[\\S]?\\s")), QLatin1String(" "));

    *terms = term.split(QLatin1Char(' '));
    QStringList::iterator it = terms->begin();
    for (; it != terms->end(); ++it) {
        (*it) = (*it).simplified();
        (*it) = (*it).toLower();
        (*it) = (*it).replace(QLatin1String("\""), QLatin1String(""));
    }

    if (term.contains(QLatin1Char('\"'))) {
        if ((term.count(QLatin1Char('\"')))%2 == 0) {
            int beg = 0;
            int end = 0;
            QString s;
            beg = term.indexOf(QLatin1Char('\"'), beg);
            while (beg != -1) {
                beg++;
                end = term.indexOf(QLatin1Char('\"'), beg);
                s = term.mid(beg, end - beg);
                s = s.toLower();
                s = s.simplified();
                if (s.contains(QLatin1Char('*'))) {
                    qWarning("Full Text Search, using a wildcard within phrases is not allowed.");
                    return false;
                }
                *seqWords += s.split(QLatin1Char(' '));
                *termSeq << s;
                beg = term.indexOf(QLatin1Char('\"'), end + 1);
            }
        } else {
            qWarning("Full Text Search, the closing quotation mark is missing.");
            return false;
        }
    }

    return true;
}

void Reader::searchInIndex(const QStringList &terms)
{
    foreach (const QString term, terms) {
        QVector<Document> documents;

        for(IndexTable::ConstIterator it = searchIndexTable.begin();
            it != searchIndexTable.end(); ++it) {
            EntryTable entryTable = it.value().first;
            DocumentList documentList = it.value().second;

            if (term.contains(QLatin1Char('*')))
                documents = setupDummyTerm(getWildcardTerms(term, entryTable), entryTable);
            else if (entryTable.value(term))
                documents = entryTable.value(term)->documents;
            else
                continue;

            if (!documents.isEmpty()) {
                DocumentInfo info;
                QString title, url;
                QVector<DocumentInfo> documentsInfo;
                foreach(const Document doc, documents) {
                    info.docNumber = doc.docNumber;
                    info.frequency = doc.frequency;
                    info.documentUrl = documentList.at(doc.docNumber).at(1);
                    info.documentTitle = documentList.at(doc.docNumber).at(0);
                    documentsInfo.append(info);
                }

                bool found = false;
                for(QList<TermInfo>::Iterator tit = termList.begin();
                    tit != termList.end(); ++tit) {
                    TermInfo *t = &(*tit);
                    if(t->term == term) {
                        t->documents += documentsInfo;
                        t->frequency += documentsInfo.count();
                        found = true; break;
                    }
                }
                if (!found)
                    termList.append(TermInfo(term, documentsInfo.count(), documentsInfo));
            }
        }
    }
    qSort(termList);
}

QVector<DocumentInfo> Reader::hits()
{
    QVector<DocumentInfo> documents;
    if (!termList.count())
        return documents;

    documents = termList.takeFirst().documents;
    for(QList<TermInfo>::Iterator it = termList.begin(); it != termList.end(); ++it) {
        TermInfo *t = &(*it);
        QVector<DocumentInfo> docs = t->documents;
        for(QVector<DocumentInfo>::Iterator minDoc_it = documents.begin();
            minDoc_it != documents.end(); ) {
            bool found = false;
            for (QVector<DocumentInfo>::ConstIterator doc_it = docs.constBegin();
                doc_it != docs.constEnd(); ++doc_it ) {
                if ( (*minDoc_it).docNumber == (*doc_it).docNumber ) {
                    (*minDoc_it).frequency += (*doc_it).frequency;
                    found = true;
                    break;
                }
            }
            if (!found)
                minDoc_it = documents.erase(minDoc_it);
            else
                ++minDoc_it;
        }
    }

    qSort(documents);
    return documents;
}

bool Reader::searchForPattern(const QStringList &patterns, const QStringList &words,
                                   const QByteArray &data)
{
    if (data.isEmpty())
        return false;

    for(QHash<QString, PosEntry*>::ConstIterator mit =
        miniIndex.begin(); mit != miniIndex.end(); ++mit) {
            delete mit.value();
    }
    miniIndex.clear();

    wordNum = 3;
    QStringList::ConstIterator cIt = words.begin();
    for ( ; cIt != words.end(); ++cIt )
        miniIndex.insert(*cIt, new PosEntry(0));

    QTextStream s(data);
    QString text = s.readAll();
    bool valid = true;
    const QChar *buf = text.unicode();
    QChar str[64];
    QChar c = buf[0];
    int j = 0;
    int i = 0;
    while ( j < text.length() ) {
        if ( c == QLatin1Char('<') || c == QLatin1Char('&') ) {
            valid = false;
            if ( i > 1 )
                buildMiniIndex( QString(str,i) );
            i = 0;
            c = buf[++j];
            continue;
        }
        if ( ( c == QLatin1Char('>') || c == QLatin1Char(';') ) && !valid ) {
            valid = true;
            c = buf[++j];
            continue;
        }
        if ( !valid ) {
            c = buf[++j];
            continue;
        }
        if ( ( c.isLetterOrNumber() || c == QLatin1Char('_') ) && i < 63 ) {
            str[i] = c.toLower();
            ++i;
        } else {
            if ( i > 1 )
                buildMiniIndex( QString(str,i) );
            i = 0;
        }
        c = buf[++j];
    }
    if ( i > 1 )
        buildMiniIndex( QString(str,i) );

    QStringList::ConstIterator patIt = patterns.begin();
    QStringList wordLst;
    QList<uint> a, b;
    QList<uint>::iterator aIt;
    for ( ; patIt != patterns.end(); ++patIt ) {
        wordLst = (*patIt).split(QLatin1Char(' '));
        a = miniIndex[ wordLst[0] ]->positions;
        for ( int j = 1; j < (int)wordLst.count(); ++j ) {
            b = miniIndex[ wordLst[j] ]->positions;
            aIt = a.begin();
            while ( aIt != a.end() ) {
                if ( b.contains( *aIt + 1 )) {
                    (*aIt)++;
                    ++aIt;
                } else {
                    aIt = a.erase( aIt );
                }
            }
        }
    }
    if ( a.count() )
        return true;
    return false;
}

QVector<Document> Reader::setupDummyTerm(const QStringList &terms,
                                              const EntryTable &entryTable)
{
    QList<Term> termList;
    for (QStringList::ConstIterator it = terms.begin(); it != terms.end(); ++it) {
        if (entryTable.value(*it)) {
            Entry *e = entryTable.value(*it);
            termList.append(Term(*it, e->documents.count(), e->documents ) );
        }
    }
    QVector<Document> maxList(0);
    if ( !termList.count() )
        return maxList;
    qSort(termList);

    maxList = termList.takeLast().documents;
    for(QList<Term>::Iterator it = termList.begin(); it != termList.end(); ++it) {
        Term *t = &(*it);
        QVector<Document> docs = t->documents;
        for (QVector<Document>::iterator docIt = docs.begin(); docIt != docs.end(); ++docIt ) {
            if ( maxList.indexOf( *docIt ) == -1 )
                maxList.append( *docIt );
        }
    }
    return maxList;
}

QStringList Reader::getWildcardTerms(const QString &term,
                                          const EntryTable &entryTable)
{
    QStringList lst;
    QStringList terms = split(term);
    QStringList::Iterator iter;

    for(EntryTable::ConstIterator it = entryTable.begin();
        it != entryTable.end(); ++it) {
        int index = 0;
        bool found = false;
        QString text( it.key() );
        for ( iter = terms.begin(); iter != terms.end(); ++iter ) {
            if ( *iter == QLatin1String("*") ) {
                found = true;
                continue;
            }
            if ( iter == terms.begin() && (*iter)[0] != text[0] ) {
                found = false;
                break;
            }
            index = text.indexOf( *iter, index );
            if ( *iter == terms.last() && index != (int)text.length()-1 ) {
                index = text.lastIndexOf( *iter );
                if ( index != (int)text.length() - (int)(*iter).length() ) {
                    found = false;
                    break;
                }
            }
            if ( index != -1 ) {
                found = true;
                index += (*iter).length();
                continue;
            } else {
                found = false;
                break;
            }
        }
        if (found)
            lst << text;
    }

    return lst;
}

void Reader::buildMiniIndex(const QString &string)
{
    if (miniIndex[string])
        miniIndex[string]->positions.append(wordNum);
    ++wordNum;
}

void Reader::reset()
{
    for(IndexTable::Iterator it = indexTable.begin();
        it != indexTable.end(); ++it) {
        cleanupIndex(it.value().first);
        it.value().second.clear();
    }
}

void Reader::cleanupIndex(EntryTable &entryTable)
{
    for(EntryTable::ConstIterator it =
        entryTable.begin(); it != entryTable.end(); ++it) {
            delete it.value();
    }

    entryTable.clear();
}


QHelpSearchIndexReaderDefault::QHelpSearchIndexReaderDefault()
    : QHelpSearchIndexReader()
{
    // nothing todo
}

QHelpSearchIndexReaderDefault::~QHelpSearchIndexReaderDefault()
{
}

void QHelpSearchIndexReaderDefault::run()
{
    mutex.lock();

    if (m_cancel) {
        mutex.unlock();
        return;
    }

    const QList<QHelpSearchQuery> &queryList = this->m_query;
    const QLatin1String key("DefaultSearchNamespaces");
    const QString collectionFile(this->m_collectionFile);
    const QString indexPath = m_indexFilesFolder;

    mutex.unlock();

    QString queryTerm;
    foreach (const QHelpSearchQuery query, queryList) {
        if (query.fieldName == QHelpSearchQuery::DEFAULT) {
            queryTerm = query.wordList.at(0);
            break;
        }
    }

    if (queryTerm.isEmpty())
        return;

    QHelpEngineCore engine(collectionFile, 0);
    if (!engine.setupData())
        return;

    const QStringList registeredDocs = engine.registeredDocumentations();
    const QStringList indexedNamespaces = engine.customValue(key).toString().
        split(QLatin1String("|"), QString::SkipEmptyParts);

    emit searchingStarted();

    // setup the reader
    m_reader.setIndexPath(indexPath);
    foreach(const QString namespaceName, registeredDocs) {
        mutex.lock();
        if (m_cancel) {
            mutex.unlock();
            searchingFinished(0);   // TODO: check this ???
            return;
        }
        mutex.unlock();

        const QList<QStringList> attributeSets =
            engine.filterAttributeSets(namespaceName);

        foreach (QStringList attributes, attributeSets) {
            // read all index files
            m_reader.setIndexFile(namespaceName, attributes.join(QLatin1String("@")));
            if (!m_reader.readIndex()) {
                qWarning("Full Text Search, could not read file for namespace: %s.",
                    namespaceName.toUtf8().constData());
            }
        }
    }

    // get the current filter attributes and minimize the index files table
    m_reader.filterFilesForAttributes(engine.filterAttributes(engine.currentFilter()));

    hitList.clear();
    QStringList terms, termSeq, seqWords;
    if (m_reader.initCheck() && // check if we could read anything
        m_reader.splitSearchTerm(queryTerm, &terms, &termSeq, &seqWords) ) {

        // search for term(s)
        m_reader.searchInIndex(terms);    // TODO: should this be interruptible as well ???

        QVector<DocumentInfo> hits = m_reader.hits();
        if (!hits.isEmpty()) {
            if (termSeq.isEmpty()) {
                foreach (const DocumentInfo docInfo, hits) {
                    mutex.lock();
                    if (m_cancel) {
                        mutex.unlock();
                        searchingFinished(0);   // TODO: check this, speed issue while locking???
                        return;
                    }
                    mutex.unlock();
                    hitList.append(qMakePair(docInfo.documentTitle, docInfo.documentUrl));
                }
            } else {
                foreach (const DocumentInfo docInfo, hits) {
                    mutex.lock();
                    if (m_cancel) {
                        mutex.unlock();
                        searchingFinished(0);   // TODO: check this, speed issue while locking???
                        return;
                    }
                    mutex.unlock();

                    if (m_reader.searchForPattern(termSeq, seqWords, engine.fileData(docInfo.documentUrl))) // TODO: should this be interruptible as well ???
                        hitList.append(qMakePair(docInfo.documentTitle, docInfo.documentUrl));
                }
            }
        }
    }

    emit searchingFinished(hitList.count());
}

        }   // namespace std
    }   // namespace fulltextsearch
}   // namespace qt

QT_END_NAMESPACE