krquery.cpp 24.1 KB
Newer Older
Rafi Yanai's avatar
Rafi Yanai committed
1 2 3 4 5
/***************************************************************************
                                 krquery.cpp
                             -------------------
    copyright            : (C) 2001 by Shie Erlich & Rafi Yanai
    email                : krusader@users.sourceforge.net
Csaba Karai's avatar
 
Csaba Karai committed
6
    web site             : http://krusader.sourceforge.net
Rafi Yanai's avatar
Rafi Yanai committed
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
 ---------------------------------------------------------------------------
  Description
 ***************************************************************************

  A

     db   dD d8888b. db    db .d8888.  .d8b.  d8888b. d88888b d8888b.
     88 ,8P' 88  `8D 88    88 88'  YP d8' `8b 88  `8D 88'     88  `8D
     88,8P   88oobY' 88    88 `8bo.   88ooo88 88   88 88ooooo 88oobY'
     88`8b   88`8b   88    88   `Y8b. 88~~~88 88   88 88~~~~~ 88`8b
     88 `88. 88 `88. 88b  d88 db   8D 88   88 88  .8D 88.     88 `88.
     YP   YD 88   YD ~Y8888P' `8888Y' YP   YP Y8888D' Y88888P 88   YD

                                                     S o u r c e    F i l e

 ***************************************************************************
 *                                                                         *
 *   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.                                   *
 *                                                                         *
 ***************************************************************************/

#include "krquery.h"
Csaba Karai's avatar
 
Csaba Karai committed
32

33
#include <QtCore/QMetaMethod>
Fathi Boudra's avatar
Fathi Boudra committed
34 35
#include <QtCore/QTextCodec>
#include <QtCore/QRegExp>
Fathi Boudra's avatar
Fathi Boudra committed
36 37
#include <QtCore/QFile>

Simon Persson's avatar
Simon Persson committed
38
#include <KI18n/KLocalizedString>
39 40
#include <KIOWidgets/KUrlCompletion>
#include <KIO/Job>
41
#include <KIOCore/KFileItem>
Fathi Boudra's avatar
Fathi Boudra committed
42 43 44 45

#include "vfs.h"
#include "krarchandler.h"
#include "krpermhandler.h"
46 47

#define  STATUS_SEND_DELAY     250
48
#define  MAX_LINE_LEN          1000
Rafi Yanai's avatar
Rafi Yanai committed
49 50

// set the defaults
Fathi Boudra's avatar
Fathi Boudra committed
51 52 53 54 55 56 57 58 59 60 61 62 63 64
KRQuery::KRQuery(): QObject(), matchesCaseSensitive(true), bNull(true),
        contain(QString()), containCaseSensetive(true),
        containWholeWord(false), containRegExp(false), containOnRemote(false),
        minSize(0), maxSize(0), newerThen(0), olderThen(0),
        owner(QString()), group(QString()), perm(QString()),
        type(QString()), inArchive(false), recurse(true),
        followLinksP(true), receivedBuffer(0), receivedBufferLen(0), processEventsConnected(0),
        codec(QTextCodec::codecForLocale())
{
    QChar ch = '\n';
    QTextCodec::ConverterState state(QTextCodec::IgnoreHeader);
    encodedEnterArray = codec->fromUnicode(&ch, 1, &state);
    encodedEnter = encodedEnterArray.data();
    encodedEnterLen = encodedEnterArray.size();
65
}
Rafi Yanai's avatar
Rafi Yanai committed
66

Csaba Karai's avatar
 
Csaba Karai committed
67
// set the defaults
Fathi Boudra's avatar
Fathi Boudra committed
68 69 70 71 72 73 74 75 76 77 78 79 80 81
KRQuery::KRQuery(const QString &name, bool matchCase) : QObject(),
        bNull(true), contain(QString()), containCaseSensetive(true),
        containWholeWord(false), containRegExp(false), containOnRemote(false),
        minSize(0), maxSize(0), newerThen(0), olderThen(0),
        owner(QString()), group(QString()), perm(QString()),
        type(QString()), inArchive(false), recurse(true),
        followLinksP(true), receivedBuffer(0), receivedBufferLen(0), processEventsConnected(0),
        codec(QTextCodec::codecForLocale())
{
    QChar ch = '\n';
    QTextCodec::ConverterState state(QTextCodec::IgnoreHeader);
    encodedEnterArray = codec->fromUnicode(&ch, 1, &state);
    encodedEnter = encodedEnterArray.data();
    encodedEnterLen = encodedEnterArray.size();
Csaba Karai's avatar
 
Csaba Karai committed
82

Fathi Boudra's avatar
Fathi Boudra committed
83
    setNameFilter(name, matchCase);
84 85
}

Fathi Boudra's avatar
Fathi Boudra committed
86 87 88
KRQuery::KRQuery(const KRQuery & that) : QObject(), receivedBuffer(0), receivedBufferLen(0), processEventsConnected(0)
{
    *this = that;
89 90
}

Fathi Boudra's avatar
Fathi Boudra committed
91 92 93 94 95
KRQuery::~KRQuery()
{
    if (receivedBuffer)
        delete []receivedBuffer;
    receivedBuffer = 0;
96 97
}

Fathi Boudra's avatar
Fathi Boudra committed
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
KRQuery& KRQuery::operator=(const KRQuery & old)
{
    matches = old.matches;
    excludes = old.excludes;
    includedDirs = old.includedDirs;
    excludedDirs = old.excludedDirs;
    matchesCaseSensitive = old.matchesCaseSensitive;
    bNull = old.bNull;
    contain = old.contain;
    containCaseSensetive = old.containCaseSensetive;
    containWholeWord = old.containWholeWord;
    containRegExp = old.containRegExp;
    containOnRemote = old.containOnRemote;
    minSize = old.minSize;
    maxSize = old.maxSize;
    newerThen = old.newerThen;
    olderThen = old.olderThen;
    owner = old.owner;
    group = old.group;
    perm = old.perm;
    type = old.type;
    customType = old.customType;
    inArchive = old.inArchive;
    recurse = old.recurse;
    followLinksP = old.followLinksP;
    whereToSearch = old.whereToSearch;
    whereNotToSearch = old.whereNotToSearch;
    origFilter = old.origFilter;

    codec = old.codec;

    encodedEnterArray = old.encodedEnterArray;
    encodedEnter = encodedEnterArray.data();
    encodedEnterLen = encodedEnterArray.size();

    return *this;
}

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
void KRQuery::load(KConfigGroup cfg)
{
    *this = KRQuery(); // reset parameters first

    if(cfg.readEntry("IsNull", true))
        return;

#define LOAD(key, var) (var = cfg.readEntry(key, var))
    LOAD("Matches", matches);
    LOAD("Excludes", excludes);
    LOAD("IncludedDirs", includedDirs);
    LOAD("ExcludedDirs", excludedDirs);
    LOAD("MatchesCaseSensitive", matchesCaseSensitive);
    LOAD("Contain", contain);
    LOAD("ContainCaseSensetive", containCaseSensetive);
    LOAD("ContainWholeWord", containWholeWord);
    LOAD("ContainRegExp", containRegExp);
    LOAD("ContainOnRemote", containOnRemote);
    LOAD("MinSize", minSize);
    LOAD("MaxSize", maxSize);
    newerThen = QDateTime::fromString(cfg.readEntry("NewerThan", QDateTime::fromTime_t(newerThen).toString())).toTime_t();
    olderThen = QDateTime::fromString(cfg.readEntry("OlderThan", QDateTime::fromTime_t(olderThen).toString())).toTime_t();
    LOAD("Owner", owner);
    LOAD("Group", group);
    LOAD("Perm", perm);
    LOAD("Type", type);
    LOAD("CustomType", customType);
    LOAD("InArchive", inArchive);
    LOAD("Recurse", recurse);
    LOAD("FollowLinks", followLinksP);
166 167 168
    // KF5 TODO?
    //LOAD("WhereToSearch", whereToSearch);
    //LOAD("WhereNotToSearch", whereNotToSearch);
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
    LOAD("OrigFilter", origFilter);

    codec = QTextCodec::codecForName(cfg.readEntry("Codec", codec->name()));
    if(!codec)
        codec = QTextCodec::codecForLocale();

    LOAD("EncodedEnterArray", encodedEnterArray);
    encodedEnter = encodedEnterArray.data();
    encodedEnterLen = encodedEnterArray.size();
#undef LOAD

    bNull = false;
}

void KRQuery::save(KConfigGroup cfg)
{
    cfg.writeEntry("IsNull", bNull);

    if(bNull)
        return;

    cfg.writeEntry("Matches", matches);
    cfg.writeEntry("Excludes", excludes);
    cfg.writeEntry("IncludedDirs", includedDirs);
    cfg.writeEntry("ExcludedDirs", excludedDirs);
    cfg.writeEntry("MatchesCaseSensitive", matchesCaseSensitive);
    cfg.writeEntry("Contain", contain);
    cfg.writeEntry("ContainCaseSensetive", containCaseSensetive);
    cfg.writeEntry("ContainWholeWord", containWholeWord);
    cfg.writeEntry("ContainRegExp", containRegExp);
    cfg.writeEntry("ContainOnRemote", containOnRemote);
    cfg.writeEntry("MinSize", minSize);
    cfg.writeEntry("MaxSize", maxSize);
    cfg.writeEntry("NewerThan", QDateTime::fromTime_t(newerThen).toString());
    cfg.writeEntry("OlderThan", QDateTime::fromTime_t(olderThen).toString());
    cfg.writeEntry("Owner", owner);
    cfg.writeEntry("Group", group);
    cfg.writeEntry("Perm", perm);
    cfg.writeEntry("Type", type);
    cfg.writeEntry("CustomType", customType);
    cfg.writeEntry("InArchive", inArchive);
    cfg.writeEntry("Recurse", recurse);
    cfg.writeEntry("FollowLinks", followLinksP);
212 213 214
    // KF5 TODO?
    //cfg.writeEntry("WhereToSearch", whereToSearch);
    //cfg.writeEntry("WhereNotToSearch", whereNotToSearch);
215 216 217 218 219 220 221 222
    cfg.writeEntry("OrigFilter", origFilter);

    cfg.writeEntry("Codec", codec->name());
    cfg.writeEntry("EncodedEnterArray", encodedEnterArray);
    cfg.writeEntry("EncodedEnter", encodedEnter);
    cfg.writeEntry("EncodedEnterLen", encodedEnterLen);
}

223
void KRQuery::connectNotify(const QMetaMethod &signal)
Fathi Boudra's avatar
Fathi Boudra committed
224
{
225
    if (signal == QMetaMethod::fromSignal(&KRQuery::processEvents))
Fathi Boudra's avatar
Fathi Boudra committed
226
        processEventsConnected++;
227 228
}

229
void KRQuery::disconnectNotify(const QMetaMethod &signal)
Fathi Boudra's avatar
Fathi Boudra committed
230
{
231
    if (signal == QMetaMethod::fromSignal(&KRQuery::processEvents))
Fathi Boudra's avatar
Fathi Boudra committed
232
        processEventsConnected--;
233 234
}

Fathi Boudra's avatar
Fathi Boudra committed
235
bool KRQuery::checkPerm(QString filePerm) const
Csaba Karai's avatar
 
Csaba Karai committed
236
{
Fathi Boudra's avatar
Fathi Boudra committed
237 238 239
    for (int i = 0; i < 9; ++i)
        if (perm[ i ] != '?' && perm[ i ] != filePerm[ i + 1 ]) return false;
    return true;
Csaba Karai's avatar
 
Csaba Karai committed
240 241
}

Fathi Boudra's avatar
Fathi Boudra committed
242
bool KRQuery::checkType(QString mime) const
Csaba Karai's avatar
 
Csaba Karai committed
243
{
Fathi Boudra's avatar
Fathi Boudra committed
244
    if (type == mime) return true;
245
    if (type == i18n("Archives")) return KRarcHandler::arcSupported(mime);
Fathi Boudra's avatar
Fathi Boudra committed
246 247 248 249 250 251 252
    if (type == i18n("Directories")) return mime.contains("directory");
    if (type == i18n("Image Files")) return mime.contains("image/");
    if (type == i18n("Text Files")) return mime.contains("text/");
    if (type == i18n("Video Files")) return mime.contains("video/");
    if (type == i18n("Audio Files")) return mime.contains("audio/");
    if (type == i18n("Custom")) return customType.contains(mime);
    return false;
Csaba Karai's avatar
 
Csaba Karai committed
253 254
}

Fathi Boudra's avatar
Fathi Boudra committed
255 256 257
bool KRQuery::match(const QString & name) const
{
    return matchCommon(name, matches, excludes);
258 259
}

Fathi Boudra's avatar
Fathi Boudra committed
260 261 262
bool KRQuery::matchDirName(const QString & name) const
{
    return matchCommon(name, includedDirs, excludedDirs);
263 264
}

Fathi Boudra's avatar
Fathi Boudra committed
265
bool KRQuery::matchCommon(const QString &nameIn, const QStringList &matchList, const QStringList &excludeList) const
Csaba Karai's avatar
 
Csaba Karai committed
266
{
Fathi Boudra's avatar
Fathi Boudra committed
267 268
    if (excludeList.count() == 0 && matchList.count() == 0)  /* true if there's no match condition */
        return true;
269

Fathi Boudra's avatar
Fathi Boudra committed
270 271 272 273
    QString name(nameIn);
    int ndx = nameIn.lastIndexOf('/');   // virtual filenames may contain '/'
    if (ndx != -1)                   // but the end of the filename is OK
        name = nameIn.mid(ndx + 1);
274

Fathi Boudra's avatar
Fathi Boudra committed
275 276 277 278
    for (int i = 0; i < excludeList.count(); ++i) {
        if (QRegExp(excludeList[ i ], matchesCaseSensitive ? Qt::CaseSensitive : Qt::CaseInsensitive, QRegExp::Wildcard).exactMatch(name))
            return false;
    }
279

Fathi Boudra's avatar
Fathi Boudra committed
280 281
    if (matchList.count() == 0)
        return true;
282

Fathi Boudra's avatar
Fathi Boudra committed
283 284 285
    for (int i = 0; i < matchList.count(); ++i) {
        if (QRegExp(matchList[ i ], matchesCaseSensitive ? Qt::CaseSensitive : Qt::CaseInsensitive, QRegExp::Wildcard).exactMatch(name))
            return true;
Csaba Karai's avatar
 
Csaba Karai committed
286
    }
Fathi Boudra's avatar
Fathi Boudra committed
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
    return false;
}

bool KRQuery::match(vfile *vf) const
{
    if (vf->vfile_isDir() && !matchDirName(vf->vfile_getName())) return false;
    // see if the name matches
    if (!match(vf->vfile_getName())) return false;
    // checking the mime
    if (!type.isEmpty() && !checkType(vf->vfile_getMime(true))) return false;
    // check that the size fit
    KIO::filesize_t size = vf->vfile_getSize();
    if (minSize && size < minSize) return false;
    if (maxSize && size > maxSize) return false;
    // check the time frame
    time_t mtime = vf->vfile_getTime_t();
    if (olderThen && mtime > olderThen) return false;
    if (newerThen && mtime < newerThen) return false;
    // check owner name
    if (!owner.isEmpty() && vf->vfile_getOwner() != owner) return false;
    // check group name
    if (!group.isEmpty() && vf->vfile_getGroup() != group) return false;
    //check permission
    if (!perm.isEmpty() && !checkPerm(vf->vfile_getPerm())) return false;

    if (!contain.isEmpty()) {
        if ((totalBytes = vf->vfile_getSize()) == 0)
            totalBytes++; // sanity
        receivedBytes = 0;
        if (receivedBuffer)
            delete receivedBuffer;
        receivedBuffer = 0;
        receivedBufferLen = 0;
        fileName = vf->vfile_getName();
        timer.start();

        if (vf->vfile_getUrl().isLocalFile()) {
            if (!containsContent(vf->vfile_getUrl().path())) return false;
        } else {
            if (containOnRemote) {
327 328 329 330 331 332 333 334
                if (processEventsConnected == 0)
                    return false;
                else if (containsContent(vf->vfile_getUrl()))
                    return true;
                else
                    return false;
            } else
                return false;
Fathi Boudra's avatar
Fathi Boudra committed
335
        }
Csaba Karai's avatar
 
Csaba Karai committed
336
    }
Csaba Karai's avatar
 
Csaba Karai committed
337

Fathi Boudra's avatar
Fathi Boudra committed
338
    return true;
Csaba Karai's avatar
 
Csaba Karai committed
339 340
}

Fathi Boudra's avatar
Fathi Boudra committed
341 342 343 344 345 346
bool KRQuery::match(KFileItem *kfi) const
{
    mode_t mode = kfi->mode() | kfi->permissions();
    QString perm = KRpermHandler::mode2QString(mode);
    if (kfi->isDir())
        perm[ 0 ] = 'd';
347

Fathi Boudra's avatar
Fathi Boudra committed
348
    vfile temp(kfi->text(), kfi->size(), perm, kfi->time(KFileItem::ModificationTime).toTime_t(),
349
               kfi->isLink(), false, kfi->user(), kfi->group(), kfi->user(),
Fathi Boudra's avatar
Fathi Boudra committed
350
               kfi->mimetype(), kfi->linkDest(), mode);
351

Fathi Boudra's avatar
Fathi Boudra committed
352
    return match(&temp);
353 354
}

355 356
// takes the string and adds BOLD to it, so that when it is displayed,
// the grepped text will be bold
Fathi Boudra's avatar
Fathi Boudra committed
357 358 359 360 361
void fixFoundTextForDisplay(QString& haystack, int start, int length)
{
    QString before = haystack.left(start);
    QString text = haystack.mid(start, length);
    QString after = haystack.mid(start + length);
362

Fathi Boudra's avatar
Fathi Boudra committed
363 364 365
    before.replace('&', "&amp;");
    before.replace('<', "&lt;");
    before.replace('>', "&gt;");
366

Fathi Boudra's avatar
Fathi Boudra committed
367 368 369
    text.replace('&', "&amp;");
    text.replace('<', "&lt;");
    text.replace('>', "&gt;");
370

Fathi Boudra's avatar
Fathi Boudra committed
371 372 373
    after.replace('&', "&amp;");
    after.replace('<', "&lt;");
    after.replace('>', "&gt;");
374

Fathi Boudra's avatar
Fathi Boudra committed
375
    haystack = ("<qt>" + before + "<b>" + text + "</b>" + after + "</qt>");
Csaba Karai's avatar
 
Csaba Karai committed
376
}
Csaba Karai's avatar
 
Csaba Karai committed
377

Fathi Boudra's avatar
Fathi Boudra committed
378
bool KRQuery::checkBuffer(const char * data, int len) const
379
{
Fathi Boudra's avatar
Fathi Boudra committed
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
    bool result = false;

    char * mergedBuffer = new char [ len + receivedBufferLen ];
    if (receivedBufferLen)
        memcpy(mergedBuffer, receivedBuffer, receivedBufferLen);
    if (len)
        memcpy(mergedBuffer + receivedBufferLen, data, len);

    int maxLen = len + receivedBufferLen;
    int maxBuffer = maxLen - encodedEnterLen;
    int lastLinePosition = 0;

    for (int enterIndex = 0; enterIndex < maxBuffer; enterIndex++) {
        if (memcmp(mergedBuffer + enterIndex, encodedEnter, encodedEnterLen) == 0) {
            QString str = codec->toUnicode(mergedBuffer + lastLinePosition, enterIndex + encodedEnterLen - lastLinePosition);
            if (str.endsWith('\n')) {
                str.chop(1);
                result = result || checkLine(str);
                lastLinePosition = enterIndex + encodedEnterLen;
                enterIndex = lastLinePosition;
                continue;
            }
        }
403
    }
Fathi Boudra's avatar
Fathi Boudra committed
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421

    if (maxLen - lastLinePosition > MAX_LINE_LEN || len == 0) {
        QString str = codec->toUnicode(mergedBuffer + lastLinePosition, maxLen - lastLinePosition);
        result = result || checkLine(str);
        lastLinePosition = maxLen;
    }

    delete []receivedBuffer;
    receivedBuffer = 0;
    receivedBufferLen = maxLen - lastLinePosition;

    if (receivedBufferLen) {
        receivedBuffer = new char [ receivedBufferLen ];
        memcpy(receivedBuffer, mergedBuffer + lastLinePosition, receivedBufferLen);
    }

    delete []mergedBuffer;
    return result;
422 423
}

Fathi Boudra's avatar
Fathi Boudra committed
424
bool KRQuery::checkLine(const QString & line, bool backwards) const
425
{
Fathi Boudra's avatar
Fathi Boudra committed
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
    if (containRegExp) {
        QRegExp rexp(contain, containCaseSensetive ? Qt::CaseSensitive : Qt::CaseInsensitive, QRegExp::RegExp);
        int ndx = backwards ? rexp.lastIndexIn(line) : rexp.indexIn(line);
        bool result = ndx >= 0;
        if (result)
            fixFoundTextForDisplay(lastSuccessfulGrep = line, lastSuccessfulGrepMatchIndex = ndx, lastSuccessfulGrepMatchLength = rexp.matchedLength());
        return result;
    }

    int ndx = backwards ? -1 : 0;

    if (line.isNull()) return false;
    if (containWholeWord) {
        while ((ndx = (backwards) ?
                      line.lastIndexOf(contain, ndx, containCaseSensetive ? Qt::CaseSensitive : Qt::CaseInsensitive) :
                              line.indexOf(contain, ndx, containCaseSensetive ? Qt::CaseSensitive : Qt::CaseInsensitive)
                       ) != -1) {
            QChar before = '\n';
            QChar after = '\n';

            if (ndx > 0)
                before = line.at(ndx - 1);
            if (ndx + contain.length() < line.length())
                after = line.at(ndx + contain.length());

            if (!before.isLetterOrNumber() && !after.isLetterOrNumber() &&
                    after != '_' && before != '_') {
                lastSuccessfulGrep = line;
                fixFoundTextForDisplay(lastSuccessfulGrep, lastSuccessfulGrepMatchIndex = ndx, lastSuccessfulGrepMatchLength = contain.length());
                return true;
            }

            if (backwards)
                ndx -= line.length() + 1;
            else
                ndx++;
        }
    } else if ((ndx = (backwards) ?
                      line.lastIndexOf(contain, -1, containCaseSensetive ? Qt::CaseSensitive : Qt::CaseInsensitive) :
                              line.indexOf(contain, 0, containCaseSensetive ? Qt::CaseSensitive : Qt::CaseInsensitive)) != -1) {
        lastSuccessfulGrep = line;
        fixFoundTextForDisplay(lastSuccessfulGrep, lastSuccessfulGrepMatchIndex = ndx, lastSuccessfulGrepMatchLength = contain.length());
        return true;
    }
470
    return false;
Fathi Boudra's avatar
Fathi Boudra committed
471
}
472

Fathi Boudra's avatar
Fathi Boudra committed
473 474 475 476 477
bool KRQuery::containsContent(QString file) const
{
    QFile qf(file);
    if (!qf.open(QIODevice::ReadOnly))
        return false;
478

Fathi Boudra's avatar
Fathi Boudra committed
479
    char buffer[ 1440 ]; // 2k buffer
480

Fathi Boudra's avatar
Fathi Boudra committed
481 482 483 484
    while (!qf.atEnd()) {
        int bytes = qf.read(buffer, sizeof(buffer));
        if (bytes <= 0)
            break;
485

Fathi Boudra's avatar
Fathi Boudra committed
486
        receivedBytes += bytes;
487

Fathi Boudra's avatar
Fathi Boudra committed
488 489 490 491 492 493 494 495 496
        if (checkBuffer(buffer, bytes))
            return true;

        if (checkTimer()) {
            bool stopped = false;
            emit((KRQuery *)this)->processEvents(stopped);
            if (stopped)
                return false;
        }
497
    }
Fathi Boudra's avatar
Fathi Boudra committed
498 499
    if (checkBuffer(buffer, 0))
        return true;
500

Fathi Boudra's avatar
Fathi Boudra committed
501
    lastSuccessfulGrep.clear(); // nothing was found
Fathi Boudra's avatar
Fathi Boudra committed
502
    return false;
503
}
504

505 506


507
bool KRQuery::containsContent(QUrl url) const
508
{
Fathi Boudra's avatar
Fathi Boudra committed
509 510 511 512 513 514 515 516 517 518 519 520 521 522
    KIO::TransferJob *contentReader = KIO::get(url, KIO::NoReload, KIO::HideProgressInfo);
    connect(contentReader, SIGNAL(data(KIO::Job *, const QByteArray &)),
            this, SLOT(containsContentData(KIO::Job *, const QByteArray &)));
    connect(contentReader, SIGNAL(result(KJob*)),
            this, SLOT(containsContentFinished(KJob*)));

    busy = true;
    containsContentResult = false;
    bool stopped = false;

    while (busy && !stopped) {
        checkTimer();
        emit((KRQuery *)this)->processEvents(stopped);
    }
523

Fathi Boudra's avatar
Fathi Boudra committed
524 525 526 527
    if (busy) {
        contentReader->kill(KJob::EmitResult);
        busy = false;
    }
528

Fathi Boudra's avatar
Fathi Boudra committed
529 530 531 532 533 534 535 536 537 538 539 540
    return containsContentResult;
}

void KRQuery::containsContentData(KIO::Job *job, const QByteArray &array)
{
    receivedBytes  += array.size();
    if (checkBuffer(array.data(), array.size())) {
        containsContentResult = true;
        containsContentFinished(job);
        job->kill(KJob::EmitResult);
        return;
    }
541
    checkTimer();
Fathi Boudra's avatar
Fathi Boudra committed
542
}
543

Fathi Boudra's avatar
Fathi Boudra committed
544 545
void KRQuery::containsContentFinished(KJob *)
{
546
    busy = false;
547 548
}

Fathi Boudra's avatar
Fathi Boudra committed
549 550 551 552
bool KRQuery::checkTimer() const
{
    if (timer.elapsed() >= STATUS_SEND_DELAY) {
        int pcnt = (int)(100.*(double)receivedBytes / (double)totalBytes + .5);
553
        QString message = i18nc("%1=filename, %2=percentage", "Searching content of '%1' (%2%)", fileName, pcnt);
Fathi Boudra's avatar
Fathi Boudra committed
554 555 556 557 558
        timer.start();
        emit((KRQuery *)this)->status(message);
        return true;
    }
    return false;
559 560
}

Fathi Boudra's avatar
Fathi Boudra committed
561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
QStringList KRQuery::split(QString str)
{
    QStringList list;
    int splitNdx = 0;
    int startNdx = 0;
    bool quotation = false;

    while (splitNdx < str.length()) {
        if (str[ splitNdx ] == '"')
            quotation = !quotation;

        if (!quotation && str[ splitNdx ] == ' ') {
            QString section = str.mid(startNdx, splitNdx - startNdx);
            startNdx = splitNdx + 1;
            if (section.startsWith('\"') && section.endsWith('\"') && section.length() >= 2)
                section = section.mid(1, section.length() - 2);
            if (!section.isEmpty())
                list.append(section);
        }
        splitNdx++;
    }
582

Fathi Boudra's avatar
Fathi Boudra committed
583 584 585 586 587 588
    if (startNdx < splitNdx) {
        QString section = str.mid(startNdx, splitNdx - startNdx);
        if (section.startsWith('\"') && section.endsWith('\"') && section.length() >= 2)
            section = section.mid(1, section.length() - 2);
        if (!section.isEmpty())
            list.append(section);
589
    }
Fathi Boudra's avatar
Fathi Boudra committed
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612

    return list;
}

void KRQuery::setNameFilter(const QString &text, bool cs)
{
    bNull = false;
    matchesCaseSensitive = cs;
    origFilter = text;

    QString matchText = text;
    QString excludeText;

    int excludeNdx = 0;
    bool quotationMark = 0;
    while (excludeNdx < matchText.length()) {
        if (matchText[ excludeNdx ] == '"')
            quotationMark = !quotationMark;
        if (!quotationMark) {
            if (matchText[ excludeNdx ] == '|')
                break;
        }
        excludeNdx++;
613
    }
Fathi Boudra's avatar
Fathi Boudra committed
614 615 616 617 618 619 620

    if (excludeNdx < matchText.length()) {
        excludeText = matchText.mid(excludeNdx + 1).trimmed();
        matchText.truncate(excludeNdx);
        matchText = matchText.trimmed();
        if (matchText.isEmpty())
            matchText = '*';
621 622
    }

Fathi Boudra's avatar
Fathi Boudra committed
623
    int i;
624

Fathi Boudra's avatar
Fathi Boudra committed
625 626
    matches  = split(matchText);
    includedDirs.clear();
627

Fathi Boudra's avatar
Fathi Boudra committed
628 629 630 631 632 633
    for (i = 0; i < matches.count();) {
        if (matches[ i ].endsWith('/')) {
            includedDirs.push_back(matches[ i ].left(matches[ i ].length() - 1));
            matches.removeAll(matches.at(i));
            continue;
        }
634

Fathi Boudra's avatar
Fathi Boudra committed
635 636 637 638
        if (!matches[ i ].contains("*") && !matches[ i ].contains("?"))
            matches[ i ] = '*' + matches[ i ] + '*';

        i++;
639 640
    }

Fathi Boudra's avatar
Fathi Boudra committed
641 642 643 644 645 646 647 648 649
    excludes = split(excludeText);
    excludedDirs.clear();

    for (i = 0; i < excludes.count();) {
        if (excludes[ i ].endsWith('/')) {
            excludedDirs.push_back(excludes[ i ].left(excludes[ i ].length() - 1));
            excludes.removeAll(excludes.at(i));
            continue;
        }
650

Fathi Boudra's avatar
Fathi Boudra committed
651 652 653 654 655
        if (!excludes[ i ].contains("*") && !excludes[ i ].contains("?"))
            excludes[ i ] = '*' + excludes[ i ] + '*';

        i++;
    }
Csaba Karai's avatar
 
Csaba Karai committed
656 657
}

Fathi Boudra's avatar
Fathi Boudra committed
658
void KRQuery::setContent(const QString &content, bool cs, bool wholeWord, bool remoteSearch, QString encoding, bool regExp)
Csaba Karai's avatar
 
Csaba Karai committed
659
{
Fathi Boudra's avatar
Fathi Boudra committed
660 661 662 663 664 665 666 667 668 669 670 671 672 673
    bNull = false;
    contain = content;
    containCaseSensetive = cs;
    containWholeWord = wholeWord;
    containRegExp = regExp;
    containOnRemote = remoteSearch;

    if (encoding.isEmpty())
        codec = QTextCodec::codecForLocale();
    else {
        codec = QTextCodec::codecForName(encoding.toLatin1());
        if (codec == 0)
            codec = QTextCodec::codecForLocale();
    }
674

Fathi Boudra's avatar
Fathi Boudra committed
675 676 677 678 679
    QChar ch = '\n';
    QTextCodec::ConverterState state(QTextCodec::IgnoreHeader);
    encodedEnterArray = codec->fromUnicode(&ch, 1, &state);
    encodedEnter = encodedEnterArray.data();
    encodedEnterLen = encodedEnterArray.size();
Csaba Karai's avatar
 
Csaba Karai committed
680 681
}

Fathi Boudra's avatar
Fathi Boudra committed
682
void KRQuery::setMinimumFileSize(KIO::filesize_t minimumSize)
Csaba Karai's avatar
 
Csaba Karai committed
683
{
Fathi Boudra's avatar
Fathi Boudra committed
684 685
    bNull = false;
    minSize = minimumSize;
Csaba Karai's avatar
 
Csaba Karai committed
686 687
}

Fathi Boudra's avatar
Fathi Boudra committed
688
void KRQuery::setMaximumFileSize(KIO::filesize_t maximumSize)
Csaba Karai's avatar
 
Csaba Karai committed
689
{
Fathi Boudra's avatar
Fathi Boudra committed
690 691
    bNull = false;
    maxSize = maximumSize;
Csaba Karai's avatar
 
Csaba Karai committed
692 693
}

Fathi Boudra's avatar
Fathi Boudra committed
694
void KRQuery::setNewerThan(time_t time)
Csaba Karai's avatar
 
Csaba Karai committed
695
{
Fathi Boudra's avatar
Fathi Boudra committed
696 697
    bNull = false;
    newerThen = time;
Csaba Karai's avatar
 
Csaba Karai committed
698 699
}

Fathi Boudra's avatar
Fathi Boudra committed
700
void KRQuery::setOlderThan(time_t time)
Csaba Karai's avatar
 
Csaba Karai committed
701
{
Fathi Boudra's avatar
Fathi Boudra committed
702 703
    bNull = false;
    olderThen = time;
Csaba Karai's avatar
 
Csaba Karai committed
704 705
}

Fathi Boudra's avatar
Fathi Boudra committed
706
void KRQuery::setOwner(const QString &ownerIn)
Csaba Karai's avatar
 
Csaba Karai committed
707
{
Fathi Boudra's avatar
Fathi Boudra committed
708 709
    bNull = false;
    owner = ownerIn;
Csaba Karai's avatar
 
Csaba Karai committed
710 711
}

Fathi Boudra's avatar
Fathi Boudra committed
712
void KRQuery::setGroup(const QString &groupIn)
Csaba Karai's avatar
 
Csaba Karai committed
713
{
Fathi Boudra's avatar
Fathi Boudra committed
714 715
    bNull = false;
    group = groupIn;
Csaba Karai's avatar
 
Csaba Karai committed
716 717
}

Fathi Boudra's avatar
Fathi Boudra committed
718
void KRQuery::setPermissions(const QString &permIn)
Csaba Karai's avatar
 
Csaba Karai committed
719
{
Fathi Boudra's avatar
Fathi Boudra committed
720 721
    bNull = false;
    perm = permIn;
Csaba Karai's avatar
 
Csaba Karai committed
722 723
}

Fathi Boudra's avatar
Fathi Boudra committed
724
void KRQuery::setMimeType(const QString &typeIn, QStringList customList)
Csaba Karai's avatar
 
Csaba Karai committed
725
{
Fathi Boudra's avatar
Fathi Boudra committed
726 727 728
    bNull = false;
    type = typeIn;
    customType = customList;
Csaba Karai's avatar
 
Csaba Karai committed
729 730
}

731
bool KRQuery::isExcluded(const QUrl &url)
Csaba Karai's avatar
 
Csaba Karai committed
732
{
Fathi Boudra's avatar
Fathi Boudra committed
733
    for (int i = 0; i < whereNotToSearch.count(); ++i)
734
        if (whereNotToSearch [ i ].isParentOf(url) || url.matches(whereNotToSearch [ i ], QUrl::StripTrailingSlash))
Fathi Boudra's avatar
Fathi Boudra committed
735
            return true;
Csaba Karai's avatar
 
Csaba Karai committed
736

Fathi Boudra's avatar
Fathi Boudra committed
737 738
    if (!matchDirName(url.fileName()))
        return true;
739

Fathi Boudra's avatar
Fathi Boudra committed
740
    return false;
Csaba Karai's avatar
 
Csaba Karai committed
741 742
}

743
void KRQuery::setSearchInDirs(const QList<QUrl> &urls)
Fathi Boudra's avatar
Fathi Boudra committed
744 745 746 747
{
    whereToSearch.clear();
    for (int i = 0; i < urls.count(); ++i) {
        QString url = urls[ i ].url();
Simon Persson's avatar
Simon Persson committed
748
        QUrl completed = QUrl::fromUserInput(KUrlCompletion::replacedPath(url, true, true), QString(), QUrl::AssumeLocalFile);
Fathi Boudra's avatar
Fathi Boudra committed
749 750
        whereToSearch.append(completed);
    }
751 752
}

753
void KRQuery::setDontSearchInDirs(const QList<QUrl> &urls)
Fathi Boudra's avatar
Fathi Boudra committed
754 755 756 757
{
    whereNotToSearch.clear();
    for (int i = 0; i < urls.count(); ++i) {
        QString url = urls[ i ].url();
Simon Persson's avatar
Simon Persson committed
758
        QUrl completed = QUrl::fromUserInput(KUrlCompletion::replacedPath(url, true, true), QString(), QUrl::AssumeLocalFile);
Fathi Boudra's avatar
Fathi Boudra committed
759 760
        whereNotToSearch.append(completed);
    }
761
}
762