incidenceattachment.cpp 21.6 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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
/*
  Copyright (c) 2010 Bertjan Broeksema <broeksema@kde.org>
  Copyright (c) 2010 Klarälvdalens Datakonsult AB, a KDAB Group company <info@kdab.com>

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

  This library 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 Library General Public
  License for more details.

  You should have received a copy of the GNU Library General Public License
  along with this library; see the file COPYING.LIB.  If not, write to the
  Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  02110-1301, USA.
*/

#include "incidenceattachment.h"
#include "attachmenteditdialog.h"
#include "attachmenticonview.h"
#include "ui_dialogdesktop.h"

#include <KdepimDBusInterfaces/UriHandler>

#include <KContacts/VCardDrag>

#include <KMime/Message>

#include <QAction>
#include <KActionCollection>
#include <QFileDialog>
#include <QMenu>
#include <KMessageBox>
#include <KProtocolManager>
#include <KRun>
#include <KIO/Job>
#include <KIO/StoredTransferJob>
#include <KJobWidgets>
#include <KLocalizedString>
#include <QIcon>
#include <QUrl>

#include <QClipboard>
#include <QMimeData>
#include <QMimeDatabase>
#include <QMimeType>

using namespace IncidenceEditorNG;

IncidenceAttachment::IncidenceAttachment(Ui::EventOrTodoDesktop *ui)
Laurent Montel's avatar
Laurent Montel committed
54 55 56
    : IncidenceEditor(nullptr)
    , mUi(ui)
    , mPopupMenu(new QMenu)
57 58 59 60 61 62
{
    setupActions();
    setupAttachmentIconView();
    setObjectName(QStringLiteral("IncidenceAttachment"));

    connect(mUi->mAddButton, &QPushButton::clicked, this, &IncidenceAttachment::addAttachment);
Laurent Montel's avatar
Laurent Montel committed
63 64
    connect(mUi->mRemoveButton, &QPushButton::clicked, this,
            &IncidenceAttachment::removeSelectedAttachments);
65 66 67 68 69 70 71
}

IncidenceAttachment::~IncidenceAttachment()
{
    delete mPopupMenu;
}

72
void IncidenceAttachment::load(const KCalendarCore::Incidence::Ptr &incidence)
73 74 75 76
{
    mLoadedIncidence = incidence;
    mAttachmentView->clear();

77 78
    KCalendarCore::Attachment::List attachments = incidence->attachments();
    for (KCalendarCore::Attachment::List::ConstIterator it = attachments.constBegin(),
Laurent Montel's avatar
Laurent Montel committed
79 80
         end = attachments.constEnd();
         it != end; ++it) {
81 82 83 84 85 86
        new AttachmentIconItem((*it), mAttachmentView);
    }

    mWasDirty = false;
}

87
void IncidenceAttachment::save(const KCalendarCore::Incidence::Ptr &incidence)
88 89 90 91 92 93 94
{
    incidence->clearAttachments();

    for (int itemIndex = 0; itemIndex < mAttachmentView->count(); ++itemIndex) {
        QListWidgetItem *item = mAttachmentView->item(itemIndex);
        AttachmentIconItem *attitem = dynamic_cast<AttachmentIconItem *>(item);
        Q_ASSERT(item);
95
        incidence->addAttachment(attitem->attachment());
96 97 98 99 100 101 102 103 104 105
    }
}

bool IncidenceAttachment::isDirty() const
{
    if (mLoadedIncidence) {
        if (mAttachmentView->count() != mLoadedIncidence->attachments().count()) {
            return true;
        }

106
        KCalendarCore::Attachment::List origAttachments = mLoadedIncidence->attachments();
107 108 109 110
        for (int itemIndex = 0; itemIndex < mAttachmentView->count(); ++itemIndex) {
            QListWidgetItem *item = mAttachmentView->item(itemIndex);
            Q_ASSERT(dynamic_cast<AttachmentIconItem *>(item));

111
            const KCalendarCore::Attachment listAttachment = static_cast<AttachmentIconItem *>(item)->attachment();
112 113

            for (int i = 0; i < origAttachments.count(); ++i) {
114
                const KCalendarCore::Attachment attachment = origAttachments.at(i);
115

116
                if (attachment == listAttachment) {
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
                    origAttachments.remove(i);
                    break;
                }
            }
        }
        // All attachments are removed from the list, meaning, the items in mAttachmentView
        // are equal to the attachments set on mLoadedIncidence.
        return !origAttachments.isEmpty();
    } else {
        // No incidence loaded, so if the user added attachments we're dirty.
        return mAttachmentView->count() != 0;
    }
}

int IncidenceAttachment::attachmentCount() const
{
    return mAttachmentView->count();
}

/// Private slots

void IncidenceAttachment::addAttachment()
{
Denis Kurz's avatar
Denis Kurz committed
140
    QPointer<QObject> that(this);
141
    AttachmentIconItem *item = new AttachmentIconItem(KCalendarCore::Attachment(), mAttachmentView);
142

Denis Kurz's avatar
Denis Kurz committed
143 144 145 146 147 148 149 150
    QPointer<AttachmentEditDialog> dialog(new AttachmentEditDialog(item, mAttachmentView));
    dialog->setWindowTitle(i18nc("@title", "Add Attachment"));
    auto dialogResult = dialog->exec();
    if (!that) {
        return;
    }

    if (dialogResult == QDialog::Rejected) {
151 152 153 154
        delete item;
    } else {
        Q_EMIT attachmentCountChanged(mAttachmentView->count());
    }
Denis Kurz's avatar
Denis Kurz committed
155
    delete dialog;
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

    checkDirtyStatus();
}

void IncidenceAttachment::copyToClipboard()
{
#ifndef QT_NO_CLIPBOARD
    QApplication::clipboard()->setMimeData(mAttachmentView->mimeData(), QClipboard::Clipboard);
#endif
}

void IncidenceAttachment::openURL(const QUrl &url)
{
    QString uri = url.url();
    UriHandler::process(uri);
}

void IncidenceAttachment::pasteFromClipboard()
{
#ifndef QT_NO_CLIPBOARD
    handlePasteOrDrop(QApplication::clipboard()->mimeData());
#endif
}

void IncidenceAttachment::removeSelectedAttachments()
{
    QList<QListWidgetItem *> selected;
    QStringList labels;

    for (int itemIndex = 0; itemIndex < mAttachmentView->count(); ++itemIndex) {
        QListWidgetItem *it = mAttachmentView->item(itemIndex);
        if (it->isSelected()) {
            AttachmentIconItem *attitem = static_cast<AttachmentIconItem *>(it);
            if (attitem) {
190
                const KCalendarCore::Attachment att = attitem->attachment();
191
                labels << att.label();
192 193 194 195 196 197 198 199 200
                selected << it;
            }
        }
    }

    if (selected.isEmpty()) {
        return;
    }

201
    QString labelsStr = labels.join(QLatin1String("<nl/>"));
202 203

    if (KMessageBox::questionYesNo(
Laurent Montel's avatar
Laurent Montel committed
204 205 206 207 208 209
            nullptr,
            xi18nc("@info",
                   "Do you really want to remove these attachments?<nl/>%1", labelsStr),
            i18nc("@title:window", "Remove Attachments?"),
            KStandardGuiItem::yes(), KStandardGuiItem::no(),
            QStringLiteral("calendarRemoveAttachments")) != KMessageBox::Yes) {
210 211 212 213
        return;
    }

    for (QList<QListWidgetItem *>::iterator it(selected.begin()), end(selected.end());
Laurent Montel's avatar
Laurent Montel committed
214
         it != end; ++it) {
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
        int row = mAttachmentView->row(*it);
        QListWidgetItem *next = mAttachmentView->item(++row);
        QListWidgetItem *prev = mAttachmentView->item(--row);
        if (next) {
            next->setSelected(true);
        } else if (prev) {
            prev->setSelected(true);
        }
        delete *it;
    }

    mAttachmentView->update();
    Q_EMIT attachmentCountChanged(mAttachmentView->count());
    checkDirtyStatus();
}

void IncidenceAttachment::saveAttachment(QListWidgetItem *item)
{
    Q_ASSERT(item);
    Q_ASSERT(dynamic_cast<AttachmentIconItem *>(item));

    AttachmentIconItem *attitem = static_cast<AttachmentIconItem *>(item);
237
    if (attitem->attachment().isEmpty()) {
238 239 240
        return;
    }

241
    KCalendarCore::Attachment att = attitem->attachment();
242 243

    // get the saveas file name
244
    const QString saveAsFile = QFileDialog::getSaveFileName(nullptr, i18nc("@title", "Save Attachment"),
245
                                                            att.label());
Laurent Montel's avatar
Laurent Montel committed
246

247
    if (saveAsFile.isEmpty()) {
248 249 250 251
        return;
    }

    QUrl sourceUrl;
252 253
    if (att.isUri()) {
        sourceUrl = QUrl(att.uri());
254
    } else {
255
        sourceUrl = attitem->tempFileForAttachment();
256 257 258 259
    }
    // save the attachment url
    auto job = KIO::file_copy(sourceUrl, QUrl::fromLocalFile(saveAsFile));
    if (!job->exec() && job->error()) {
Laurent Montel's avatar
Laurent Montel committed
260
        KMessageBox::error(nullptr, job->errorString());
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
    }
}

void IncidenceAttachment::saveSelectedAttachments()
{
    for (int itemIndex = 0; itemIndex < mAttachmentView->count(); ++itemIndex) {
        QListWidgetItem *item = mAttachmentView->item(itemIndex);
        if (item->isSelected()) {
            saveAttachment(item);
        }
    }
}

void IncidenceAttachment::showAttachment(QListWidgetItem *item)
{
    Q_ASSERT(item);
    Q_ASSERT(dynamic_cast<AttachmentIconItem *>(item));
    AttachmentIconItem *attitem = static_cast<AttachmentIconItem *>(item);
279
    if (attitem->attachment().isEmpty()) {
280 281 282
        return;
    }

283
    const KCalendarCore::Attachment att = attitem->attachment();
284 285
    if (att.isUri()) {
        openURL(QUrl(att.uri()));
286
    } else {
Laurent Montel's avatar
Laurent Montel committed
287 288 289
        KRun::RunFlags flags;
        flags |= KRun::DeleteTemporaryFiles;
        flags |= KRun::RunExecutables;
290
        KRun::runUrl(attitem->tempFileForAttachment(), att.mimeType(), nullptr, flags);
291 292 293 294 295
    }
}

void IncidenceAttachment::showContextMenu(const QPoint &pos)
{
Laurent Montel's avatar
Laurent Montel committed
296
    const bool enable = mAttachmentView->itemAt(pos) != nullptr;
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343

    int numSelected = 0;
    for (int itemIndex = 0; itemIndex < mAttachmentView->count(); ++itemIndex) {
        QListWidgetItem *item = mAttachmentView->item(itemIndex);
        if (item->isSelected()) {
            numSelected++;
        }
    }

    mOpenAction->setEnabled(enable);
    //TODO: support saving multiple attachments into a directory
    mSaveAsAction->setEnabled(enable && numSelected == 1);
#ifndef QT_NO_CLIPBOARD
    mCopyAction->setEnabled(enable && numSelected == 1);
    mCutAction->setEnabled(enable && numSelected == 1);
#endif
    mDeleteAction->setEnabled(enable);
    mEditAction->setEnabled(enable);
    mPopupMenu->exec(mAttachmentView->mapToGlobal(pos));
}

void IncidenceAttachment::showSelectedAttachments()
{
    for (int itemIndex = 0; itemIndex < mAttachmentView->count(); ++itemIndex) {
        QListWidgetItem *item = mAttachmentView->item(itemIndex);
        if (item->isSelected()) {
            showAttachment(item);
        }
    }
}

void IncidenceAttachment::cutToClipboard()
{
#ifndef QT_NO_CLIPBOARD
    copyToClipboard();
    removeSelectedAttachments();
#endif
}

void IncidenceAttachment::editSelectedAttachments()
{
    for (int itemIndex = 0; itemIndex < mAttachmentView->count(); ++itemIndex) {
        QListWidgetItem *item = mAttachmentView->item(itemIndex);
        if (item->isSelected()) {
            Q_ASSERT(dynamic_cast<AttachmentIconItem *>(item));

            AttachmentIconItem *attitem = static_cast<AttachmentIconItem *>(item);
344
            if (attitem->attachment().isEmpty()) {
345 346 347 348 349 350
                return;
            }

            QPointer<AttachmentEditDialog> dialog(
                new AttachmentEditDialog(attitem, mAttachmentView, false));
            dialog->setModal(false);
Laurent Montel's avatar
Laurent Montel committed
351
            dialog->setAttribute(Qt::WA_DeleteOnClose, true);
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
            dialog->show();
        }
    }
}

void IncidenceAttachment::slotItemRenamed(QListWidgetItem *item)
{
    Q_ASSERT(item);
    Q_ASSERT(dynamic_cast<AttachmentIconItem *>(item));
    static_cast<AttachmentIconItem *>(item)->setLabel(item->text());
    checkDirtyStatus();
}

void IncidenceAttachment::slotSelectionChanged()
{
    bool selected = false;
    for (int itemIndex = 0; itemIndex < mAttachmentView->count(); ++itemIndex) {
        QListWidgetItem *item = mAttachmentView->item(itemIndex);
        if (item->isSelected()) {
            selected = true;
            break;
        }
    }
    mUi->mRemoveButton->setEnabled(selected);
}

/// Private functions

void IncidenceAttachment::handlePasteOrDrop(const QMimeData *mimeData)
{
382 383 384
    if (!mimeData) {
        return;
    }
385 386 387 388 389 390 391 392 393
    QList<QUrl> urls;
    bool probablyWeHaveUris = false;
    QStringList labels;

    if (KContacts::VCardDrag::canDecode(mimeData)) {
        KContacts::Addressee::List addressees;
        KContacts::VCardDrag::fromMimeData(mimeData, addressees);
        urls.reserve(addressees.count());
        labels.reserve(addressees.count());
Laurent Montel's avatar
Laurent Montel committed
394
        const KContacts::Addressee::List::ConstIterator end(addressees.constEnd());
395
        for (KContacts::Addressee::List::ConstIterator it = addressees.constBegin();
Laurent Montel's avatar
Laurent Montel committed
396
             it != end; ++it) {
397
            urls.append(QUrl(QStringLiteral("uid:") + (*it).uid()));
398 399 400 401 402 403 404 405 406 407
            // there is some weirdness about realName(), hence fromUtf8
            labels.append(QString::fromUtf8((*it).realName().toLatin1()));
        }
        probablyWeHaveUris = true;
    } else if (mimeData->hasUrls()) {
        QMap<QString, QString> metadata;

        //QT5
        //urls = QList<QUrl>::fromMimeData( mimeData, &metadata );
        probablyWeHaveUris = true;
Laurent Montel's avatar
Laurent Montel committed
408
        labels
409
#if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
Laurent Montel's avatar
Laurent Montel committed
410
            = metadata[QStringLiteral("labels")].split(QLatin1Char(':'), QString::SkipEmptyParts);
411 412 413
#else
            = metadata[QStringLiteral("labels")].split(QLatin1Char(':'), Qt::SkipEmptyParts);
#endif
Laurent Montel's avatar
Laurent Montel committed
414 415
        const QStringList::Iterator end(labels.end());
        for (QStringList::Iterator it = labels.begin(); it != end; ++it) {
416 417 418
            *it = QUrl::fromPercentEncoding((*it).toLatin1());
        }
    } else if (mimeData->hasText()) {
Laurent Montel's avatar
Laurent Montel committed
419
        const QString text = mimeData->text();
420
#if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
Laurent Montel's avatar
Laurent Montel committed
421
        QStringList lst = text.split(QLatin1Char('\n'), QString::SkipEmptyParts);
422 423 424
#else
        QStringList lst = text.split(QLatin1Char('\n'), Qt::SkipEmptyParts);
#endif
425
        urls.reserve(lst.count());
Laurent Montel's avatar
Laurent Montel committed
426 427
        QStringList::ConstIterator end(lst.constEnd());
        for (QStringList::ConstIterator it = lst.constBegin(); it != end; ++it) {
428
            urls.append(QUrl(*it));
429 430 431 432
        }
        probablyWeHaveUris = true;
    }
    QMenu menu;
Laurent Montel's avatar
Laurent Montel committed
433
    QAction *linkAction = nullptr, *cancelAction = nullptr;
434
    if (probablyWeHaveUris) {
Laurent Montel's avatar
Laurent Montel committed
435 436 437
        linkAction
            = menu.addAction(QIcon::fromTheme(QStringLiteral("insert-link")),
                             i18nc("@action:inmenu", "&Link here"));
438 439
        // we need to check if we can reasonably expect to copy the objects
        bool weCanCopy = true;
Laurent Montel's avatar
Laurent Montel committed
440 441
        QList<QUrl>::ConstIterator end(urls.constEnd());
        for (QList<QUrl>::ConstIterator it = urls.constBegin(); it != end; ++it) {
442 443 444 445 446
            if (!(weCanCopy = KProtocolManager::supportsReading(*it))) {
                break; // either we can copy them all, or no copying at all
            }
        }
        if (weCanCopy) {
Laurent Montel's avatar
Laurent Montel committed
447 448
            menu.addAction(QIcon::fromTheme(QStringLiteral("edit-copy")),
                           i18nc("@action:inmenu", "&Copy here"));
449 450
        }
    } else {
Laurent Montel's avatar
Laurent Montel committed
451 452
        menu.addAction(QIcon::fromTheme(QStringLiteral("edit-copy")),
                       i18nc("@action:inmenu", "&Copy here"));
453 454 455
    }

    menu.addSeparator();
Laurent Montel's avatar
Laurent Montel committed
456 457 458
    cancelAction
        = menu.addAction(QIcon::fromTheme(QStringLiteral("process-stop")),
                         i18nc("@action:inmenu", "C&ancel"));
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476

    QByteArray data;
    QString mimeType;
    QString label;

    if (!mimeData->formats().isEmpty() && !probablyWeHaveUris) {
        mimeType = mimeData->formats().first();
        data = mimeData->data(mimeType);
        QMimeDatabase db;
        QMimeType mime = db.mimeTypeForName(mimeType);
        if (mime.isValid()) {
            label = mime.comment();
        }
    }

    QAction *ret = menu.exec(QCursor::pos());
    if (linkAction == ret) {
        QStringList::ConstIterator jt = labels.constBegin();
Laurent Montel's avatar
Laurent Montel committed
477
        const QList<QUrl>::ConstIterator jtEnd = urls.constEnd();
478
        for (QList<QUrl>::ConstIterator it = urls.constBegin();
Laurent Montel's avatar
Laurent Montel committed
479
             it != jtEnd; ++it) {
Laurent Montel's avatar
Laurent Montel committed
480 481
            addUriAttachment((*it).url(), QString(), (jt == labels.constEnd()
                                                      ? QString() : *(jt++)), true);
482 483 484
        }
    } else if (cancelAction != ret) {
        if (probablyWeHaveUris) {
Laurent Montel's avatar
Laurent Montel committed
485
            QList<QUrl>::ConstIterator end = urls.constEnd();
486
            for (QList<QUrl>::ConstIterator it = urls.constBegin();
Laurent Montel's avatar
Laurent Montel committed
487
                 it != end; ++it) {
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
                KIO::Job *job = KIO::storedGet(*it);
                //TODO verify if slot exist !
                connect(job, &KIO::Job::result, this, &IncidenceAttachment::downloadComplete);
            }
        } else { // we take anything
            addDataAttachment(data, mimeType, label);
        }
    }
}

void IncidenceAttachment::downloadComplete(KJob *)
{
    //TODO
}

void IncidenceAttachment::setupActions()
{
    KActionCollection *ac = new KActionCollection(this);
//  ac->addAssociatedWidget( this );

Laurent Montel's avatar
Laurent Montel committed
508 509
    mOpenAction = new QAction(QIcon::fromTheme(QStringLiteral("document-open")), i18nc("@action:inmenu open the attachment in a viewer",
                                                                                       "&Open"), this);
510 511 512 513
    connect(mOpenAction, &QAction::triggered, this, &IncidenceAttachment::showSelectedAttachments);
    ac->addAction(QStringLiteral("view"), mOpenAction);
    mPopupMenu->addAction(mOpenAction);

Laurent Montel's avatar
Laurent Montel committed
514
    mSaveAsAction = new QAction(QIcon::fromTheme(QStringLiteral("document-save-as")), i18nc("@action:inmenu save the attachment to a file",
Laurent Montel's avatar
Laurent Montel committed
515
                                                                                            "Save As..."), this);
Laurent Montel's avatar
Laurent Montel committed
516 517
    connect(mSaveAsAction, &QAction::triggered, this,
            &IncidenceAttachment::saveSelectedAttachments);
518 519 520 521
    mPopupMenu->addAction(mSaveAsAction);
    mPopupMenu->addSeparator();

#ifndef QT_NO_CLIPBOARD
Laurent Montel's avatar
Laurent Montel committed
522
    mCopyAction = KStandardAction::copy(this, &IncidenceAttachment::copyToClipboard, ac);
523 524
    mPopupMenu->addAction(mCopyAction);

Laurent Montel's avatar
Laurent Montel committed
525
    mCutAction = KStandardAction::cut(this, &IncidenceAttachment::cutToClipboard, ac);
526 527
    mPopupMenu->addAction(mCutAction);

Laurent Montel's avatar
Laurent Montel committed
528
    QAction *action = KStandardAction::paste(this, &IncidenceAttachment::pasteFromClipboard, ac);
529 530 531 532
    mPopupMenu->addAction(action);
    mPopupMenu->addSeparator();
#endif

Laurent Montel's avatar
Laurent Montel committed
533
    mDeleteAction = new QAction(QIcon::fromTheme(QStringLiteral("list-remove")), i18nc("@action:inmenu remove the attachment",
Laurent Montel's avatar
Laurent Montel committed
534
                                                                                       "&Remove"), this);
Laurent Montel's avatar
Laurent Montel committed
535 536
    connect(mDeleteAction, &QAction::triggered, this,
            &IncidenceAttachment::removeSelectedAttachments);
537 538 539 540 541
    ac->addAction(QStringLiteral("remove"), mDeleteAction);
    mDeleteAction->setShortcut(Qt::Key_Delete);
    mPopupMenu->addAction(mDeleteAction);
    mPopupMenu->addSeparator();

Laurent Montel's avatar
Laurent Montel committed
542
    mEditAction = new QAction(QIcon::fromTheme(QStringLiteral("document-properties")), i18nc("@action:inmenu show a dialog used to edit the attachment",
Laurent Montel's avatar
Laurent Montel committed
543
                                                                                             "&Properties..."), this);
544 545 546 547 548 549 550 551 552 553 554 555
    connect(mEditAction, &QAction::triggered, this, &IncidenceAttachment::editSelectedAttachments);
    ac->addAction(QStringLiteral("edit"), mEditAction);
    mPopupMenu->addAction(mEditAction);
}

void IncidenceAttachment::setupAttachmentIconView()
{
    mAttachmentView = new AttachmentIconView;
    mAttachmentView->setWhatsThis(i18nc("@info:whatsthis",
                                        "Displays items (files, mail, etc.) that "
                                        "have been associated with this event or to-do."));

Laurent Montel's avatar
Laurent Montel committed
556 557 558 559 560 561 562 563
    connect(mAttachmentView, &AttachmentIconView::itemDoubleClicked, this,
            &IncidenceAttachment::showAttachment);
    connect(mAttachmentView, &AttachmentIconView::itemChanged, this,
            &IncidenceAttachment::slotItemRenamed);
    connect(mAttachmentView, &AttachmentIconView::itemSelectionChanged, this,
            &IncidenceAttachment::slotSelectionChanged);
    connect(mAttachmentView, &AttachmentIconView::customContextMenuRequested, this,
            &IncidenceAttachment::showContextMenu);
564 565

    QGridLayout *layout = new QGridLayout(mUi->mAttachmentViewPlaceHolder);
566
    layout->setContentsMargins(0, 0, 0, 0);
567 568 569
    layout->addWidget(mAttachmentView);
}

570
// void IncidenceAttachmentEditor::addAttachment( KCalendarCore::Attachment *attachment )
571 572 573 574
// {
//   new AttachmentIconItem( attachment, mAttachmentView );
// }

Laurent Montel's avatar
Laurent Montel committed
575
void IncidenceAttachment::addDataAttachment(const QByteArray &data, const QString &mimeType, const QString &label)
576
{
577
    AttachmentIconItem *item = new AttachmentIconItem(KCalendarCore::Attachment(), mAttachmentView);
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599

    QString nlabel = label;
    if (mimeType == QLatin1String("message/rfc822")) {
        // mail message. try to set the label from the mail Subject:
        KMime::Message msg;
        msg.setContent(data);
        msg.parse();
        nlabel = msg.subject()->asUnicodeString();
    }

    item->setData(data);
    item->setLabel(nlabel);
    if (mimeType.isEmpty()) {
        QMimeDatabase db;
        item->setMimeType(db.mimeTypeForData(data).name());
    } else {
        item->setMimeType(mimeType);
    }

    checkDirtyStatus();
}

Laurent Montel's avatar
Laurent Montel committed
600
void IncidenceAttachment::addUriAttachment(const QString &uri, const QString &mimeType, const QString &label, bool inLine)
601 602
{
    if (!inLine) {
Laurent Montel's avatar
Laurent Montel committed
603
        AttachmentIconItem *item
604
            = new AttachmentIconItem(KCalendarCore::Attachment(), mAttachmentView);
605 606 607
        item->setUri(uri);
        item->setLabel(label);
        if (mimeType.isEmpty()) {
608
            if (uri.startsWith(QLatin1String("uid:"))) {
609
                item->setMimeType(QStringLiteral("text/directory"));
610
            } else if (uri.startsWith(QLatin1String("kmail:"))) {
611
                item->setMimeType(QStringLiteral("message/rfc822"));
612
            } else if (uri.startsWith(QLatin1String("urn:x-ical"))) {
613
                item->setMimeType(QStringLiteral("text/calendar"));
614
            } else if (uri.startsWith(QLatin1String("news:"))) {
615 616 617
                item->setMimeType(QStringLiteral("message/news"));
            } else {
                QMimeDatabase db;
618
                item->setMimeType(db.mimeTypeForUrl(QUrl(uri)).name());
619 620 621
            }
        }
    } else {
622
        auto job = KIO::storedGet(QUrl(uri));
Laurent Montel's avatar
Laurent Montel committed
623
        KJobWidgets::setWindow(job, nullptr);
624 625 626 627 628 629
        if (job->exec()) {
            const QByteArray data = job->data();
            addDataAttachment(data, mimeType, label);
        }
    }
}