grantleecontactformatter.cpp 9.45 KB
Newer Older
1 2 3
/*
  This file is part of KAddressBook.

4
  SPDX-FileCopyrightText: 2010 Tobias Koenig <tokoe@kde.org>
5

6
  SPDX-License-Identifier: LGPL-2.0-or-later
7 8 9
*/

#include "grantleecontactformatter.h"
Laurent Montel's avatar
Laurent Montel committed
10
#include <GrantleeTheme/GrantleeTheme>
11
#include "../contactobject/contactgrantleewrapper.h"
12

Laurent Montel's avatar
Laurent Montel committed
13
#include <KContacts/Addressee>
14 15 16 17

#include <GrantleeTheme/GrantleeThemeEngine>
#include <GrantleeTheme/GrantleeKi18nLocalizer>

18
#include <grantlee/context.h>
19
#include <grantlee/metatype.h>
20 21 22 23 24 25 26 27 28 29 30
#include <grantlee/templateloader.h>

#include <AkonadiCore/Item>

#include <KColorScheme>

#include <KStringHandler>
#include <KConfigGroup>
#include <KLocalizedString>

#include <QLocale>
31
#include <QMetaProperty>
32
#include <QRegularExpression>
33
#include <QSet>
34 35 36

using namespace KAddressBookGrantlee;

37 38 39 40 41 42 43 44 45 46
// Grantlee has no Q_GADGET support yet
#define GRANTLEE_MAKE_GADGET(Class) \
    GRANTLEE_BEGIN_LOOKUP(Class) \
    const auto idx = Class::staticMetaObject.indexOfProperty(property.toUtf8().constData()); \
    if (idx < 0) { \
        return {};} \
    const auto mp = Class::staticMetaObject.property(idx); \
    return mp.readOnGadget(&object); \
    GRANTLEE_END_LOOKUP

47
GRANTLEE_MAKE_GADGET(KContacts::Address)
48
GRANTLEE_MAKE_GADGET(KContacts::Email)
49
GRANTLEE_MAKE_GADGET(KContacts::Impp)
50
GRANTLEE_MAKE_GADGET(KContacts::PhoneNumber)
51
GRANTLEE_MAKE_GADGET(KContacts::ResourceLocatorUrl)
52
GRANTLEE_MAKE_GADGET(KAddressBookGrantlee::ContactGrantleeWrapper)
53 54 55 56

GRANTLEE_BEGIN_LOOKUP(QUrl)
if (property == QLatin1String("scheme")) {
    return object.scheme();
57 58
} else if (property == QLatin1String("path")) {
    return object.path();
59 60
}
GRANTLEE_END_LOOKUP
61

62 63 64 65 66 67 68 69 70
class Q_DECL_HIDDEN GrantleeContactFormatter::Private
{
public:
    Private()
    {
        KConfig config(QStringLiteral("akonadi_contactrc"));
        KConfigGroup group(&config, QStringLiteral("View"));
        showQRCode = group.readEntry("QRCodes", true);

71
        mEngine.reset(new GrantleeTheme::Engine);
72 73 74 75 76 77

        mTemplateLoader = QSharedPointer<Grantlee::FileSystemTemplateLoader>(new Grantlee::FileSystemTemplateLoader());
    }

    ~Private()
    {
Laurent Montel's avatar
Laurent Montel committed
78
        mTemplateLoader.clear();
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
    }

    void changeGrantleePath(const QString &path)
    {
        mTemplateLoader->setTemplateDirs(QStringList() << path);
        mEngine->addTemplateLoader(mTemplateLoader);

        mSelfcontainedTemplate = mEngine->loadByName(QStringLiteral("contact.html"));
        if (mSelfcontainedTemplate->error()) {
            mErrorMessage += mSelfcontainedTemplate->errorString() + QStringLiteral("<br>");
        }

        mEmbeddableTemplate = mEngine->loadByName(QStringLiteral("contact_embedded.html"));
        if (mEmbeddableTemplate->error()) {
            mErrorMessage += mEmbeddableTemplate->errorString() + QStringLiteral("<br>");
        }
    }

    QVector<QObject *> mObjects;
98
    std::unique_ptr<GrantleeTheme::Engine> mEngine;
99 100 101 102
    QSharedPointer<Grantlee::FileSystemTemplateLoader> mTemplateLoader;
    Grantlee::Template mSelfcontainedTemplate;
    Grantlee::Template mEmbeddableTemplate;
    QString mErrorMessage;
Laurent Montel's avatar
Laurent Montel committed
103
    bool forceDisableQRCode = false;
Laurent Montel's avatar
Laurent Montel committed
104
    bool showQRCode = true;
105 106 107 108 109
};

GrantleeContactFormatter::GrantleeContactFormatter()
    : d(new Private)
{
110
    Grantlee::registerMetaType<KContacts::Address>();
111
    Grantlee::registerMetaType<KContacts::Email>();
112
    Grantlee::registerMetaType<KContacts::Impp>();
113
    Grantlee::registerMetaType<KContacts::PhoneNumber>();
114
    Grantlee::registerMetaType<KContacts::ResourceLocatorUrl>();
115
    Grantlee::registerMetaType<ContactGrantleeWrapper>();
116
    Grantlee::registerMetaType<QUrl>();
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
}

GrantleeContactFormatter::~GrantleeContactFormatter()
{
    delete d;
}

void GrantleeContactFormatter::setAbsoluteThemePath(const QString &path)
{
    d->changeGrantleePath(path);
}

void GrantleeContactFormatter::setGrantleeTheme(const GrantleeTheme::Theme &theme)
{
    d->changeGrantleePath(theme.absolutePath());
}

void GrantleeContactFormatter::setForceDisableQRCode(bool b)
{
Laurent Montel's avatar
Laurent Montel committed
136
    d->forceDisableQRCode = b;
137 138 139 140 141 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
}

bool GrantleeContactFormatter::forceDisableQRCode() const
{
    return d->forceDisableQRCode;
}

void GrantleeContactFormatter::setShowQRCode(bool b)
{
    d->showQRCode = b;
}

QString GrantleeContactFormatter::toHtml(HtmlForm form) const
{
    if (!d->mErrorMessage.isEmpty()) {
        return d->mErrorMessage;
    }

    KContacts::Addressee rawContact;
    const Akonadi::Item localItem = item();
    if (localItem.isValid() && localItem.hasPayload<KContacts::Addressee>()) {
        rawContact = localItem.payload<KContacts::Addressee>();
    } else {
        rawContact = contact();
    }

    if (rawContact.isEmpty()) {
        return QString();
    }

    // Custom fields
    QVariantList customFields;
    QVariantList customFieldsUrl;
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
    static QSet<QString> blacklistedKeys = {
        QStringLiteral("CRYPTOPROTOPREF"),
        QStringLiteral("OPENPGPFP"),
        QStringLiteral("SMIMEFP"),
        QStringLiteral("CRYPTOSIGNPREF"),
        QStringLiteral("CRYPTOENCRYPTPREF"),
        QStringLiteral("Anniversary"),
        QStringLiteral("BlogFeed"),
        QStringLiteral("Profession"),
        QStringLiteral("Office"),
        QStringLiteral("ManagersName"),
        QStringLiteral("AssistantsName"),
        QStringLiteral("SpousesName"),
        QStringLiteral("IMAddress"),
        QStringLiteral("AddressBook"),
        QStringLiteral("MailPreferedFormatting"),
        QStringLiteral("MailAllowToRemoteContent"),
        QStringLiteral("MAILPREFEREDFORMATTING"),
        QStringLiteral("MAILALLOWTOREMOTECONTENT")
    };

    const auto customs = rawContact.customs();
    for (QString custom : customs) {
        if (custom.startsWith(QLatin1String("KADDRESSBOOK-"))) {
            custom.remove(QStringLiteral("KADDRESSBOOK-X-"));
            custom.remove(QStringLiteral("KADDRESSBOOK-"));
196

197 198 199
            int pos = custom.indexOf(QLatin1Char(':'));
            QString key = custom.left(pos);
            QString value = custom.mid(pos + 1);
200

201 202 203
            if (blacklistedKeys.contains(key)) {
                continue;
            }
204

205 206 207 208 209 210 211 212 213 214 215 216
            bool addUrl = false;
            // check whether it is a custom local field
            for (int i = 0; i < customFieldDescriptions().size(); ++i) {
                const QVariantMap description = customFieldDescriptions().at(i);
                if (description.value(QStringLiteral("key")).toString() == key) {
                    key = description.value(QStringLiteral("title")).toString();
                    const QString descriptionType = description.value(QStringLiteral("type")).toString();
                    if (descriptionType == QLatin1String("boolean")) {
                        if (value == QLatin1String("true")) {
                            value = i18nc("Boolean value", "yes");
                        } else {
                            value = i18nc("Boolean value", "no");
217
                        }
218 219 220 221 222 223 224 225 226 227 228 229
                    } else if (descriptionType == QLatin1String("date")) {
                        const QDate date = QDate::fromString(value, Qt::ISODate);
                        value = QLocale().toString(date, QLocale::ShortFormat);
                    } else if (descriptionType == QLatin1String("time")) {
                        const QTime time = QTime::fromString(value, Qt::ISODate);
                        value = QLocale::system().toString(time, QLocale::ShortFormat);
                    } else if (descriptionType == QLatin1String("datetime")) {
                        const QDateTime dateTime = QDateTime::fromString(value, Qt::ISODate);
                        value = QLocale().toString(dateTime, QLocale::ShortFormat);
                    } else if (descriptionType == QLatin1String("url")) {
                        value = KStringHandler::tagUrls(value.toHtmlEscaped());
                        addUrl = true;
230
                    }
231
                    break;
232 233
                }
            }
234 235 236 237 238 239 240 241 242
            QVariantHash customFieldObject;
            customFieldObject.insert(QStringLiteral("title"), key);
            customFieldObject.insert(QStringLiteral("value"), value);

            if (addUrl) {
                customFieldsUrl.append(customFieldObject);
            } else {
                customFields.append(customFieldObject);
            }
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
        }
    }

    QVariantHash colorsObject;

    colorsObject.insert(
        QStringLiteral("linkColor"),
        KColorScheme(QPalette::Active, KColorScheme::View).foreground().color().name());

    colorsObject.insert(
        QStringLiteral("textColor"),
        KColorScheme(QPalette::Active, KColorScheme::View).foreground().color().name());

    colorsObject.insert(
        QStringLiteral("backgroundColor"),
        KColorScheme(QPalette::Active, KColorScheme::View).background().color().name());

    QVariantHash mapping;
261
    mapping.insert(QStringLiteral("contact"), QVariant::fromValue(ContactGrantleeWrapper(rawContact)));
262
    mapping.insert(QStringLiteral("colors"), colorsObject);
263 264 265
    mapping.insert(QStringLiteral("customFields"), customFields);
    mapping.insert(QStringLiteral("customFieldsUrl"), customFieldsUrl);
    mapping.insert(QStringLiteral("hasqrcode"), !d->forceDisableQRCode && d->showQRCode);
266 267

    Grantlee::Context context(mapping);
268
    context.setLocalizer(d->mEngine->localizer());
269 270 271 272 273 274 275 276 277

    if (form == SelfcontainedForm) {
        return d->mSelfcontainedTemplate->render(&context);
    } else if (form == EmbeddableForm) {
        return d->mEmbeddableTemplate->render(&context);
    } else {
        return QString();
    }
}
278 279 280 281 282

void GrantleeContactFormatter::setApplicationDomain(const QByteArray &domain)
{
    d->mEngine->localizer()->setApplicationDomain(domain);
}