File indexing completed on 2024-11-24 04:39:31

0001 /*
0002     This file is part of Contact Editor.
0003 
0004     SPDX-FileCopyrightText: 2009 Tobias Koenig <tokoe@kde.org>
0005 
0006     SPDX-License-Identifier: LGPL-2.0-or-later
0007 */
0008 
0009 #include "categorieseditwidget.h"
0010 
0011 #include <Akonadi/Item>
0012 #include <Akonadi/Tag>
0013 #include <Akonadi/TagWidget>
0014 #include <QHBoxLayout>
0015 #include <akonadi/tagcreatejob.h>
0016 using namespace Akonadi;
0017 CategoriesEditWidget::CategoriesEditWidget(QWidget *parent)
0018     : QWidget(parent)
0019     , mTagWidget(new Akonadi::TagWidget(this))
0020 {
0021     auto layout = new QHBoxLayout(this);
0022     layout->setContentsMargins({});
0023     layout->addWidget(mTagWidget);
0024 }
0025 
0026 CategoriesEditWidget::~CategoriesEditWidget() = default;
0027 
0028 void CategoriesEditWidget::setReadOnly(bool readOnly)
0029 {
0030     mTagWidget->setReadOnly(readOnly);
0031 }
0032 
0033 void CategoriesEditWidget::loadContact(const KContacts::Addressee &contact)
0034 {
0035     Akonadi::Tag::List tags;
0036 
0037     const QStringList categories = contact.categories();
0038     tags.reserve(categories.count());
0039     for (const QString &category : categories) {
0040         if (category.startsWith(QLatin1StringView("akonadi:"))) {
0041             tags.append(Akonadi::Tag::fromUrl(QUrl(category)));
0042         } else {
0043             Akonadi::Tag missingTag = Akonadi::Tag(category);
0044             auto createJob = new Akonadi::TagCreateJob(missingTag, this);
0045             createJob->setMergeIfExisting(true);
0046             connect(createJob, &Akonadi::TagCreateJob::result, this, &CategoriesEditWidget::onMissingTagCreated);
0047         }
0048     }
0049 
0050     mTagWidget->setSelection(tags);
0051 }
0052 
0053 void CategoriesEditWidget::onMissingTagCreated(KJob *job)
0054 {
0055     if (job->error()) {
0056         return;
0057     }
0058     auto createJob = static_cast<Akonadi::TagCreateJob *>(job);
0059 
0060     auto selectedTags{mTagWidget->selection()};
0061     selectedTags += createJob->tag();
0062     mTagWidget->setSelection(selectedTags);
0063 }
0064 
0065 void CategoriesEditWidget::storeContact(KContacts::Addressee &contact) const
0066 {
0067     QStringList categories;
0068 
0069     const Akonadi::Tag::List tags = mTagWidget->selection();
0070     categories.reserve(tags.count());
0071     for (const Akonadi::Tag &tag : tags) {
0072         categories.append(tag.name());
0073     }
0074 
0075     contact.setCategories(categories);
0076 }
0077 
0078 #include "moc_categorieseditwidget.cpp"