kftabdlg.cpp 32.7 KB
Newer Older
1 2
/*******************************************************************
* kftabdlg.cpp
Laurent Montel's avatar
Laurent Montel committed
3
*
4 5
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
Laurent Montel's avatar
Laurent Montel committed
6
* published by the Free Software Foundation; either version 2 of
7
* the License, or (at your option) any later version.
Laurent Montel's avatar
Laurent Montel committed
8
*
9 10 11 12
* 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.
Laurent Montel's avatar
Laurent Montel committed
13
*
14 15
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
Laurent Montel's avatar
Laurent Montel committed
16
*
17 18
******************************************************************/

Max Blazejak's avatar
Max Blazejak committed
19
#include "kftabdlg.h"
20

21
#include <QApplication>
22
#include <QButtonGroup>
23 24 25
#include <QCheckBox>
#include <QDesktopWidget>
#include <QFileDialog>
26
#include <QLabel>
Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
27
#include <QMimeDatabase>
28
#include <QPushButton>
29 30
#include <QRadioButton>
#include <QSpinBox>
31
#include <QStandardPaths>
32 33 34
#include <QWhatsThis>
#include <QtConcurrent/QtConcurrentRun>
#include <QFutureWatcher>
Laurent Montel's avatar
Laurent Montel committed
35
#include <QGridLayout>
36

37 38
#include <KComboBox>
#include <KConfigGroup>
39
#include <KDateComboBox>
40 41 42 43 44 45
#include <KLineEdit>
#include <KLocalizedString>
#include <KMessageBox>
#include <KRegExpEditorInterface>
#include <KServiceTypeTrader>
#include <KSharedConfig>
Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
46
#include <KShell>
47 48
#include <KUrlComboBox>
#include <KUrlCompletion>
49 50 51

#include <algorithm>

52
#include "kquery.h"
53

54
// Static utility functions
55
static void save_pattern(KComboBox *, const QString &, const QString &);
56

57
static const int specialMimeTypeCount = 10;
58

59
struct MimeTypes
60
{
Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
61
    QVector<QMimeType> all;
62 63 64
    QStringList image;
    QStringList video;
    QStringList audio;
65 66
};

67
KfindTabWidget::KfindTabWidget(QWidget *parent)
68
    : QTabWidget(parent)
Laurent Montel's avatar
Minor  
Laurent Montel committed
69
    , regExpDialog(nullptr)
70 71
{
    // This validator will be used for all numeric edit fields
Laurent Montel's avatar
Laurent Montel committed
72
    //KDigitValidator *digitV = new KDigitValidator(this);
73 74 75

    // ************ Page One ************

Laurent Montel's avatar
Laurent Montel committed
76
    pages[0] = new QWidget;
Laurent Montel's avatar
Laurent Montel committed
77
    pages[0]->setObjectName(QStringLiteral("page1"));
78

Tobias Koenig's avatar
Tobias Koenig committed
79
    nameBox = new KComboBox(pages[0]);
Laurent Montel's avatar
Laurent Montel committed
80
    nameBox->setEditable(true);
81
    nameBox->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);  // allow smaller than widest entry
Laurent Montel's avatar
Laurent Montel committed
82 83 84 85 86 87
    QLabel *namedL = new QLabel(i18nc("this is the label for the name textfield", "&Named:"), pages[0]);
    namedL->setBuddy(nameBox);
    namedL->setObjectName(QStringLiteral("named"));
    namedL->setToolTip(i18n("You can use wildcard matching and \";\" for separating multiple names"));
    dirBox = new KUrlComboBox(KUrlComboBox::Directories, pages[0]);
    dirBox->setEditable(true);
Bernhard Beschow's avatar
Bernhard Beschow committed
88 89
    dirBox->setCompletionObject(new KUrlCompletion(KUrlCompletion::DirCompletion));
    dirBox->setAutoDeleteCompletionObject(true);
90
    dirBox->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);  // allow smaller than widest entry
Laurent Montel's avatar
Laurent Montel committed
91 92 93 94 95 96
    QLabel *lookinL = new QLabel(i18n("Look &in:"), pages[0]);
    lookinL->setBuddy(dirBox);
    lookinL->setObjectName(QStringLiteral("lookin"));
    subdirsCb = new QCheckBox(i18n("Include &subfolders"), pages[0]);
    caseSensCb = new QCheckBox(i18n("Case s&ensitive search"), pages[0]);
    browseB = new QPushButton(i18n("&Browse..."), pages[0]);
97
    useLocateCb = new QCheckBox(i18n("&Use files index"), pages[0]);
98
    hiddenFilesCb = new QCheckBox(i18n("Show &hidden files"), pages[0]);
99 100 101
    // Setup

    subdirsCb->setChecked(true);
102
    caseSensCb->setChecked(false);
103
    useLocateCb->setChecked(false);
104
    hiddenFilesCb->setChecked(false);
105
    if (QStandardPaths::findExecutable(QStringLiteral("locate")).isEmpty()) {
106
        useLocateCb->setEnabled(false);
Laurent Montel's avatar
Laurent Montel committed
107
    }
108

Stephan Kulow's avatar
compile  
Stephan Kulow committed
109
    nameBox->setDuplicatesEnabled(false);
110
    nameBox->setFocus();
Stephan Kulow's avatar
compile  
Stephan Kulow committed
111
    dirBox->setDuplicatesEnabled(false);
112

Urs Wolfer's avatar
Urs Wolfer committed
113 114
    nameBox->setInsertPolicy(QComboBox::InsertAtTop);
    dirBox->setInsertPolicy(QComboBox::InsertAtTop);
115

Lukáš Tinkl's avatar
Lukáš Tinkl committed
116
    const QString nameWhatsThis
Laurent Montel's avatar
Laurent Montel committed
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
        = i18n("<qt>Enter the filename you are looking for. <br />"
               "Alternatives may be separated by a semicolon \";\".<br />"
               "<br />"
               "The filename may contain the following special characters:"
               "<ul>"
               "<li><b>?</b> matches any single character</li>"
               "<li><b>*</b> matches zero or more of any characters</li>"
               "<li><b>[...]</b> matches any of the characters between the braces</li>"
               "</ul>"
               "<br />"
               "Example searches:"
               "<ul>"
               "<li><b>*.kwd;*.txt</b> finds all files ending with .kwd or .txt</li>"
               "<li><b>go[dt]</b> finds god and got</li>"
               "<li><b>Hel?o</b> finds all files that start with \"Hel\" and end with \"o\", "
               "having one character in between</li>"
               "<li><b>My Document.kwd</b> finds a file of exactly that name</li>"
               "</ul></qt>");
Tobias Koenig's avatar
Tobias Koenig committed
135 136
    nameBox->setWhatsThis(nameWhatsThis);
    namedL->setWhatsThis(nameWhatsThis);
137
    const QString whatsfileindex
138
        = i18n("<qt>This lets you use the files' index created by the <i>slocate</i> "
Andrew Coles's avatar
 
Andrew Coles committed
139
               "package to speed-up the search; remember to update the index from time to time "
140 141
               "(using <i>updatedb</i>)."
               "</qt>");
Tobias Koenig's avatar
Tobias Koenig committed
142
    useLocateCb->setWhatsThis(whatsfileindex);
143

144 145
    // Layout

Laurent Montel's avatar
Laurent Montel committed
146
    QGridLayout *grid = new QGridLayout(pages[0]);
147
    QVBoxLayout *subgrid = new QVBoxLayout();
Laurent Montel's avatar
Laurent Montel committed
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
    grid->addWidget(namedL, 0, 0);
    grid->addWidget(nameBox, 0, 1, 1, 3);
    grid->addWidget(lookinL, 1, 0);
    grid->addWidget(dirBox, 1, 1);
    grid->addWidget(browseB, 1, 2);
    grid->setColumnStretch(1, 1);
    grid->addLayout(subgrid, 2, 1, 1, 2);

    QHBoxLayout *layoutOne = new QHBoxLayout();
    layoutOne->addWidget(subdirsCb);
    layoutOne->addWidget(hiddenFilesCb);

    QHBoxLayout *layoutTwo = new QHBoxLayout();
    layoutTwo->addWidget(caseSensCb);
    layoutTwo->addWidget(useLocateCb);

    subgrid->addLayout(layoutOne);
    subgrid->addLayout(layoutTwo);

167
    subgrid->addStretch(1);
168 169 170

    // Signals

Laurent Montel's avatar
Laurent Montel committed
171
    connect(browseB, &QPushButton::clicked, this, &KfindTabWidget::getDirectory);
172

Laurent Montel's avatar
Laurent Montel committed
173
    connect(nameBox, static_cast<void (KComboBox::*)()>(&KComboBox::returnPressed), this, &KfindTabWidget::startSearch);
174

Laurent Montel's avatar
Laurent Montel committed
175
    connect(dirBox, static_cast<void (KUrlComboBox::*)()>(&KUrlComboBox::returnPressed), this, &KfindTabWidget::startSearch);
Laurent Montel's avatar
Laurent Montel committed
176

177 178
    // ************ Page Two

Laurent Montel's avatar
Laurent Montel committed
179
    pages[1] = new QWidget;
Laurent Montel's avatar
Laurent Montel committed
180
    pages[1]->setObjectName(QStringLiteral("page2"));
181

Laurent Montel's avatar
Laurent Montel committed
182 183 184
    findCreated = new QCheckBox(i18n("Find all files created or &modified:"), pages[1]);
    bg = new QButtonGroup();
    rb[0] = new QRadioButton(i18n("&between"), pages[1]);
185
    rb[1] = new QRadioButton(pages[1]); // text set in updateDateLabels
Thorsten Roeder's avatar
Thorsten Roeder committed
186
    andL = new QLabel(i18n("and"), pages[1]);
Laurent Montel's avatar
Laurent Montel committed
187 188 189
    andL->setObjectName(QStringLiteral("and"));
    betweenType = new KComboBox(pages[1]);
    betweenType->setObjectName(QStringLiteral("comboBetweenType"));
190
    betweenType->addItems(QVector<QString>(5).toList()); // texts set in updateDateLabels
Laurent Montel's avatar
Laurent Montel committed
191
    betweenType->setCurrentIndex(1);
192
    updateDateLabels(1, 1);
193

194
    const QDate dt = QDate::currentDate().addYears(-1);
195

196
    fromDate = new KDateComboBox(pages[1]);
Laurent Montel's avatar
Laurent Montel committed
197
    fromDate->setObjectName(QStringLiteral("fromDate"));
198
    fromDate->setDate(dt);
Laurent Montel's avatar
Laurent Montel committed
199 200
    toDate = new KDateComboBox(pages[1]);
    toDate->setObjectName(QStringLiteral("toDate"));
201
    timeBox = new QSpinBox(pages[1]);
Laurent Montel's avatar
Laurent Montel committed
202 203 204 205 206 207 208 209
    timeBox->setRange(1, 60);
    timeBox->setSingleStep(1);
    timeBox->setObjectName(QStringLiteral("timeBox"));

    sizeBox = new KComboBox(pages[1]);
    sizeBox->setObjectName(QStringLiteral("sizeBox"));
    QLabel *sizeL = new QLabel(i18n("File &size is:"), pages[1]);
    sizeL->setBuddy(sizeBox);
210
    sizeEdit = new QSpinBox(pages[1]);
Laurent Montel's avatar
Laurent Montel committed
211 212 213
    sizeEdit->setRange(0, INT_MAX);
    sizeEdit->setSingleStep(1);
    sizeEdit->setObjectName(QStringLiteral("sizeEdit"));
Alexander Neundorf's avatar
 
Alexander Neundorf committed
214
    sizeEdit->setValue(1);
Laurent Montel's avatar
Laurent Montel committed
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
    sizeUnitBox = new KComboBox(pages[1]);
    sizeUnitBox->setObjectName(QStringLiteral("sizeUnitBox"));

    m_usernameBox = new KComboBox(pages[1]);
    m_usernameBox->setEditable(true);
    m_usernameBox->setObjectName(QStringLiteral("m_combo1"));
    QLabel *usernameLabel = new QLabel(i18n("Files owned by &user:"), pages[1]);
    usernameLabel->setBuddy(m_usernameBox);
    m_groupBox = new KComboBox(pages[1]);
    m_groupBox->setEditable(true);
    m_groupBox->setObjectName(QStringLiteral("m_combo2"));
    QLabel *groupLabel = new QLabel(i18n("Owned by &group:"), pages[1]);
    groupLabel->setBuddy(m_groupBox);

    sizeBox->addItem(i18nc("file size isn't considered in the search", "(none)"));
    sizeBox->addItem(i18n("At Least"));
    sizeBox->addItem(i18n("At Most"));
    sizeBox->addItem(i18n("Equal To"));

    sizeUnitBox->addItem(i18np("Byte", "Bytes", 1));
    sizeUnitBox->addItem(i18n("KiB"));
    sizeUnitBox->addItem(i18n("MiB"));
    sizeUnitBox->addItem(i18n("GiB"));
    sizeUnitBox->setCurrentIndex(1);
Alexander Neundorf's avatar
 
Alexander Neundorf committed
239

240
    int tmp = sizeEdit->fontMetrics().boundingRect(QStringLiteral(" 000000000 ")).width();
Alexander Neundorf's avatar
 
Alexander Neundorf committed
241 242
    sizeEdit->setMinimumSize(tmp, sizeEdit->sizeHint().height());

Stephan Kulow's avatar
compile  
Stephan Kulow committed
243 244
    m_usernameBox->setDuplicatesEnabled(false);
    m_groupBox->setDuplicatesEnabled(false);
Urs Wolfer's avatar
Urs Wolfer committed
245 246
    m_usernameBox->setInsertPolicy(QComboBox::InsertAtTop);
    m_groupBox->setInsertPolicy(QComboBox::InsertAtTop);
Alexander Neundorf's avatar
 
Alexander Neundorf committed
247

248
    // Setup
249
    rb[0]->setChecked(true);
Laurent Montel's avatar
Laurent Montel committed
250 251
    bg->addButton(rb[0]);
    bg->addButton(rb[1]);
252 253 254

    // Layout

Laurent Montel's avatar
Laurent Montel committed
255
    QGridLayout *grid1 = new QGridLayout(pages[1]);
Alexander Neundorf's avatar
 
Alexander Neundorf committed
256

Laurent Montel's avatar
Laurent Montel committed
257
    grid1->addWidget(findCreated, 0, 0, 1, 3);
Alexander Neundorf's avatar
 
Alexander Neundorf committed
258

Laurent Montel's avatar
Laurent Montel committed
259 260 261 262
    grid1->addWidget(rb[0], 1, 1);
    grid1->addWidget(fromDate, 1, 2);
    grid1->addWidget(andL, 1, 3, Qt::AlignHCenter);
    grid1->addWidget(toDate, 1, 4);
Alexander Neundorf's avatar
 
Alexander Neundorf committed
263

Laurent Montel's avatar
Laurent Montel committed
264
    grid1->addWidget(rb[1], 2, 1);
Thorsten Roeder's avatar
Thorsten Roeder committed
265
    grid1->addWidget(timeBox, 2, 2, 1, 2);
Laurent Montel's avatar
Laurent Montel committed
266
    grid1->addWidget(betweenType, 2, 4);
Alexander Neundorf's avatar
 
Alexander Neundorf committed
267

Laurent Montel's avatar
Laurent Montel committed
268 269 270 271
    grid1->addWidget(sizeL, 3, 0, 1, 2);
    grid1->addWidget(sizeBox, 3, 2);
    grid1->addWidget(sizeEdit, 3, 3);
    grid1->addWidget(sizeUnitBox, 3, 4);
Alexander Neundorf's avatar
 
Alexander Neundorf committed
272

Laurent Montel's avatar
Laurent Montel committed
273 274 275 276
    grid1->addWidget(usernameLabel, 4, 0, 1, 2);
    grid1->addWidget(m_usernameBox, 4, 2);
    grid1->addWidget(groupLabel, 4, 3);
    grid1->addWidget(m_groupBox, 4, 4);
Alexander Neundorf's avatar
 
Alexander Neundorf committed
277

Laurent Montel's avatar
Laurent Montel committed
278 279 280
    for (int c = 1; c <= 4; c++) {
        grid1->setColumnStretch(c, 1);
    }
Alexander Neundorf's avatar
 
Alexander Neundorf committed
281

Laurent Montel's avatar
Laurent Montel committed
282
    grid1->setRowStretch(6, 1);
283 284

    // Connect
Laurent Montel's avatar
Laurent Montel committed
285 286 287
    connect(findCreated, &QCheckBox::toggled, this, &KfindTabWidget::fixLayout);
    connect(bg, static_cast<void (QButtonGroup::*)(QAbstractButton *)>(&QButtonGroup::buttonClicked), this, &KfindTabWidget::fixLayout);
    connect(sizeBox, static_cast<void (KComboBox::*)(int)>(&KComboBox::activated), this, &KfindTabWidget::slotSizeBoxChanged);
288
    connect(timeBox, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &KfindTabWidget::slotUpdateDateLabelsForNumber);
289
#if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
Laurent Montel's avatar
Laurent Montel committed
290
    connect(betweenType, static_cast<void (KComboBox::*)(int)>(&KComboBox::currentIndexChanged), this, &KfindTabWidget::slotUpdateDateLabelsForType);
291 292 293
#else
    connect(betweenType, static_cast<void (KComboBox::*)(int, const QString &)>(&KComboBox::currentIndexChanged), this, &KfindTabWidget::slotUpdateDateLabelsForType);
#endif
294
    connect(sizeEdit, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &KfindTabWidget::slotUpdateByteComboBox);
295 296 297

    // ************ Page Three

Laurent Montel's avatar
Laurent Montel committed
298
    pages[2] = new QWidget;
Laurent Montel's avatar
Laurent Montel committed
299
    pages[2]->setObjectName(QStringLiteral("page3"));
300

Laurent Montel's avatar
Laurent Montel committed
301 302
    typeBox = new KComboBox(pages[2]);
    typeBox->setObjectName(QStringLiteral("typeBox"));
303
    typeBox->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);  // allow smaller than widest entry
Laurent Montel's avatar
Laurent Montel committed
304 305 306
    QLabel *typeL = new QLabel(i18nc("label for the file type combobox", "File &type:"), pages[2]);
    typeL->setBuddy(typeBox);
    textEdit = new KLineEdit(pages[2]);
307
    textEdit->setClearButtonEnabled(true);
Laurent Montel's avatar
Laurent Montel committed
308 309 310
    textEdit->setObjectName(QStringLiteral("textEdit"));
    QLabel *textL = new QLabel(i18n("C&ontaining text:"), pages[2]);
    textL->setBuddy(textEdit);
311

Laurent Montel's avatar
Laurent Montel committed
312
    connect(textEdit, &KLineEdit::returnPressed, this, &KfindTabWidget::startSearch);
313

314
    const QString containingtext
Laurent Montel's avatar
Laurent Montel committed
315 316 317 318 319
        = i18n("<qt>If specified, only files that contain this text"
               " are found. Note that not all file types from the list"
               " above are supported. Please refer to the documentation"
               " for a list of supported file types."
               "</qt>");
Laurent Montel's avatar
Laurent Montel committed
320
    textEdit->setToolTip(containingtext);
Tobias Koenig's avatar
Tobias Koenig committed
321
    textL->setWhatsThis(containingtext);
322

Laurent Montel's avatar
Laurent Montel committed
323 324 325
    caseContextCb = new QCheckBox(i18n("Case s&ensitive"), pages[2]);
    binaryContextCb = new QCheckBox(i18n("Include &binary files"), pages[2]);
    regexpContentCb = new QCheckBox(i18n("Regular e&xpression"), pages[2]);
326

327
    const QString binaryTooltip
Laurent Montel's avatar
Laurent Montel committed
328 329 330
        = i18n("<qt>This lets you search in any type of file, "
               "even those that usually do not contain text (for example "
               "program files and images).</qt>");
Laurent Montel's avatar
Laurent Montel committed
331
    binaryContextCb->setToolTip(binaryTooltip);
332

Laurent Montel's avatar
Minor  
Laurent Montel committed
333
    QPushButton *editRegExp = nullptr;
Laurent Montel's avatar
Laurent Montel committed
334
    if (!KServiceTypeTrader::self()->query(QStringLiteral("KRegExpEditor/KRegExpEditor")).isEmpty()) {
Stephan Kulow's avatar
compile  
Stephan Kulow committed
335 336
        // The editor is available, so lets use it.
        editRegExp = new QPushButton(i18n("&Edit..."), pages[2]);
Laurent Montel's avatar
Laurent Montel committed
337
        editRegExp->setObjectName(QStringLiteral("editRegExp"));
338
    }
339

Laurent Montel's avatar
Laurent Montel committed
340 341 342 343 344 345
    metainfokeyEdit = new KLineEdit(pages[2]);
    metainfoEdit = new KLineEdit(pages[2]);
    QLabel *textMetaInfo = new QLabel(i18nc("as in search for", "fo&r:"), pages[2]);
    textMetaInfo->setBuddy(metainfoEdit);
    QLabel *textMetaKey = new QLabel(i18n("Search &metainfo sections:"), pages[2]);
    textMetaKey->setBuddy(metainfokeyEdit);
Alexander Neundorf's avatar
 
Alexander Neundorf committed
346

347
    // Setup
Tobias Koenig's avatar
Tobias Koenig committed
348 349 350 351 352 353 354 355 356 357
    typeBox->addItem(i18n("All Files & Folders"));
    typeBox->addItem(i18n("Files"));
    typeBox->addItem(i18n("Folders"));
    typeBox->addItem(i18n("Symbolic Links"));
    typeBox->addItem(i18n("Special Files (Sockets, Device Files, ...)"));
    typeBox->addItem(i18n("Executable Files"));
    typeBox->addItem(i18n("SUID Executable Files"));
    typeBox->addItem(i18n("All Images"));
    typeBox->addItem(i18n("All Video"));
    typeBox->addItem(i18n("All Sounds"));
358 359
    typeBox->insertSeparator(typeBox->count()); // append separator

360
    auto mimeTypeFuture = QtConcurrent::run([] {
361 362
        MimeTypes mimeTypes;

Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
363 364 365 366 367
        const auto types = QMimeDatabase().allMimeTypes();
        foreach (const QMimeType &type, types) {
            if ((!type.comment().isEmpty())
                && (!type.name().startsWith(QLatin1String("kdedevice/")))
                && (!type.name().startsWith(QLatin1String("all/")))) {
368 369
                mimeTypes.all.append(type);

Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
370 371 372 373 374 375
                if (type.name().startsWith(QLatin1String("image/"))) {
                    mimeTypes.image.append(type.name());
                } else if (type.name().startsWith(QLatin1String("video/"))) {
                    mimeTypes.video.append(type.name());
                } else if (type.name().startsWith(QLatin1String("audio/"))) {
                    mimeTypes.audio.append(type.name());
376 377 378
                }
            }
        }
379

Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
380 381
        std::sort(mimeTypes.all.begin(), mimeTypes.all.end(), [](const QMimeType &lhs, const QMimeType &rhs) {
            return lhs.comment() < rhs.comment();
382
        });
383

384 385 386 387 388 389 390 391 392
        return mimeTypes;
    });

    auto *watcher = new QFutureWatcher<MimeTypes>(this);
    watcher->setFuture(mimeTypeFuture);
    connect(watcher, &QFutureWatcher<MimeTypes>::finished, this, [this, watcher] {
        const MimeTypes &mimeTypes = watcher->result();

        for (const auto &mime : qAsConst(mimeTypes.all)) {
Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
393
            typeBox->addItem(mime.comment());
394 395 396 397 398 399 400 401 402 403
        }

        m_types = mimeTypes.all;

        m_ImageTypes = mimeTypes.image;
        m_VideoTypes = mimeTypes.video;
        m_AudioTypes = mimeTypes.audio;

        watcher->deleteLater();
    });
404

Laurent Montel's avatar
Laurent Montel committed
405 406 407 408 409 410
    if (editRegExp) {
        // The editor was available, so lets use it.
        connect(regexpContentCb, &QCheckBox::toggled, editRegExp, &QPushButton::setEnabled);
        editRegExp->setEnabled(false);
        connect(editRegExp, &QPushButton::clicked, this, &KfindTabWidget::slotEditRegExp);
    } else {
411
        regexpContentCb->hide();
Laurent Montel's avatar
Laurent Montel committed
412
    }
413 414

    // Layout
415
    tmp = sizeEdit->fontMetrics().boundingRect(QStringLiteral(" 00000 ")).width();
416 417
    sizeEdit->setMinimumSize(tmp, sizeEdit->sizeHint().height());

Laurent Montel's avatar
Laurent Montel committed
418 419 420 421 422 423 424 425 426 427 428 429 430
    QGridLayout *grid2 = new QGridLayout(pages[2]);
    grid2->addWidget(typeL, 0, 0);
    grid2->addWidget(textL, 1, 0);
    grid2->addWidget(typeBox, 0, 1, 1, 3);
    grid2->addWidget(textEdit, 1, 1, 1, 3);
    grid2->addWidget(regexpContentCb, 2, 2);
    grid2->addWidget(caseContextCb, 2, 1);
    grid2->addWidget(binaryContextCb, 3, 1);

    grid2->addWidget(textMetaKey, 4, 0);
    grid2->addWidget(metainfokeyEdit, 4, 1);
    grid2->addWidget(textMetaInfo, 4, 2, Qt::AlignHCenter);
    grid2->addWidget(metainfoEdit, 4, 3);
Alexander Neundorf's avatar
 
Alexander Neundorf committed
431

Laurent Montel's avatar
Laurent Montel committed
432
    metainfokeyEdit->setText(QStringLiteral("*"));
Alexander Neundorf's avatar
 
Alexander Neundorf committed
433

Laurent Montel's avatar
Laurent Montel committed
434 435 436
    if (editRegExp) {
        // The editor was available, so lets use it.
        grid2->addWidget(editRegExp, 2, 3);
437
    }
Lukáš Tinkl's avatar
Lukáš Tinkl committed
438

Laurent Montel's avatar
Laurent Montel committed
439 440 441
    addTab(pages[0], i18n("Name/&Location"));
    addTab(pages[2], i18nc("tab name: search by contents", "C&ontents"));
    addTab(pages[1], i18n("&Properties"));
442 443 444

    // Setup
    const QString whatsmetainfo
Laurent Montel's avatar
Laurent Montel committed
445 446 447 448 449 450 451
        = i18n("<qt>Search within files' specific comments/metainfo<br />"
               "These are some examples:<br />"
               "<ul>"
               "<li><b>Audio files (mp3...)</b> Search in id3 tag for a title, an album</li>"
               "<li><b>Images (png...)</b> Search images with a special resolution, comment...</li>"
               "</ul>"
               "</qt>");
452
    const QString whatsmetainfokey
Laurent Montel's avatar
Laurent Montel committed
453 454 455 456 457 458
        = i18n("<qt>If specified, search only in this field<br />"
               "<ul>"
               "<li><b>Audio files (mp3...)</b> This can be Title, Album...</li>"
               "<li><b>Images (png...)</b> Search only in Resolution, Bitdepth...</li>"
               "</ul>"
               "</qt>");
Tobias Koenig's avatar
Tobias Koenig committed
459
    textMetaInfo->setWhatsThis(whatsmetainfo);
Laurent Montel's avatar
Laurent Montel committed
460
    metainfoEdit->setToolTip(whatsmetainfo);
Tobias Koenig's avatar
Tobias Koenig committed
461
    textMetaKey->setWhatsThis(whatsmetainfokey);
Laurent Montel's avatar
Laurent Montel committed
462
    metainfokeyEdit->setToolTip(whatsmetainfokey);
463

464 465 466 467 468 469
    fixLayout();
    loadHistory();
}

KfindTabWidget::~KfindTabWidget()
{
Laurent Montel's avatar
Laurent Montel committed
470 471 472 473
    delete pages[0];
    delete pages[1];
    delete pages[2];
    delete bg;
474 475
}

Laurent Montel's avatar
Laurent Montel committed
476
void KfindTabWidget::setURL(const QUrl &url)
477
{
Laurent Montel's avatar
Laurent Montel committed
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
    KConfigGroup conf(KSharedConfig::openConfig(), "History");
    m_url = url;
    QStringList sl = conf.readPathEntry("Directories", QStringList());
    dirBox->clear(); // make sure there is no old Stuff in there

    if (!sl.isEmpty()) {
        dirBox->addItems(sl);
        // If the _searchPath already exists in the list we do not
        // want to add it again
        int indx = sl.indexOf(m_url.toDisplayString());
        if (indx == -1) {
            dirBox->insertItem(0, m_url.toDisplayString()); // make it the first one
            dirBox->setCurrentIndex(0);
        } else {
            dirBox->setCurrentIndex(indx);
        }
    } else {
Laurent Montel's avatar
Laurent Montel committed
495 496 497 498 499 500 501 502 503
        fillDirBox();
    }
}

void KfindTabWidget::fillDirBox()
{
    QDir m_dir(QStringLiteral("/lib"));
    dirBox->insertItem(0, m_url.toDisplayString());
    dirBox->addUrl(QUrl::fromLocalFile(QDir::homePath()));
504
    dirBox->addUrl(QUrl::fromLocalFile(QStringLiteral("/")));
Laurent Montel's avatar
Laurent Montel committed
505 506 507
    dirBox->addUrl(QUrl::fromLocalFile(QStringLiteral("/usr")));
    if (m_dir.exists()) {
        dirBox->addUrl(QUrl::fromLocalFile(QStringLiteral("lib")));
Laurent Montel's avatar
Laurent Montel committed
508
    }
Laurent Montel's avatar
Laurent Montel committed
509 510 511 512 513
    dirBox->addUrl(QUrl::fromLocalFile(QStringLiteral("/home")));
    dirBox->addUrl(QUrl::fromLocalFile(QStringLiteral("/etc")));
    dirBox->addUrl(QUrl::fromLocalFile(QStringLiteral("/var")));
    dirBox->addUrl(QUrl::fromLocalFile(QStringLiteral("/mnt")));
    dirBox->setCurrentIndex(0);
514 515 516 517
}

void KfindTabWidget::saveHistory()
{
Laurent Montel's avatar
Laurent Montel committed
518 519
    save_pattern(nameBox, QStringLiteral("History"), QStringLiteral("Patterns"));
    save_pattern(dirBox, QStringLiteral("History"), QStringLiteral("Directories"));
520 521 522 523
}

void KfindTabWidget::loadHistory()
{
Laurent Montel's avatar
Laurent Montel committed
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
    // Load pattern history
    KConfigGroup conf(KSharedConfig::openConfig(), QStringLiteral("History"));
    QStringList sl = conf.readEntry(QStringLiteral("Patterns"), QStringList());
    if (!sl.isEmpty()) {
        nameBox->addItems(sl);
    } else {
        nameBox->addItem(QStringLiteral("*"));
    }

    sl = conf.readPathEntry(QStringLiteral("Directories"), QStringList());
    if (!sl.isEmpty()) {
        dirBox->addItems(sl);
        // If the _searchPath already exists in the list we do not
        // want to add it again
        int indx = sl.indexOf(m_url.toDisplayString());
        if (indx == -1) {
            dirBox->insertItem(0, m_url.toDisplayString()); // make it the first one
            dirBox->setCurrentIndex(0);
        } else {
            dirBox->setCurrentIndex(indx);
        }
    } else {
Laurent Montel's avatar
Laurent Montel committed
546
        fillDirBox();
Laurent Montel's avatar
Laurent Montel committed
547
    }
548 549
}

550
void KfindTabWidget::slotEditRegExp()
551
{
552
#if 0
Laurent Montel's avatar
Laurent Montel committed
553
    if (!regExpDialog) {
Laurent Montel's avatar
Laurent Montel committed
554
        regExpDialog = KServiceTypeTrader::createInstanceFromQuery<QDialog>(QStringLiteral("KRegExpEditor/KRegExpEditor"), QString(), this);
Laurent Montel's avatar
Laurent Montel committed
555
    }
556

Laurent Montel's avatar
Laurent Montel committed
557 558 559 560
    KRegExpEditorInterface *iface = qobject_cast<KRegExpEditorInterface *>(regExpDialog);
    if (!iface) {
        return;
    }
561

Laurent Montel's avatar
Laurent Montel committed
562
    iface->setRegExp(textEdit->text());
Laurent Montel's avatar
Laurent Montel committed
563
    if (regExpDialog->exec()) {
Laurent Montel's avatar
Laurent Montel committed
564 565
        textEdit->setText(iface->regExp());
    }
566
#endif
567 568
}

569 570
void KfindTabWidget::setFocus()
{
Laurent Montel's avatar
Laurent Montel committed
571 572
    nameBox->setFocus();
    nameBox->lineEdit()->selectAll();
573 574
}

575 576
void KfindTabWidget::slotSizeBoxChanged(int index)
{
Laurent Montel's avatar
Laurent Montel committed
577 578
    sizeEdit->setEnabled((bool)(index != 0));
    sizeUnitBox->setEnabled((bool)(index != 0));
579 580 581 582
}

void KfindTabWidget::setDefaults()
{
583
    const QDate dt = QDate::currentDate().addYears(-1);
584

Laurent Montel's avatar
Laurent Montel committed
585 586
    fromDate->setDate(dt);
    toDate->setDate(QDate::currentDate());
587 588

    timeBox->setValue(1);
Laurent Montel's avatar
Laurent Montel committed
589
    betweenType->setCurrentIndex(1);
590

Laurent Montel's avatar
Laurent Montel committed
591 592 593
    typeBox->setCurrentIndex(0);
    sizeBox->setCurrentIndex(0);
    sizeUnitBox->setCurrentIndex(1);
594 595 596 597 598 599 600 601 602
    sizeEdit->setValue(1);
}

/*
  Checks if dates are correct and popups a error box
  if they are not.
*/
bool KfindTabWidget::isDateValid()
{
Laurent Montel's avatar
Laurent Montel committed
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
    // All files
    if (!findCreated->isChecked()) {
        return true;
    }

    if (rb[1]->isChecked()) {
        if (timeBox->value() > 0) {
            return true;
        }

        KMessageBox::sorry(this, i18n("Unable to search within a period which is less than a minute."));
        return false;
    }

    // If we can not parse either of the dates or
    // "from" date is bigger than "to" date return false.
    const QDate from = fromDate->date();
    const QDate to = toDate->date();

    QString str;
    if (!from.isValid() || !to.isValid()) {
        str = i18n("The date is not valid.");
    } else if (from > to) {
        str = i18n("Invalid date range.");
    } else if (from > QDate::currentDate()) {
        str = i18n("Unable to search dates in the future.");
    }

    if (!str.isEmpty()) {
Laurent Montel's avatar
Laurent Montel committed
632
        KMessageBox::sorry(nullptr, str);
Laurent Montel's avatar
Laurent Montel committed
633 634 635
        return false;
    }
    return true;
636 637 638 639
}

void KfindTabWidget::setQuery(KQuery *query)
{
Laurent Montel's avatar
Laurent Montel committed
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
    KIO::filesize_t size;
    KIO::filesize_t sizeunit;
    bool itemAlreadyContained(false);
    // only start if we have valid dates
    if (!isDateValid()) {
        return;
    }

    const QString trimmedDirBoxText = dirBox->currentText().trimmed();
    const QString tildeExpandedPath = KShell::tildeExpand(trimmedDirBoxText);

    query->setPath(QUrl::fromUserInput(tildeExpandedPath, m_url.toLocalFile(), QUrl::AssumeLocalFile));

    for (int idx = 0; idx < dirBox->count(); idx++) {
        if (dirBox->itemText(idx) == dirBox->currentText()) {
            itemAlreadyContained = true;
        }
    }

    if (!itemAlreadyContained) {
        dirBox->addItem(dirBox->currentText().trimmed(), 0);
    }

    QString regex = nameBox->currentText().isEmpty() ? QStringLiteral("*") : nameBox->currentText();
    query->setRegExp(regex, caseSensCb->isChecked());
    itemAlreadyContained = false;
    for (int idx = 0; idx < nameBox->count(); idx++) {
        if (nameBox->itemText(idx) == nameBox->currentText()) {
            itemAlreadyContained = true;
        }
    }

    if (!itemAlreadyContained) {
        nameBox->addItem(nameBox->currentText(), 0);
    }

    query->setRecursive(subdirsCb->isChecked());

    switch (sizeUnitBox->currentIndex()) {
    case 0:
        sizeunit = 1;  //one byte
        break;
    case 2:
        sizeunit = 1048576;  //1Mi
        break;
    case 3:
        sizeunit = 1073741824;  //1Gi
        break;
    case 1:  // fall to default case
    default:
        sizeunit = 1024; //1Ki
        break;
    }
    size = sizeEdit->value() * sizeunit;
694

695 696
// TODO: troeder: do we need this check since it is very unlikely
// to exceed ULLONG_MAX with INT_MAX * 1024^3.
697
// Or is there an arch where this can happen?
698
#if 0
Laurent Montel's avatar
Laurent Montel committed
699 700 701 702 703 704 705 706 707 708
    if (size < 0) { // overflow
        if (KMessageBox::warningYesNo(this, i18n("Size is too big. Set maximum size value?"), i18n("Error"), i18n("Set"), i18n("Do Not Set"))
            == KMessageBox::Yes) {
            sizeEdit->setValue(INT_MAX);
            sizeUnitBox->setCurrentIndex(0);
            size = INT_MAX;
        } else {
            return;
        }
    }
709 710
#endif

Laurent Montel's avatar
Laurent Montel committed
711 712 713 714 715
    // set range mode and size value
    query->setSizeRange(sizeBox->currentIndex(), size, 0);

    // dates
    QDateTime epoch;
716
    epoch.setSecsSinceEpoch(0);
Laurent Montel's avatar
Laurent Montel committed
717 718 719 720 721 722 723

    // Add date predicate
    if (findCreated->isChecked()) { // Modified
        if (rb[0]->isChecked()) { // Between dates
            const QDate &from = fromDate->date();
            const QDate &to = toDate->date();
            // do not generate negative numbers .. find doesn't handle that
724 725 726 727
#if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
            time_t time1 = epoch.secsTo(QDateTime(from));
            time_t time2 = epoch.secsTo(QDateTime(to.addDays(1))) - 1; // Include the last day
#else
728 729
            time_t time1 = epoch.secsTo(QDateTime(from.startOfDay()));
            time_t time2 = epoch.secsTo(QDateTime(to.addDays(1).startOfDay())) - 1; // Include the last day
730
#endif
Laurent Montel's avatar
Laurent Montel committed
731 732 733

            query->setTimeRange(time1, time2);
        } else {
Laurent Montel's avatar
Laurent Montel committed
734
            time_t cur = time(nullptr);
Laurent Montel's avatar
Laurent Montel committed
735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759
            time_t minutes = cur;

            switch (betweenType->currentIndex()) {
            case 0: // minutes
                minutes = timeBox->value();
                break;
            case 1: // hours
                minutes = 60 * timeBox->value();
                break;
            case 2: // days
                minutes = 60 * 24 * timeBox->value();
                break;
            case 3: // months
                minutes = 60 * 24 * (time_t)(timeBox->value() * 30.41667);
                break;
            case 4: // years
                minutes = 12 * 60 * 24 * (time_t)(timeBox->value() * 30.41667);
                break;
            }

            query->setTimeRange(cur - minutes * 60, 0);
        }
    } else {
        query->setTimeRange(0, 0);
    }
760

Laurent Montel's avatar
Laurent Montel committed
761 762
    query->setUsername(m_usernameBox->currentText());
    query->setGroupname(m_groupBox->currentText());
763

Laurent Montel's avatar
Laurent Montel committed
764
    query->setFileType(typeBox->currentIndex());
765

766
    int id = typeBox->currentIndex() - specialMimeTypeCount - 1 /*the separator*/;
767

768
    if ((id >= -4) && (id < (int)m_types.count())) {
Laurent Montel's avatar
Laurent Montel committed
769
        switch (id) {
770
        case -4:
Laurent Montel's avatar
Laurent Montel committed
771 772
            query->setMimeType(m_ImageTypes);
            break;
773
        case -3:
Laurent Montel's avatar
Laurent Montel committed
774 775
            query->setMimeType(m_VideoTypes);
            break;
776
        case -2:
Laurent Montel's avatar
Laurent Montel committed
777 778 779
            query->setMimeType(m_AudioTypes);
            break;
        default:
Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
780
            query->setMimeType(QStringList() += m_types.value(id).name());
Laurent Montel's avatar
Laurent Montel committed
781 782 783
        }
    } else {
        query->setMimeType(QStringList());
784
    }
Laurent Montel's avatar
Laurent Montel committed
785 786 787 788 789 790 791 792 793 794 795

    //Metainfo
    query->setMetaInfo(metainfoEdit->text(), metainfokeyEdit->text());

    //Use locate to speed-up search ?
    query->setUseFileIndex(useLocateCb->isChecked());

    query->setShowHiddenFiles(hiddenFilesCb->isChecked());

    query->setContext(textEdit->text(), caseContextCb->isChecked(),
                      binaryContextCb->isChecked(), regexpContentCb->isChecked());
796 797 798 799
}

void KfindTabWidget::getDirectory()
{
Laurent Montel's avatar
Laurent Montel committed
800 801
    const QString result
        = QFileDialog::getExistingDirectory(this, QString(), dirBox->currentText().trimmed());
Laurent Montel's avatar
Laurent Montel committed
802 803 804 805 806 807 808 809 810 811 812

    if (!result.isEmpty()) {
        for (int i = 0; i < dirBox->count(); i++) {
            if (result == dirBox->itemText(i)) {
                dirBox->setCurrentIndex(i);
                return;
            }
        }
        dirBox->insertItem(0, result);
        dirBox->setCurrentIndex(0);
    }
813 814 815 816
}

void KfindTabWidget::beginSearch()
{
817
///  dirlister->openUrl(KUrl(dirBox->currentText().trimmed()));
818

Laurent Montel's avatar
Laurent Montel committed
819
    saveHistory();
820

821 822
    for(QWidget *page : pages) {
        page->setEnabled(false);
Laurent Montel's avatar
Laurent Montel committed
823
    }
824 825 826 827
}

void KfindTabWidget::endSearch()
{
828 829
    for(QWidget *page : pages) {
        page->setEnabled(true);
830
    }
831 832 833 834 835 836 837 838
}

/*
  Disables/enables all edit fields depending on their
  respective check buttons.
*/
void KfindTabWidget::fixLayout()
{
Laurent Montel's avatar
Laurent Montel committed
839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866
    int i;
    // If "All files" is checked - disable all edits
    // and second radio group on page two

    if (!findCreated->isChecked()) {
        fromDate->setEnabled(false);
        toDate->setEnabled(false);
        andL->setEnabled(false);
        timeBox->setEnabled(false);
        for (i = 0; i < 2; ++i) {
            rb[i]->setEnabled(false);
        }
        betweenType->setEnabled(false);
    } else {
        for (i = 0; i < 2; ++i) {
            rb[i]->setEnabled(true);
        }

        fromDate->setEnabled(rb[0]->isChecked());
        toDate->setEnabled(rb[0]->isChecked());
        andL->setEnabled(rb[0]->isEnabled());
        timeBox->setEnabled(rb[1]->isChecked());
        betweenType->setEnabled(rb[1]->isChecked());
    }

    // Size box on page three
    sizeEdit->setEnabled(sizeBox->currentIndex() != 0);
    sizeUnitBox->setEnabled(sizeBox->currentIndex() != 0);
867 868
}

869 870
bool KfindTabWidget::isSearchRecursive()
{
Laurent Montel's avatar
Laurent Montel committed
871
    return subdirsCb->isChecked();
872 873
}

874
void KfindTabWidget::slotUpdateDateLabelsForNumber(int value)
875
{
Laurent Montel's avatar
Laurent Montel committed
876
    updateDateLabels(betweenType->currentIndex(), value);
877 878 879 880
}

void KfindTabWidget::slotUpdateDateLabelsForType(int index)
{
Laurent Montel's avatar
Laurent Montel committed
881
    updateDateLabels(index, timeBox->value());
882 883 884 885
}

void KfindTabWidget::updateDateLabels(int type, int value)
{
Laurent Montel's avatar
Laurent Montel committed
886 887 888 889 890 891 892 893 894
    QString typeKey(type == 0 ? QLatin1Char('i') : type == 1 ? QLatin1Char('h') : type == 2 ? QLatin1Char('d') : type == 3 ? QLatin1Char('m') : QLatin1Char('y'));
    rb[1]->setText(ki18ncp("during the previous minute(s)/hour(s)/...; "
                           "dynamic context 'type': 'i' minutes, 'h' hours, 'd' days, 'm' months, 'y' years",
                           "&during the previous", "&during the previous").subs(value).inContext(QStringLiteral("type"), typeKey).toString());
    betweenType->setItemText(0, i18ncp("use date ranges to search files by modified time", "minute", "minutes", value));
    betweenType->setItemText(1, i18ncp("use date ranges to search files by modified time", "hour", "hours", value));
    betweenType->setItemText(2, i18ncp("use date ranges to search files by modified time", "day", "days", value));
    betweenType->setItemText(3, i18ncp("use date ranges to search files by modified time", "month", "months", value));
    betweenType->setItemText(4, i18ncp("use date ranges to search files by modified time", "year", "years", value));
895 896 897 898
}

void KfindTabWidget::slotUpdateByteComboBox(int value)
{
Laurent Montel's avatar
Laurent Montel committed
899
    sizeUnitBox->setItemText(0, i18np("Byte", "Bytes", value));
900 901
}

902 903 904
/**
   Digit validator. Allows only digits to be typed.
**/
Laurent Montel's avatar
Laurent Montel committed
905 906
KDigitValidator::KDigitValidator(QWidget *parent)
    : QValidator(parent)
907
{
Laurent Montel's avatar
Laurent Montel committed
908
    r = new QRegExp(QStringLiteral("^[0-9]*$"));
909 910 911
}

KDigitValidator::~KDigitValidator()
Laurent Montel's avatar
Laurent Montel committed
912
{
Laurent Montel's avatar
Laurent Montel committed
913
    delete r;
Laurent Montel's avatar
Laurent Montel committed
914
}
915

Laurent Montel's avatar
Laurent Montel committed
916
QValidator::State KDigitValidator::validate(QString &input, int &) const
917 <