utils.cpp 29.7 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/*
  Copyright (c) 2009, 2010 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com
    Author: Frank Osterfeld <osterfeld@kde.org>
    Author: Andras Mantia <andras@kdab.com>

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License along
  with this program; if not, write to the Free Software Foundation, Inc.,
  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

  As a special exception, permission is given to link this program
  with any edition of Qt, and distribute the resulting executable,
  without including the source code for Qt in the source distribution.
*/

#include "utils.h"
#include "kcalprefs.h"
27

28
29
30
31
32
#include <Collection>
#include <CollectionDialog>
#include <EntityDisplayAttribute>
#include <EntityTreeModel>
#include <Item>
33
34

#include <AkonadiCore/AgentInstance>
35
#include <AkonadiCore/AgentManager>
36
#include <AkonadiCore/EntityDisplayAttribute>
37
38
39
40
41
42
#include <Akonadi/Calendar/ETMCalendar>
#include <Akonadi/Calendar/PublishDialog>
#include <akonadi/calendar/calendarsettings.h>

#include <KHolidays/HolidayRegion>

43
44
45
46
47
48
49
50
51
#include <KCalendarCore/CalFilter>
#include <KCalendarCore/Event>
#include <KCalendarCore/FreeBusy>
#include <KCalendarCore/Incidence>
#include <KCalendarCore/Journal>
#include <KCalendarCore/MemoryCalendar>
#include <KCalendarCore/Todo>
#include <KCalendarCore/ICalFormat>
#include <KCalendarCore/FileStorage>
52
53
54
55
56
57
58

#include <KCalUtils/DndFactory>
#include <KCalUtils/ICalDrag>
#include <KCalUtils/VCalDrag>

#include <KMessageBox>
#include <KIO/FileCopyJob>
59
#include <KLocalizedString>
60

61
#include <QApplication>
62
63
64
65
66
67
68
#include <QUrl>
#include <QAbstractItemModel>
#include <QDrag>
#include <QMimeData>
#include <QModelIndex>
#include <QPointer>
#include <QFileDialog>
69
#include <QUrlQuery>
70
#include <QRegularExpression>
71
#include <QTimeZone>
72
#include <QStyle>
73
74
75
76
77

#include "calendarsupport_debug.h"

using namespace CalendarSupport;
using namespace KHolidays;
78
using namespace KCalendarCore;
79

80
KCalendarCore::Incidence::Ptr CalendarSupport::incidence(const Akonadi::Item &item)
81
82
83
{
    //relying on exception for performance reasons
    try {
84
        return item.payload<KCalendarCore::Incidence::Ptr>();
Laurent Montel's avatar
Laurent Montel committed
85
    } catch (const Akonadi::PayloadException &) {
86
        return KCalendarCore::Incidence::Ptr();
87
88
89
    }
}

90
KCalendarCore::Event::Ptr CalendarSupport::event(const Akonadi::Item &item)
91
92
93
{
    //relying on exception for performance reasons
    try {
94
        KCalendarCore::Incidence::Ptr incidence = item.payload<KCalendarCore::Incidence::Ptr>();
95
        if (hasEvent(incidence)) {
96
            return item.payload<KCalendarCore::Event::Ptr>();
97
        }
Laurent Montel's avatar
Laurent Montel committed
98
    } catch (const Akonadi::PayloadException &) {
99
        return KCalendarCore::Event::Ptr();
100
    }
101
    return KCalendarCore::Event::Ptr();
102
103
}

104
KCalendarCore::Event::Ptr CalendarSupport::event(const KCalendarCore::Incidence::Ptr &incidence)
105
106
{
    if (hasEvent(incidence)) {
107
        return incidence.staticCast<KCalendarCore::Event>();
108
    }
109
    return KCalendarCore::Event::Ptr();
110
111
}

112
KCalendarCore::Incidence::List CalendarSupport::incidencesFromItems(const Akonadi::Item::List &items)
113
{
114
    KCalendarCore::Incidence::List incidences;
Laurent Montel's avatar
Laurent Montel committed
115
    for (const Akonadi::Item &item : items) {
116
        if (const KCalendarCore::Incidence::Ptr e = CalendarSupport::incidence(item)) {
117
118
119
120
121
122
            incidences.push_back(e);
        }
    }
    return incidences;
}

123
KCalendarCore::Todo::Ptr CalendarSupport::todo(const Akonadi::Item &item)
124
125
{
    try {
126
        KCalendarCore::Incidence::Ptr incidence = item.payload<KCalendarCore::Incidence::Ptr>();
127
        if (hasTodo(incidence)) {
128
            return item.payload<KCalendarCore::Todo::Ptr>();
129
        }
Laurent Montel's avatar
Laurent Montel committed
130
    } catch (const Akonadi::PayloadException &) {
131
        return KCalendarCore::Todo::Ptr();
132
    }
133
    return KCalendarCore::Todo::Ptr();
134
135
}

136
KCalendarCore::Todo::Ptr CalendarSupport::todo(const KCalendarCore::Incidence::Ptr &incidence)
137
138
{
    if (hasTodo(incidence)) {
139
        return incidence.staticCast<KCalendarCore::Todo>();
140
    }
141
    return KCalendarCore::Todo::Ptr();
142
143
}

144
KCalendarCore::Journal::Ptr CalendarSupport::journal(const Akonadi::Item &item)
145
146
{
    try {
147
        KCalendarCore::Incidence::Ptr incidence = item.payload<KCalendarCore::Incidence::Ptr>();
148
        if (hasJournal(incidence)) {
149
            return item.payload<KCalendarCore::Journal::Ptr>();
150
        }
Laurent Montel's avatar
Laurent Montel committed
151
    } catch (const Akonadi::PayloadException &) {
152
        return KCalendarCore::Journal::Ptr();
153
    }
154
    return KCalendarCore::Journal::Ptr();
155
156
}

157
KCalendarCore::Journal::Ptr CalendarSupport::journal(const KCalendarCore::Incidence::Ptr &incidence)
158
159
{
    if (hasJournal(incidence)) {
160
        return incidence.staticCast<KCalendarCore::Journal>();
161
    }
162
    return KCalendarCore::Journal::Ptr();
163
164
165
166
}

bool CalendarSupport::hasIncidence(const Akonadi::Item &item)
{
167
    return item.hasPayload<KCalendarCore::Incidence::Ptr>();
168
169
170
171
}

bool CalendarSupport::hasEvent(const Akonadi::Item &item)
{
172
    return item.hasPayload<KCalendarCore::Event::Ptr>();
173
174
}

175
bool CalendarSupport::hasEvent(const KCalendarCore::Incidence::Ptr &incidence)
176
{
177
    return incidence && incidence->type() == KCalendarCore::Incidence::TypeEvent;
178
179
180
181
}

bool CalendarSupport::hasTodo(const Akonadi::Item &item)
{
182
    return item.hasPayload<KCalendarCore::Todo::Ptr>();
183
184
}

185
bool CalendarSupport::hasTodo(const KCalendarCore::Incidence::Ptr &incidence)
186
{
187
    return incidence && incidence->type() == KCalendarCore::Incidence::TypeTodo;
188
189
190
191
}

bool CalendarSupport::hasJournal(const Akonadi::Item &item)
{
192
    return item.hasPayload<KCalendarCore::Journal::Ptr>();
193
194
}

195
bool CalendarSupport::hasJournal(const KCalendarCore::Incidence::Ptr &incidence)
196
{
197
    return incidence && incidence->type() == KCalendarCore::Incidence::TypeJournal;
198
199
}

200
QMimeData *CalendarSupport::createMimeData(const Akonadi::Item::List &items)
201
202
{
    if (items.isEmpty()) {
Laurent Montel's avatar
Laurent Montel committed
203
        return nullptr;
204
205
    }

206
    KCalendarCore::MemoryCalendar::Ptr cal(new KCalendarCore::MemoryCalendar(QTimeZone::systemTimeZone()));
207
208
209

    QList<QUrl> urls;
    int incidencesFound = 0;
Laurent Montel's avatar
Laurent Montel committed
210
    for (const Akonadi::Item &item : items) {
211
        const KCalendarCore::Incidence::Ptr incidence(CalendarSupport::incidence(item));
212
213
214
215
216
        if (!incidence) {
            continue;
        }
        ++incidencesFound;
        urls.push_back(item.url());
217
        KCalendarCore::Incidence::Ptr i(incidence->clone());
218
219
220
221
        cal->addIncidence(i);
    }

    if (incidencesFound == 0) {
Laurent Montel's avatar
Laurent Montel committed
222
        return nullptr;
223
224
225
226
227
228
229
230
231
232
233
    }

    std::unique_ptr<QMimeData> mimeData(new QMimeData);

    mimeData->setUrls(urls);

    KCalUtils::ICalDrag::populateMimeData(mimeData.get(), cal);

    return mimeData.release();
}

234
QMimeData *CalendarSupport::createMimeData(const Akonadi::Item &item)
235
{
236
    return createMimeData(Akonadi::Item::List() << item);
237
238
239
}

#ifndef QT_NO_DRAGANDDROP
240
QDrag *CalendarSupport::createDrag(const Akonadi::Item &item, QWidget *parent)
241
{
242
    return createDrag(Akonadi::Item::List() << item, parent);
243
}
Laurent Montel's avatar
Laurent Montel committed
244

245
246
247
248
249
250
251
252
253
#endif

static QByteArray findMostCommonType(const Akonadi::Item::List &items)
{
    QByteArray prev;
    if (items.isEmpty()) {
        return "Incidence";
    }

Laurent Montel's avatar
Laurent Montel committed
254
    for (const Akonadi::Item &item : items) {
255
256
257
258
259
260
261
262
263
264
265
266
267
        if (!CalendarSupport::hasIncidence(item)) {
            continue;
        }
        const QByteArray type = CalendarSupport::incidence(item)->typeStr();
        if (!prev.isEmpty() && type != prev) {
            return "Incidence";
        }
        prev = type;
    }
    return prev;
}

#ifndef QT_NO_DRAGANDDROP
268
QDrag *CalendarSupport::createDrag(const Akonadi::Item::List &items, QWidget *parent)
269
270
{
    std::unique_ptr<QDrag> drag(new QDrag(parent));
271
    drag->setMimeData(CalendarSupport::createMimeData(items));
272
273
274

    const QByteArray common = findMostCommonType(items);
    if (common == "Event") {
275
        drag->setPixmap(QIcon::fromTheme(QStringLiteral("view-calendar-day")).pixmap(qApp->style()->pixelMetric(QStyle::PM_ToolBarIconSize)));
276
    } else if (common == "Todo") {
277
        drag->setPixmap(QIcon::fromTheme(QStringLiteral("view-calendar-tasks")).pixmap(qApp->style()->pixelMetric(QStyle::PM_ToolBarIconSize)));
278
279
280
281
    }

    return drag.release();
}
Laurent Montel's avatar
Laurent Montel committed
282

283
284
#endif

285
static bool itemMatches(const Akonadi::Item &item, const KCalendarCore::CalFilter *filter)
286
287
{
    assert(filter);
288
    KCalendarCore::Incidence::Ptr inc = CalendarSupport::incidence(item);
289
290
291
292
293
294
    if (!inc) {
        return false;
    }
    return filter->filterIncidence(inc);
}

Laurent Montel's avatar
Laurent Montel committed
295
Akonadi::Item::List CalendarSupport::applyCalFilter(const Akonadi::Item::List &items_, const KCalendarCore::CalFilter *filter)
296
297
298
{
    Q_ASSERT(filter);
    Akonadi::Item::List items(items_);
299
300
301
    items.erase(std::remove_if(items.begin(), items.end(), [filter](const Akonadi::Item &item) {
        return !itemMatches(item, filter);
    }), items.end());
302
303
304
    return items;
}

Laurent Montel's avatar
Laurent Montel committed
305
bool CalendarSupport::isValidIncidenceItemUrl(const QUrl &url, const QStringList &supportedMimeTypes)
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
{
    if (!url.isValid()) {
        return false;
    }

    if (url.scheme() != QLatin1String("akonadi")) {
        return false;
    }

    return supportedMimeTypes.contains(QUrlQuery(url).queryItemValue(QStringLiteral("type")));
}

bool CalendarSupport::isValidIncidenceItemUrl(const QUrl &url)
{
    return isValidIncidenceItemUrl(url,
321
322
323
324
                                   QStringList() << KCalendarCore::Event::eventMimeType()
                                                 << KCalendarCore::Todo::todoMimeType()
                                                 << KCalendarCore::Journal::journalMimeType()
                                                 << KCalendarCore::FreeBusy::freeBusyMimeType());
325
326
327
328
329
}

static bool containsValidIncidenceItemUrl(const QList<QUrl> &urls)
{
    return
330
        std::find_if(urls.begin(), urls.end(), [](const QUrl &url) {
Laurent Montel's avatar
Laurent Montel committed
331
332
        return CalendarSupport::isValidIncidenceItemUrl(url);
    }) != urls.constEnd();
333
334
335
336
}

bool CalendarSupport::canDecode(const QMimeData *md)
{
337
338
    if (md) {
        return
Laurent Montel's avatar
Laurent Montel committed
339
340
341
            containsValidIncidenceItemUrl(md->urls())
            || KCalUtils::ICalDrag::canDecode(md)
            || KCalUtils::VCalDrag::canDecode(md);
342
343
344
    } else {
        return false;
    }
345
346
347
348
349
}

QList<QUrl> CalendarSupport::incidenceItemUrls(const QMimeData *mimeData)
{
    QList<QUrl> urls;
Laurent Montel's avatar
Laurent Montel committed
350
    const QList<QUrl> urlsList = mimeData->urls();
Laurent Montel's avatar
Laurent Montel committed
351
    for (const QUrl &i : urlsList) {
352
353
354
355
356
357
358
359
360
361
362
        if (isValidIncidenceItemUrl(i)) {
            urls.push_back(i);
        }
    }
    return urls;
}

QList<QUrl> CalendarSupport::todoItemUrls(const QMimeData *mimeData)
{
    QList<QUrl> urls;

Laurent Montel's avatar
Laurent Montel committed
363
364
    const QList<QUrl> urlList = mimeData->urls();
    for (const QUrl &i : urlList) {
365
        if (isValidIncidenceItemUrl(i, QStringList() << KCalendarCore::Todo::todoMimeType())) {
366
367
368
369
370
371
372
373
            urls.push_back(i);
        }
    }
    return urls;
}

bool CalendarSupport::mimeDataHasIncidence(const QMimeData *mimeData)
{
Laurent Montel's avatar
Laurent Montel committed
374
375
    return !incidenceItemUrls(mimeData).isEmpty()
           || !incidences(mimeData).isEmpty();
376
377
}

378
KCalendarCore::Todo::List CalendarSupport::todos(const QMimeData *mimeData)
379
{
380
    KCalendarCore::Todo::List todos;
381
382

#ifndef QT_NO_DRAGANDDROP
383
    KCalendarCore::Calendar::Ptr cal(KCalUtils::DndFactory::createDropCalendar(mimeData));
384
    if (cal) {
385
        const KCalendarCore::Todo::List calTodos = cal->todos();
386
        todos.reserve(calTodos.count());
387
388
        for (const KCalendarCore::Todo::Ptr &i : calTodos) {
            todos.push_back(KCalendarCore::Todo::Ptr(i->clone()));
389
390
391
392
393
394
395
        }
    }
#endif

    return todos;
}

396
KCalendarCore::Incidence::List CalendarSupport::incidences(const QMimeData *mimeData)
397
{
398
    KCalendarCore::Incidence::List incidences;
399
400

#ifndef QT_NO_DRAGANDDROP
401
    KCalendarCore::Calendar::Ptr cal(KCalUtils::DndFactory::createDropCalendar(mimeData));
402
    if (cal) {
403
        const KCalendarCore::Incidence::List calIncidences = cal->incidences();
404
        incidences.reserve(calIncidences.count());
405
406
        for (const KCalendarCore::Incidence::Ptr &i : calIncidences) {
            incidences.push_back(KCalendarCore::Incidence::Ptr(i->clone()));
407
408
409
410
411
412
413
        }
    }
#endif

    return incidences;
}

Laurent Montel's avatar
Laurent Montel committed
414
Akonadi::Collection CalendarSupport::selectCollection(QWidget *parent, int &dialogCode, const QStringList &mimeTypes, const Akonadi::Collection &defCollection)
415
416
{
    QPointer<Akonadi::CollectionDialog> dlg(new Akonadi::CollectionDialog(parent));
417
    dlg->setWindowTitle(i18nc("@title:window", "Select Calendar"));
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
    dlg->setDescription(i18n("Select the calendar where this item will be stored."));
    dlg->changeCollectionDialogOptions(Akonadi::CollectionDialog::KeepTreeExpanded);
    qCDebug(CALENDARSUPPORT_LOG) << "selecting collections with mimeType in " << mimeTypes;

    dlg->setMimeTypeFilter(mimeTypes);
    dlg->setAccessRightsFilter(Akonadi::Collection::CanCreateItem);
    if (defCollection.isValid()) {
        dlg->setDefaultCollection(defCollection);
    }
    Akonadi::Collection collection;

    // FIXME: don't use exec.
    dialogCode = dlg->exec();
    if (dlg && dialogCode == QDialog::Accepted) {
        collection = dlg->selectedCollection();

        if (!collection.isValid()) {
            qCWarning(CALENDARSUPPORT_LOG) << "An invalid collection was selected!";
        }
    }
    delete dlg;
    return collection;
}

Akonadi::Item CalendarSupport::itemFromIndex(const QModelIndex &idx)
{
    Akonadi::Item item = idx.data(Akonadi::EntityTreeModel::ItemRole).value<Akonadi::Item>();
    item.setParentCollection(
        idx.data(Akonadi::EntityTreeModel::ParentCollectionRole).value<Akonadi::Collection>());
    return item;
}

Laurent Montel's avatar
Laurent Montel committed
450
Akonadi::Collection::List CalendarSupport::collectionsFromModel(const QAbstractItemModel *model, const QModelIndex &parentIndex, int start, int end)
451
452
453
454
455
456
457
458
459
{
    const int endRow = end >= 0 ? end : model->rowCount(parentIndex) - 1;
    Akonadi::Collection::List collections;
    int row = start;
    QModelIndex i = model->index(row, 0, parentIndex);
    while (row <= endRow) {
        const Akonadi::Collection collection = collectionFromIndex(i);
        if (collection.isValid()) {
            collections << collection;
Laurent Montel's avatar
Laurent Montel committed
460
            QModelIndex childIndex = model->index(0, 0, i);
461
462
463
464
465
466
467
468
469
470
            if (childIndex.isValid()) {
                collections << collectionsFromModel(model, i);
            }
        }
        ++row;
        i = i.sibling(row, 0);
    }
    return collections;
}

Laurent Montel's avatar
Laurent Montel committed
471
Akonadi::Item::List CalendarSupport::itemsFromModel(const QAbstractItemModel *model, const QModelIndex &parentIndex, int start, int end)
472
473
474
475
476
477
478
479
480
481
{
    const int endRow = end >= 0 ? end : model->rowCount(parentIndex) - 1;
    Akonadi::Item::List items;
    int row = start;
    QModelIndex i = model->index(row, 0, parentIndex);
    while (row <= endRow) {
        const Akonadi::Item item = itemFromIndex(i);
        if (CalendarSupport::hasIncidence(item)) {
            items << item;
        } else {
Laurent Montel's avatar
Laurent Montel committed
482
            QModelIndex childIndex = model->index(0, 0, i);
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
            if (childIndex.isValid()) {
                items << itemsFromModel(model, i);
            }
        }
        ++row;
        i = i.sibling(row, 0);
    }
    return items;
}

Akonadi::Collection CalendarSupport::collectionFromIndex(const QModelIndex &index)
{
    return index.data(Akonadi::EntityTreeModel::CollectionRole).value<Akonadi::Collection>();
}

Akonadi::Collection::Id CalendarSupport::collectionIdFromIndex(const QModelIndex &index)
{
    return index.data(Akonadi::EntityTreeModel::CollectionIdRole).value<Akonadi::Collection::Id>();
}

Akonadi::Collection::List CalendarSupport::collectionsFromIndexes(const QModelIndexList &indexes)
{
    Akonadi::Collection::List l;
    l.reserve(indexes.count());
Laurent Montel's avatar
Laurent Montel committed
507
    for (const QModelIndex &idx : indexes) {
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
        l.push_back(collectionFromIndex(idx));
    }
    return l;
}

QString CalendarSupport::displayName(Akonadi::ETMCalendar *calendar, const Akonadi::Collection &c)
{
    Akonadi::Collection fullCollection;
    if (calendar && calendar->collection(c.id()).isValid()) {
        fullCollection = calendar->collection(c.id());
    } else {
        fullCollection = c;
    }

    QString cName = fullCollection.name();
    const QString resourceName = fullCollection.resource();

    // Kolab Groupware
526
    if (resourceName.contains(QLatin1String("kolab"))) {
527
528
529
530
531
532
533
534
        QString typeStr = cName; // contents type: "Calendar", "Tasks", etc
        QString ownerStr;        // folder owner: "fred", "ethel", etc
        QString nameStr;         // folder name: "Public", "Test", etc
        if (calendar) {
            Akonadi::Collection p = c.parentCollection();
            while (p != Akonadi::Collection::root()) {
                Akonadi::Collection tCol = calendar->collection(p.id());
                const QString tName = tCol.name();
Laurent Montel's avatar
Laurent Montel committed
535
                if (tName.startsWith(QLatin1String("shared.cal"), Qt::CaseInsensitive)) {
536
537
                    ownerStr = QStringLiteral("Shared");
                    nameStr = cName;
Laurent Montel's avatar
Laurent Montel committed
538
                    typeStr = i18n("Calendar");
539
                    break;
Laurent Montel's avatar
Laurent Montel committed
540
541
                } else if (tName.startsWith(QLatin1String("shared.tasks"), Qt::CaseInsensitive)
                           || tName.startsWith(QLatin1String("shared.todo"), Qt::CaseInsensitive)) {
542
543
                    ownerStr = QStringLiteral("Shared");
                    nameStr = cName;
Laurent Montel's avatar
Laurent Montel committed
544
                    typeStr = i18n("Tasks");
545
                    break;
546
                } else if (tName.startsWith(QLatin1String("shared.journal"), Qt::CaseInsensitive)) {
547
548
                    ownerStr = QStringLiteral("Shared");
                    nameStr = cName;
Laurent Montel's avatar
Laurent Montel committed
549
                    typeStr = i18n("Journal");
550
                    break;
Laurent Montel's avatar
Laurent Montel committed
551
                } else if (tName.startsWith(QLatin1String("shared.notes"), Qt::CaseInsensitive)) {
552
553
                    ownerStr = QStringLiteral("Shared");
                    nameStr = cName;
Laurent Montel's avatar
Laurent Montel committed
554
                    typeStr = i18n("Notes");
555
                    break;
Laurent Montel's avatar
Laurent Montel committed
556
557
558
559
                } else if (tName != i18n("Calendar")
                           && tName != i18n("Tasks")
                           && tName != i18n("Journal")
                           && tName != i18n("Notes")) {
560
561
562
563
564
565
566
567
568
569
570
                    ownerStr = tName;
                    break;
                } else {
                    nameStr = typeStr;
                    typeStr = tName;
                }
                p = p.parentCollection();
            }
        }

        if (!ownerStr.isEmpty()) {
Laurent Montel's avatar
Laurent Montel committed
571
            if (!ownerStr.compare(QLatin1String("INBOX"), Qt::CaseInsensitive)) {
572
573
                return i18nc("%1 is folder contents",
                             "My Kolab %1", typeStr);
Laurent Montel's avatar
Laurent Montel committed
574
575
576
            } else if (!ownerStr.compare(QLatin1String("SHARED"), Qt::CaseInsensitive)
                       || !ownerStr.compare(QLatin1String("CALENDAR"), Qt::CaseInsensitive)
                       || !ownerStr.compare(QLatin1String("RESOURCES"), Qt::CaseInsensitive)) {
577
578
579
580
581
582
583
                return i18nc("%1 is folder name, %2 is folder contents",
                             "Shared Kolab %1 %2", nameStr, typeStr);
            } else {
                if (nameStr.isEmpty()) {
                    return i18nc("%1 is folder owner name, %2 is folder contents",
                                 "%1's Kolab %2", ownerStr, typeStr);
                } else {
Laurent Montel's avatar
Laurent Montel committed
584
585
586
                    return i18nc(
                        "%1 is folder owner name, %2 is folder name, %3 is folder contents",
                        "%1's %2 Kolab %3", ownerStr, nameStr, typeStr);
587
588
589
590
591
592
593
594
595
                }
            }
        } else {
            return i18nc("%1 is folder contents",
                         "Kolab %1", typeStr);
        }
    } //end kolab section

    // Dav Groupware
596
    if (resourceName.contains(QLatin1String("davgroupware"))) {
Laurent Montel's avatar
Laurent Montel committed
597
598
599
600
        const QString resourceDisplayName
            = Akonadi::AgentManager::self()->instance(resourceName).name();
        return i18nc("%1 is the folder name", "%1 in %2",
                     fullCollection.displayName(), resourceDisplayName);
601
602
603
    } //end caldav section

    // Google
604
    if (resourceName.contains(QLatin1String("google"))) {
605
606
607
608
609
610
611
612
613
        QString ownerStr;        // folder owner: "user@gmail.com"
        if (calendar) {
            Akonadi::Collection p = c.parentCollection();
            ownerStr = calendar->collection(p.id()).displayName();
        }

        const QString nameStr = c.displayName(); // folder name: can be anything

        QString typeStr;
Laurent Montel's avatar
Laurent Montel committed
614
        const QString mimeStr = c.contentMimeTypes().join(QLatin1Char(','));
615
        if (mimeStr.contains(QLatin1String(".event"))) {
616
            typeStr = i18n("Calendar");
617
        } else if (mimeStr.contains(QLatin1String(".todo"))) {
618
            typeStr = i18n("Tasks");
619
        } else if (mimeStr.contains(QLatin1String(".journal"))) {
620
            typeStr = i18n("Journal");
621
        } else if (mimeStr.contains(QLatin1String(".note"))) {
622
623
624
625
626
627
628
            typeStr = i18n("Notes");
        } else {
            typeStr = mimeStr;
        }

        if (!ownerStr.isEmpty()) {
            const int atChar = ownerStr.lastIndexOf(QLatin1Char('@'));
Laurent Montel's avatar
Laurent Montel committed
629
            if (atChar >= 0) {
Laurent Montel's avatar
Laurent Montel committed
630
                ownerStr.truncate(atChar);
Laurent Montel's avatar
Laurent Montel committed
631
            }
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
            if (nameStr.isEmpty()) {
                return i18nc("%1 is folder owner name, %2 is folder contents",
                             "%1's Google %2", ownerStr, typeStr);
            } else {
                return i18nc("%1 is folder owner name, %2 is folder name",
                             "%1's %2", ownerStr, nameStr);
            }
        } else {
            return i18nc("%1 is folder contents",
                         "Google %1", typeStr);
        }
    } //end google section

    // Not groupware so the collection is "mine"
    const QString dName = fullCollection.displayName();

    if (!dName.isEmpty()) {
Laurent Montel's avatar
Laurent Montel committed
649
        return fullCollection.name().startsWith(QLatin1String("akonadi_")) ? i18n("My %1",
Laurent Montel's avatar
Laurent Montel committed
650
                                                                                  dName) : dName;
651
652
653
654
655
656
657
    } else if (!fullCollection.name().isEmpty()) {
        return fullCollection.name();
    } else {
        return i18nc("unknown resource", "Unknown");
    }
}

658
659
660
661
QString CalendarSupport::toolTipString(const Akonadi::Collection &coll, bool richText)
{
    Q_UNUSED(richText);

Laurent Montel's avatar
Laurent Montel committed
662
    QString str = QStringLiteral("<qt>");
663
664
665
666
667
668
669
670
671
672

    // Display Name
    QString displayName;
    if (coll.hasAttribute<Akonadi::EntityDisplayAttribute>()) {
        displayName = coll.attribute<Akonadi::EntityDisplayAttribute>()->displayName();
    }

    if (displayName.isEmpty()) {
        displayName = coll.name();
    }
673
674
675
    if (coll.id() == CalendarSupport::KCalPrefs::instance()->defaultCalendarId()) {
        displayName = i18nc("this is the default calendar", "%1 (Default Calendar)", displayName);
    }
676
677
678
679
680
681
    str += QLatin1String("<b>") + displayName + QLatin1String("</b>");
    str += QLatin1String("<hr>");

    // Calendar Type
    QString calendarType;
    if (!coll.isVirtual()) {
Laurent Montel's avatar
Laurent Montel committed
682
683
        const Akonadi::AgentInstance instance
            = Akonadi::AgentManager::self()->instance(coll.resource());
684
685
        calendarType = instance.type().name();
    } else {
686
        calendarType = i18nc("a virtual folder type", "Virtual");
687
    }
688
    str += QLatin1String("<i>") + i18n("Folder type:") + QLatin1String("</i>");
689
690
    str += QLatin1String("&nbsp;") + calendarType;

691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
    // Content Type
    QStringList mimeTypes = coll.contentMimeTypes();
    mimeTypes.removeAll(QLatin1String("inode/directory"));
    QString mimeTypeStr;
    if (!mimeTypes.isEmpty()) {
        mimeTypeStr = QLocale().createSeparatedList(
                          mimeTypes.
                          replaceInStrings(
                              QLatin1String("application/x-vnd.akonadi.calendar."), QString()));
    } else {
        mimeTypeStr = i18nc("collection has no mimetypes to show the user", "none");
    }
    str += QLatin1String("<br>");
    str += QLatin1String("<i>") + i18n("Content type:") + QLatin1String("</i>");
    str += QLatin1String("&nbsp;") + mimeTypeStr;
    str += QLatin1String("</br>");

708
709
710
711
712
713
714
715
716
717
718
719
720
721
    // Read only?
    bool isReadOnly = !(coll.rights() & Akonadi::Collection::CanChangeItem);
    str += QLatin1String("<br>");
    str += QLatin1String("<i>") + i18n("Rights:") + QLatin1String("</i>");
    str += QLatin1String("&nbsp;");
    if (isReadOnly) {
        str += i18nc("the calendar is read-only", "read-only");
    } else {
        str += i18nc("the calendar is read and write", "read+write");
    }
    str += QLatin1String("</br>");

    str += QLatin1String("</qt>");
    return str;
Laurent Montel's avatar
Laurent Montel committed
722
}
723

724
QString CalendarSupport::subMimeTypeForIncidence(const KCalendarCore::Incidence::Ptr &incidence)
725
726
727
728
{
    return incidence->mimeType();
}

Laurent Montel's avatar
Laurent Montel committed
729
QList<QDate> CalendarSupport::workDays(const QDate &startDate, const QDate &endDate)
730
731
732
733
734
735
736
737
738
739
740
741
742
743
{
    QList<QDate> result;

    const int mask(~(KCalPrefs::instance()->mWorkWeekMask));
    const int numDays = startDate.daysTo(endDate) + 1;

    for (int i = 0; i < numDays; ++i) {
        const QDate date = startDate.addDays(i);
        if (!(mask & (1 << (date.dayOfWeek() - 1)))) {
            result.append(date);
        }
    }

    if (KCalPrefs::instance()->mExcludeHolidays) {
744
745
        const QStringList holidays = KCalPrefs::instance()->mHolidays;
        for (const QString &regionStr : holidays) {
746
747
748
749
750
751
752
753
754
755
            KHolidays::HolidayRegion region(regionStr);
            if (region.isValid()) {
                const KHolidays::Holiday::List list = region.holidays(startDate, endDate);
                const int listCount(list.count());
                for (int i = 0; i < listCount; ++i) {
                    const Holiday &h = list.at(i);
                    if (h.dayType() == Holiday::NonWorkday) {
                        result.removeAll(h.observedStartDate());
                    }
                }
756
757
758
759
760
761
762
763
764
765
766
            }
        }
    }

    return result;
}

QStringList CalendarSupport::holiday(const QDate &date)
{
    QStringList hdays;

767
    bool showCountryCode = (KCalPrefs::instance()->mHolidays.count() > 1);
768
769
    const QStringList holidays = KCalPrefs::instance()->mHolidays;
    for (const QString &regionStr : holidays) {
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
        KHolidays::HolidayRegion region(regionStr);
        if (region.isValid()) {
            const Holiday::List list = region.holidays(date);
            const int listCount = list.count();
            for (int i = 0; i < listCount; ++i) {
                // don't add duplicates.
                // TODO: won't find duplicates in different languages however.
                const QString name = list.at(i).name();
                if (showCountryCode) {
                    // If more than one holiday region, append the country code to the holiday
                    // display name to help the user identify which region it belongs to.
                    const QRegularExpression holidaySE(
                        i18nc("search pattern for holidayname", "^%1", name));
                    if (hdays.filter(holidaySE).isEmpty()) {
                        const QString pholiday = i18n("%1 (%2)", name, region.countryCode());
                        hdays.append(pholiday);
                    } else {
                        // More than 1 region has the same holiday => remove the country code
                        // i.e don't show "Holiday (US)" and "Holiday(FR)"; just show "Holiday".
                        const QRegularExpression holidayRE(
                            i18nc("replace pattern for holidayname (countrycode)", "^%1 \\(.*\\)", name));
                        hdays.replaceInStrings(holidayRE, name);
                        hdays.removeDuplicates();
                    }
                } else {
                    if (!hdays.contains(name)) {
                        hdays.append(name);
                    }
                }
            }
        }
801
    }
802

803
804
805
    return hdays;
}

806
QStringList CalendarSupport::categories(const KCalendarCore::Incidence::List &incidences)
807
808
809
810
{
    QStringList cats, thisCats;
    // @TODO: For now just iterate over all incidences. In the future,
    // the list of categories should be built when reading the file.
811
    for (const KCalendarCore::Incidence::Ptr &incidence : incidences) {
812
        thisCats = incidence->categories();
Laurent Montel's avatar
Laurent Montel committed
813
        const QStringList::ConstIterator send(thisCats.constEnd());
814
        for (QStringList::ConstIterator si = thisCats.constBegin();
Laurent Montel's avatar
Laurent Montel committed
815
             si != send; ++si) {
816
817
818
819
820
821
822
823
            if (!cats.contains(*si)) {
                cats.append(*si);
            }
        }
    }
    return cats;
}

Laurent Montel's avatar
Laurent Montel committed
824
bool CalendarSupport::mergeCalendar(const QString &srcFilename, const KCalendarCore::Calendar::Ptr &destCalendar)
825
826
827
828
829
830
831
832
833
834
835
836
{
    if (srcFilename.isEmpty()) {
        qCCritical(CALENDARSUPPORT_LOG) << "Empty filename.";
        return false;
    }

    if (!QFile::exists(srcFilename)) {
        qCCritical(CALENDARSUPPORT_LOG) << "File'" << srcFilename << "' doesn't exist.";
    }

    // merge in a file
    destCalendar->startBatchAdding();
837
    KCalendarCore::FileStorage storage(destCalendar);
838
    storage.setFileName(srcFilename);
Laurent Montel's avatar
Laurent Montel committed
839
    bool loadedSuccesfully = storage.load();
840
841
842
843
    destCalendar->endBatchAdding();

    return loadedSuccesfully;
}
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867

void CalendarSupport::createAlarmReminder(const Alarm::Ptr &alarm, KCalendarCore::IncidenceBase::IncidenceType type)
{
    int duration; // in secs
    switch (CalendarSupport::KCalPrefs::instance()->mReminderTimeUnits) {
    default:
    case 0: // mins
        duration = CalendarSupport::KCalPrefs::instance()->mReminderTime * 60;
        break;
    case 1: // hours
        duration = CalendarSupport::KCalPrefs::instance()->mReminderTime * 60 * 60;
        break;
    case 2: // days
        duration = CalendarSupport::KCalPrefs::instance()->mReminderTime * 60 * 60 * 24;
        break;
    }
    alarm->setType(KCalendarCore::Alarm::Display);
    alarm->setEnabled(true);
    if (type == KCalendarCore::Incidence::TypeEvent) {
        alarm->setStartOffset(KCalendarCore::Duration(-duration));
    } else {
        alarm->setEndOffset(KCalendarCore::Duration(-duration));
    }
}