dirresourceimportdialog.cpp 18 KB
Newer Older
David Jarvie's avatar
David Jarvie committed
1
2
3
/*
 *  dirresourceimportdialog.cpp - configuration dialog to import directory resources
 *  Program:  kalarm
4
 *  SPDX-FileCopyrightText: 2020 David Jarvie <djarvie@kde.org>
David Jarvie's avatar
David Jarvie committed
5
 *
6
 *  SPDX-License-Identifier: GPL-2.0-or-later
David Jarvie's avatar
David Jarvie 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
32
33
 */

#include "dirresourceimportdialog.h"
#include "dirresourceimportdialog_p.h"
#include "ui_dirresourceimportdialog_intro.h"
#include "ui_dirresourceimportdialog_type.h"

#include "resources.h"
#include "fileresource.h"

#include <KFileItem>
#include <KColorScheme>
#include <KLocalizedString>
#include <KIO/StatJob>

#include <QTimer>

using namespace KAlarmCal;


/******************************************************************************
* Constructor.
*/
DirResourceImportDialog::DirResourceImportDialog(const QString& dirResourceName, const QString& dirResourcePath, KAlarmCal::CalEvent::Types types, QWidget* parent)
    : KAssistantDialog(parent)
    , mAlarmTypes(types)
{
David Jarvie's avatar
David Jarvie committed
34
    setWindowTitle(i18nc("@title:window", "Import Directory Resource"));
David Jarvie's avatar
David Jarvie committed
35
36
37
38
    // Remove Help button
    buttonBox()->removeButton(button(QDialogButtonBox::Help));

    mPageIntro = new DirResourceImportIntroWidget(dirResourceName, dirResourcePath, types, this);
David Jarvie's avatar
David Jarvie committed
39
    addPage(mPageIntro, i18nc("@title:tab", "Import Calendar Directory Resource"));
David Jarvie's avatar
David Jarvie committed
40
41
42
43
44
45

    mAlarmTypeCount = 0;
    if (mAlarmTypes & CalEvent::ACTIVE)
    {
        ++mAlarmTypeCount;
        mPageActive = new DirResourceImportTypeWidget(CalEvent::ACTIVE, this);
David Jarvie's avatar
David Jarvie committed
46
        addPage(mPageActive, i18nc("@title:tab", "Import Active Alarms"));
David Jarvie's avatar
David Jarvie committed
47
48
49
50
51
52
53
54
        connect(mPageActive, &DirResourceImportTypeWidget::status, this, &DirResourceImportDialog::typeStatusChanged);
        mLastPage = mPageActive;
    }

    if (mAlarmTypes & CalEvent::ARCHIVED)
    {
        ++mAlarmTypeCount;
        mPageArchived = new DirResourceImportTypeWidget(CalEvent::ARCHIVED, this);
David Jarvie's avatar
David Jarvie committed
55
        addPage(mPageArchived, i18nc("@title:tab", "Import Archived Alarms"));
David Jarvie's avatar
David Jarvie committed
56
57
58
59
60
61
62
63
        connect(mPageArchived, &DirResourceImportTypeWidget::status, this, &DirResourceImportDialog::typeStatusChanged);
        mLastPage = mPageArchived;
    }

    if (mAlarmTypes & CalEvent::TEMPLATE)
    {
        ++mAlarmTypeCount;
        mPageTemplate = new DirResourceImportTypeWidget(CalEvent::TEMPLATE, this);
David Jarvie's avatar
David Jarvie committed
64
        addPage(mPageTemplate, i18nc("@title:tab", "Import Alarm Templates"));
David Jarvie's avatar
David Jarvie committed
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
        connect(mPageTemplate, &DirResourceImportTypeWidget::status, this, &DirResourceImportDialog::typeStatusChanged);
        mLastPage = mPageTemplate;
    }

    connect(this, &KPageDialog::currentPageChanged, this, &DirResourceImportDialog::pageChanged);
}

DirResourceImportDialog::~DirResourceImportDialog()
{
}

/******************************************************************************
* Return the existing resource to import into, for a specified alarm type.
*/
ResourceId DirResourceImportDialog::resourceId(KAlarmCal::CalEvent::Type type) const
{
    const DirResourceImportTypeWidget* page = typePage(type);
    return page ? page->resourceId() : -1;
}

/******************************************************************************
* Return the new calendar file URL, for a specified alarm type.
*/
QUrl DirResourceImportDialog::url(KAlarmCal::CalEvent::Type type) const
{
    const DirResourceImportTypeWidget* page = typePage(type);
    return page ? page->url() : QUrl();
}

/******************************************************************************
* Return the resource's display name, for a specified alarm type.
*/
QString DirResourceImportDialog::displayName(KAlarmCal::CalEvent::Type type) const
{
    const DirResourceImportTypeWidget* page = typePage(type);
    return page ? page->displayName() : QString();
}

/******************************************************************************
* Set a validation function to apply to an entered URL.
*/
void DirResourceImportDialog::setUrlValidation(QString (*func)(const QUrl&))
{
    if (mPageActive)
        mPageActive->setUrlValidation(func);
    if (mPageArchived)
        mPageArchived->setUrlValidation(func);
    if (mPageTemplate)
        mPageTemplate->setUrlValidation(func);
}

/******************************************************************************
* When a new page is displayed, set appropriate heights for elements within the
* page, and enable/disable elements according to their status.
*/
void DirResourceImportDialog::pageChanged(KPageWidgetItem* current, KPageWidgetItem* before)
{
    Q_UNUSED(before);

    if (current)
    {
126
        auto page = static_cast<DirResourceImportWidgetBase*>(current->widget());
David Jarvie's avatar
David Jarvie committed
127
        page->setTextSizes();
128
        auto typePage = qobject_cast<DirResourceImportTypeWidget*>(page);
David Jarvie's avatar
David Jarvie committed
129
130
131
132
133
134
135
136
137
138
139
140
        if (typePage)
            typePage->validate();
    }
}

/******************************************************************************
* Called when the data entered into an alarm type import page has changed.
* Enable or disable the Next button, depending on whether the entered data is
* valid or not.
*/
void DirResourceImportDialog::typeStatusChanged(bool ok)
{
141
    auto page = qobject_cast<DirResourceImportTypeWidget*>(currentPage()->widget());
David Jarvie's avatar
David Jarvie committed
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
    if (page)
    {
        nextButton()->setEnabled(ok  &&  (page != mLastPage));
        finishButton()->setEnabled(ok  &&  (page == mLastPage));
    }
}

const DirResourceImportTypeWidget* DirResourceImportDialog::typePage(KAlarmCal::CalEvent::Type type) const
{
    if (mAlarmTypes & type)
    {
        switch (type)
        {
            case CalEvent::ACTIVE:    return mPageActive;
            case CalEvent::ARCHIVED:  return mPageArchived;
            case CalEvent::TEMPLATE:  return mPageTemplate;
            default:
                break;
        }
    }
    return nullptr;
}


/*=============================================================================
= Class DirResourceImportWidgetBase
= Base class for page widgets.
=============================================================================*/
DirResourceImportWidgetBase::DirResourceImportWidgetBase(QWidget* parent)
    : QWidget(parent)
{
}


/*=============================================================================
= Class DirResourceImportIntroWidget
= The first page of the directory resource import dialog, which gives general
= information to the user.
=============================================================================*/
DirResourceImportIntroWidget::DirResourceImportIntroWidget(const QString& dirResourceName, const QString& dirResourcePath, KAlarmCal::CalEvent::Types types, QWidget* parent)
    : DirResourceImportWidgetBase(parent)
{
    mUi = new Ui_DirResourceImportIntroWidget;
    mUi->setupUi(this);
    mUi->dirNameLabel->setText(dirResourceName);
    mUi->dirPathLabel->setText(dirResourcePath);

    QStringList typeNames;
    if (types & CalEvent::ACTIVE)
David Jarvie's avatar
David Jarvie committed
191
        typeNames += i18nc("@item:intext", "Active alarms");
David Jarvie's avatar
David Jarvie committed
192
    if (types & CalEvent::ARCHIVED)
David Jarvie's avatar
David Jarvie committed
193
        typeNames += i18nc("@item:intext", "Archived alarms");
David Jarvie's avatar
David Jarvie committed
194
    if (types & CalEvent::TEMPLATE)
David Jarvie's avatar
David Jarvie committed
195
        typeNames += i18nc("@item:intext", "Alarm templates");
David Jarvie's avatar
David Jarvie committed
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
    mUi->dirTypesLabel->setText(typeNames.join(QStringLiteral(", ")));

    if (typeNames.size() > 1)
        mUi->warning1->setVisible(false);
    else
        mUi->warning2->setVisible(false);
}

DirResourceImportIntroWidget::~DirResourceImportIntroWidget()
{
    delete mUi;
}

/******************************************************************************
* Called when the page is displayed, to set appropriate heights for QLabel
* elements with text wrapping, and then remove empty space between widgets.
* By default, if QLabel contains more than one line of text, it often occupies
* more space than required, and calling setMinimumHeight() doesn't affect this.
*/
void DirResourceImportIntroWidget::setTextSizes()
{
    mUi->warning1->setFixedHeight(mUi->warning1->height());
    mUi->warning2->setFixedHeight(mUi->warning2->height());
    mUi->note->setFixedHeight(mUi->note->height());
    setFixedHeight(sizeHint().height());
}


/*=============================================================================
= Class DirResourceImportTypeWidget
= The page of the directory resource import dialog which allows the user to
= specify how to import one alarm type.
=============================================================================*/
DirResourceImportTypeWidget::DirResourceImportTypeWidget(CalEvent::Type alarmType, QWidget* parent)
    : DirResourceImportWidgetBase(parent)
{
    mUi = new Ui_DirResourceImportTypeWidget;
    mUi->setupUi(this);

    const QVector<Resource> resources = Resources::allResources<FileResource>(alarmType, Resources::DefaultFirst | Resources::DisplayName);
    if (resources.isEmpty())
    {
        mUi->mergeRadio->setVisible(false);
        mUi->mergeRadio->setEnabled(false);
        mUi->mergeResource->setVisible(false);
    }
    else
    {
        for (const Resource& resource : resources)
            mUi->mergeResource->addItem(resource.displayName(), QVariant(resource.id()));
    }

David Jarvie's avatar
David Jarvie committed
248
    connect(mUi->optionGroup, QOverload<QAbstractButton*, bool>::of(&QButtonGroup::buttonToggled), this, &DirResourceImportTypeWidget::importTypeSelected);
David Jarvie's avatar
David Jarvie committed
249
250

    mUi->pathRequester->setMode(KFile::File);
251
    mUi->pathRequester->setFilter(QStringLiteral("*.ics|%1").arg(i18nc("@item:inlistbox File type selection filter", "Calendar files")));
David Jarvie's avatar
David Jarvie committed
252
253
254
    mUi->statusLabel->setText(QString());
    mUi->pathRequester->setFocus();
    mUi->pathRequester->installEventFilter(this);
255
    connect(mUi->pathRequester, QOverload<const QString &>::of(&KUrlRequester::returnPressed), this, [this]() { validate(); });
David Jarvie's avatar
David Jarvie committed
256
257
258
259
260
261
262
263
264
265
266
267
268
    connect(mUi->pathRequester, &KUrlRequester::urlSelected, this, [this]() { validate(); });
    connect(mUi->pathRequester, &KUrlRequester::textChanged, this, [this]() { setStatus(false); });
    connect(mUi->nameText, &QLineEdit::textChanged, this, [this]() { validate(); });

    // Indent fields beneath each radio button option.
    QRadioButton radio(this);
    QStyleOptionButton opt;
    opt.initFrom(&radio);
    int indentWidth = style()->subElementRect(QStyle::SE_RadioButtonIndicator, &opt).width();
    mUi->grid->setColumnMinimumWidth(0, indentWidth);
    mUi->grid->setColumnStretch(1, 1);

    importTypeSelected();
David Jarvie's avatar
David Jarvie committed
269
    QTimer::singleShot(0, this, &DirResourceImportTypeWidget::validate);   //NOLINT(clang-analyzer-cplusplus.NewDeleteLeaks)
David Jarvie's avatar
David Jarvie committed
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
}

DirResourceImportTypeWidget::~DirResourceImportTypeWidget()
{
    delete mUi;
}

/******************************************************************************
* Return the existing resource ID to import into.
*/
ResourceId DirResourceImportTypeWidget::resourceId() const
{
    return mUi->mergeRadio->isChecked() ? mUi->mergeResource->currentData().toLongLong() : -1;
}

/******************************************************************************
* Return the new calendar file URL.
*/
QUrl DirResourceImportTypeWidget::url() const
{
    return mUi->newRadio->isChecked() ? mUi->pathRequester->url() : QUrl();
}

/******************************************************************************
* Return the resource's display name.
*/
QString DirResourceImportTypeWidget::displayName() const
{
    return mUi->newRadio->isChecked() ? mUi->nameText->text() : QString();
}

/******************************************************************************
* Notify the page that it is the last page.
*/
void DirResourceImportTypeWidget::setLastPage()
{
    mLastPage = true;
}

/******************************************************************************
* Set a validation function to apply to an entered URL.
*/
void DirResourceImportTypeWidget::setUrlValidation(QString (*func)(const QUrl&))
{
    mUrlValidationFunc = func;
}

/******************************************************************************
* Called when the page is displayed, to set appropriate heights for QLabel
* elements with text wrapping, and then remove empty space between widgets.
* By default, if QLabel contains more than one line of text, it often occupies
* more space than required, and calling setMinimumHeight() doesn't affect this.
*/
void DirResourceImportTypeWidget::setTextSizes()
{
325
    const int spacing = style()->pixelMetric(QStyle::PM_LayoutVerticalSpacing);
David Jarvie's avatar
David Jarvie committed
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
    mUi->spacer1->changeSize(10, 2*spacing, QSizePolicy::Fixed, QSizePolicy::Fixed);
    mUi->spacer2->changeSize(10, 2*spacing, QSizePolicy::Fixed, QSizePolicy::Fixed);
    mUi->spacer3->changeSize(10, 2*spacing, QSizePolicy::Fixed, QSizePolicy::Fixed);
    setFixedHeight(sizeHint().height());
}

bool DirResourceImportTypeWidget::eventFilter(QObject* o, QEvent* e)
{
    if (o == mUi->pathRequester  &&  e->type() == QEvent::FocusOut)
        validate();
    return QWidget::eventFilter(o, e);
}

/******************************************************************************
* Called when an import destination type radio button has been selected.
* Enable or disable the other controls.
*/
void DirResourceImportTypeWidget::importTypeSelected()
{
    const bool importMerge = mUi->mergeRadio->isChecked();
    const bool importNew   = mUi->newRadio->isChecked();
    mUi->mergeResource->setEnabled(importMerge);
    mUi->pathLabel->setEnabled(importNew);
    mUi->pathRequester->setEnabled(importNew);
    mUi->statusLabel->setEnabled(importNew);
    mUi->nameLabel->setEnabled(importNew);
    mUi->nameText->setEnabled(importNew);

    if (importNew)
        validate();
    else if (importMerge  ||  mUi->noRadio->isChecked())
        Q_EMIT status(true);
}

/******************************************************************************
* Validate the current user input. If invalid, disable the OK button.
* Reply = false if invalid, or if waiting for remote validity to be checked.
*/
void DirResourceImportTypeWidget::validate()
{
    if (!mUi->newRadio->isChecked())
        return;

    // Validate URL first, in order to display any error message.
    const QUrl currentUrl = mUi->pathRequester->url();
    if (mUi->pathRequester->text().trimmed().isEmpty() || currentUrl.isEmpty())
    {
        setStatus(false);
        return;
    }
    if (mUrlValidationFunc)
    {
        const QString error = (*mUrlValidationFunc)(currentUrl);
        if (!error.isEmpty())
        {
            setStatus(false, error);
            return;
        }
    }

    if (!currentUrl.isLocalFile())
    {
        // It's a remote file.
        // Check whether the file can be read or written.
        if (mStatJob)
            mStatJob->kill();
        mCheckingDir = false;
        mStatJob = KIO::statDetails(currentUrl, KIO::StatJob::SourceSide, KIO::StatDetail::StatNoDetails, KIO::HideProgressInfo);
        connect(mStatJob, &KIO::StatJob::result, this, &DirResourceImportTypeWidget::slotStatJobResult);

        // Disable the OK button until the file's status is determined.
        setStatus(false, i18nc("@info:status", "Checking file information..."), false);
        return;
    }

    // It's a local file. Check that it doesn't already exist, and that it can be created.
    QFileInfo file(currentUrl.toLocalFile());
    if (file.exists())
    {
        setStatus(false, i18nc("@info:status", "Error! File already exists."));
        return;
    }
    QFileInfo dir(file.path());
    if (!dir.exists())
    {
        setStatus(false, i18nc("@info:status", "Error! Cannot create file (directory does not exist)."));
        return;
    }
    if (!dir.isWritable())
    {
        setStatus(false, i18nc("@info:status", "Error! Cannot create file (directory is not writable)."));
        return;
    }

    if (mUi->nameText->text().trimmed().isEmpty())
    {
        setStatus(false);
        return;
    }

    setStatus(true);
}

/******************************************************************************
* Called when the status of the remote URL has been determined.
* Ensures that the URL doesn't exist, but can be created.
*/
void DirResourceImportTypeWidget::slotStatJobResult(KJob* job)
{
435
    auto statJob = static_cast<KIO::StatJob*>(job);
David Jarvie's avatar
David Jarvie committed
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
    mStatJob = nullptr;

    if (!mCheckingDir)
    {
        // Results from checking the remote file.
        if (job->error() == KIO::ERR_DOES_NOT_EXIST)
        {
            // The file doesn't exist (as expected), so check that the file's
            // directory is writable.
            mCheckingDir = true;
            mStatJob = KIO::statDetails(KIO::upUrl(mUi->pathRequester->url()),
                                        KIO::StatJob::SourceSide,
                                        KIO::StatDetail::StatDefaultDetails,
                                        KIO::HideProgressInfo);
            connect(mStatJob, &KIO::StatJob::result, this, &DirResourceImportTypeWidget::slotStatJobResult);
            return;
        }
        setStatus(false, i18nc("@info:status", "Error! File already exists."));
    }
    else
    {
        // Results from checking the remote file's directory.
        mCheckingDir = false;
        if (job->error())
        {
            if (job->error() == KIO::ERR_DOES_NOT_EXIST)
                setStatus(false, i18nc("@info:status", "Error! Cannot create file (directory does not exist)."));
            else
                setStatus(false, i18nc("@info:status", "Error! Cannot create file (directory is not writable)."));
        }
        else
        {
            KFileItem fi(statJob->statResult(), KIO::upUrl(mUi->pathRequester->url()));
            if (!fi.isDir())
David Jarvie's avatar
David Jarvie committed
470
                setStatus(false, i18nc("@info", "Error! Cannot create file (directory does not exist)."));
David Jarvie's avatar
David Jarvie committed
471
            else if (!fi.isWritable())
David Jarvie's avatar
David Jarvie committed
472
                setStatus(false, i18nc("@info", "Error! Cannot create file (directory is not writable)."));
David Jarvie's avatar
David Jarvie committed
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
            else
                setStatus(true);
        }
    }
}

/******************************************************************************
* Set or clear the URL status message, and notify the dialog of the new status.
*/
void DirResourceImportTypeWidget::setStatus(bool ok, const QString& errorMessage, bool errorColour)
{
    if (ok)
        mUi->statusLabel->setText(QString());
    else
    {
        QPalette pal = mUi->pathLabel->palette();
        if (errorColour  &&  !errorMessage.isEmpty())
            pal.setColor(QPalette::WindowText, KColorScheme(QPalette::Active).foreground(KColorScheme::NegativeText).color());
        mUi->statusLabel->setPalette(pal);
        mUi->statusLabel->setText(errorMessage);
    }
    Q_EMIT status(ok);
}

// vim: et sw=4: