pixbufmanipulator.cpp 13.3 KB
Newer Older
1
/*
Sébastien Blin's avatar
Sébastien Blin committed
2
 *  Copyright (C) 2015-2019 Savoir-faire Linux Inc.
3
 *  Author: Stepan Salenikovich <stepan.salenikovich@savoirfairelinux.com>
4
 *  Author: Sébastien Blin <sebastien.blin@savoirfairelinux.com>
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
 *
 *  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 3 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.
 */

21
#include "pixbufmanipulator.h"
22 23 24 25 26 27 28 29

#include <QtCore/QSize>
#include <QtCore/QMetaType>
#include <person.h>
#include <memory>
#include <call.h>
#include <contactmethod.h>

30 31 32 33 34 35 36 37 38
#include <string>
#include <algorithm>

// lrc
#include <api/contactmodel.h>
#include <api/conversation.h>
#include <api/account.h>
#include <api/contact.h>

39 40 41
namespace Interfaces {

PixbufManipulator::PixbufManipulator()
42
    : conferenceAvatar_{ring_draw_conference_avatar(FALLBACK_AVATAR_SIZE), g_object_unref}
43 44 45
{
}

46 47 48 49 50
std::shared_ptr<GdkPixbuf>
PixbufManipulator::temporaryItemAvatar() const
{
    GError *error = nullptr;
    std::shared_ptr<GdkPixbuf> result(
51
        gdk_pixbuf_new_from_resource("/net/jami/JamiGnome/temporary-item", &error),
52 53 54 55 56 57 58 59 60 61 62
        g_object_unref
    );

    if (result == nullptr) {
        g_debug("Could not load icon: %s", error->message);
        g_clear_error(&error);
        return generateAvatar("", "");
    }
    return result;
}

63 64 65 66
std::shared_ptr<GdkPixbuf>
PixbufManipulator::generateAvatar(const ContactMethod* cm) const
{
    auto cm_number = QString("0");
67
    QString bestName;
68 69 70 71 72
    if (cm) {
        auto hashName = cm->uri().userinfo();
        if (hashName.size() > 0) {
            cm_number = hashName.at(0);
        }
73
        // Get the bestName to draw
74 75
        if (!cm->bestName().isEmpty()) {
            // Prioritize the name
76
            bestName = cm->bestName().toUpper();
77 78
        } else if (!cm->bestId().isEmpty()) {
            // If the contact has no name, use the id
79
            bestName = cm->bestId().toUpper();
80
        }
81 82 83 84 85 86
    }

    bool ok;
    auto color = cm_number.toUInt(&ok, 16);
    if (!ok) color = 0;

87 88 89
    // Retrieve first character
    auto letter = bestName.isEmpty() ? "" : QString(bestName.at(0)).toStdString();

90 91 92
    return std::shared_ptr<GdkPixbuf> {
        ring_draw_fallback_avatar(
            FALLBACK_AVATAR_SIZE,
93
            letter,
94 95 96 97
            color
        ),
        g_object_unref
    };
98

99 100
}

101 102 103
std::shared_ptr<GdkPixbuf>
PixbufManipulator::generateAvatar(const std::string& alias, const std::string& uri) const
{
104
    std::string letter = {};
105 106 107 108 109 110 111 112
    if (!alias.empty()) {
        // Use QString for special characters like ø for example
        letter = QString(QString(alias.c_str()).toUpper().at(0)).toStdString();
    }
    auto color = 10; // 10 = default color (light grey)
    if (uri.length() > 0) {
        auto* md5 = g_compute_checksum_for_string(G_CHECKSUM_MD5, uri.c_str(), -1);
        color = std::string("0123456789abcdef").find(md5[0]);
113
    }
114 115 116 117 118 119 120 121 122 123 124

    return std::shared_ptr<GdkPixbuf> {
        ring_draw_fallback_avatar(
            FALLBACK_AVATAR_SIZE,
            letter,
            color
        ),
        g_object_unref
    };
}

125
std::shared_ptr<GdkPixbuf>
126 127
PixbufManipulator::scaleAndFrame(const GdkPixbuf *photo,
                                 const QSize& size,
128
                                 bool displayInformation,
129
                                 IconStatus status,
130
                                 uint unreadMessages)
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
{
    /**
     * for now, respect the height requested
     * the framing process will add another 10px, so account for that
     * when scaling the photos
     */

    int height = size.height();
    if (size.height() != size.width())
        g_warning("requested contact photo width != height; only respecting the height as the largest dimension");
    int photo_h = height - 10;
    int photo_w = photo_h;

    /* scale photo, make sure to respect the request height as the largest dimension*/
    int w = gdk_pixbuf_get_width(photo);
    int h = gdk_pixbuf_get_height(photo);
    if (h > w)
        photo_w = w * ((double)photo_h / h);
    if (w > h)
        photo_h = h * ((double)photo_w / w);

    std::unique_ptr<GdkPixbuf, decltype(g_object_unref)&> scaled_photo{
        gdk_pixbuf_scale_simple(photo, photo_w, photo_h, GDK_INTERP_BILINEAR),
        g_object_unref};

    /* frame photo */
aviau's avatar
aviau committed
157 158 159 160 161
    std::shared_ptr<GdkPixbuf> result {
        ring_frame_avatar(scaled_photo.get()),
        g_object_unref
    };

162 163
    /* draw information */
    if (displayInformation) {
164 165
        /* draw status */
        result.reset(ring_draw_status(result.get(), status), g_object_unref);
aviau's avatar
aviau committed
166

167 168 169 170
        /* draw visual notification for unread messages */
        if (unreadMessages)
            result.reset(ring_draw_unread_messages(result.get(), unreadMessages), g_object_unref);
    }
171

aviau's avatar
aviau committed
172
    return result;
173 174 175
}

QVariant
176
PixbufManipulator::callPhoto(Call* c, const QSize& size, bool displayInformation)
177
{
aviau's avatar
aviau committed
178 179
    if (c->type() == Call::Type::CONFERENCE) {
        /* conferences are always "online" */
180
        return QVariant::fromValue(scaleAndFrame(conferenceAvatar_.get(), size, displayInformation));
aviau's avatar
aviau committed
181
    }
182
    return callPhoto(c->peerContactMethod(), size, displayInformation);
183 184 185
}

QVariant
186
PixbufManipulator::callPhoto(const ContactMethod* n, const QSize& size, bool displayInformation)
187 188
{
    if (n->contact()) {
189
        return contactPhoto(n->contact(), size, displayInformation);
190
    } else {
191
        return QVariant::fromValue(scaleAndFrame(generateAvatar(n).get(), size, displayInformation));
192 193 194 195
    }
}

QVariant
196
PixbufManipulator::contactPhoto(Person* c, const QSize& size, bool displayInformation)
197 198 199
{
    /**
     * try to get the photo
200
     * otherwise use the generated avatar
201 202 203 204 205 206
     */

    std::shared_ptr<GdkPixbuf> photo;

    if (c->photo().isValid())
        photo = c->photo().value<std::shared_ptr<GdkPixbuf>>();
207 208 209 210
    else {
        auto cm = c->phoneNumbers().size() > 0 ? c->phoneNumbers().first() : nullptr;
        photo = generateAvatar(cm);
    }
211

212
    return QVariant::fromValue(scaleAndFrame(photo.get(), size, displayInformation));
213 214
}

215
QVariant PixbufManipulator::personPhoto(const QByteArray& data, const QString& type)
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
{
    Q_UNUSED(type);
    /* Try to load the image from the data provided by lrc vcard utils;
     * lrc is getting the image data assuming that it is inlined in the vcard,
     * for now URIs are not supported.
     *
     * The format of the data should be either base 64 or ascii (hex), try both
     */

    GError *error = NULL;
    GdkPixbuf *pixbuf = NULL;
    GInputStream *stream = NULL;

    /* first try using base64 */
    QByteArray ba64 = QByteArray::fromBase64(data);
    stream = g_memory_input_stream_new_from_data(ba64.constData(),
                                                 ba64.size(),
                                                 NULL);

    pixbuf = gdk_pixbuf_new_from_stream(stream, NULL, &error);
    g_input_stream_close(stream, NULL, NULL);
    g_object_unref(stream);

    if (!pixbuf) {
        // g_debug("failed decoding person photo using base64: %s", error->message);
241
        g_clear_error(&error);
242 243 244 245 246 247 248 249 250 251 252 253 254

        /* failed with base64, try hex */
        QByteArray baHex = QByteArray::fromHex(data);
        stream = g_memory_input_stream_new_from_data(baHex.constData(),
                                                     baHex.size(),
                                                     NULL);

        pixbuf = gdk_pixbuf_new_from_stream(stream, NULL, &error);
        g_input_stream_close(stream, NULL, NULL);
        g_object_unref(stream);

        if (!pixbuf) {
            // g_debug("failed decoding person photo using hex (ASCII): %s", error->message);
255
            g_clear_error(&error);
256 257 258 259 260 261 262 263 264 265 266
        }
    }

    if (pixbuf) {
        std::shared_ptr<GdkPixbuf> avatar(pixbuf, g_object_unref);
        return QVariant::fromValue(avatar);
    }

    /* could not load image, return emtpy QVariant */
    return QVariant();
}
267

268
QVariant
269
PixbufManipulator::conversationPhoto(const lrc::api::conversation::Info& conversationInfo,
270 271
                                     const lrc::api::account::Info& accountInfo,
                                     const QSize& size,
272
                                     bool displayInformation)
273
{
274
    auto contacts = conversationInfo.participants;
275 276 277 278 279 280 281 282
    if (!contacts.empty()) {
        try {
            // Get first contact photo
            auto contactUri = contacts.front();
            auto contactInfo = accountInfo.contactModel->getContact(contactUri);
            auto contactPhoto = contactInfo.profileInfo.avatar;
            auto bestName = contactInfo.profileInfo.alias.empty()? contactInfo.registeredName : contactInfo.profileInfo.alias;
            auto unreadMessages = conversationInfo.unreadMessages;
283 284 285 286
            auto status = contactInfo.isPresent? IconStatus::PRESENT : IconStatus::ABSENT;
            if (accountInfo.profileInfo.type == lrc::api::profile::Type::SIP && contactInfo.profileInfo.type == lrc::api::profile::Type::TEMPORARY)
            {
                return QVariant::fromValue(scaleAndFrame(generateAvatar("", "").get(), size, displayInformation, status));
287
            } else if (accountInfo.profileInfo.type == lrc::api::profile::Type::SIP) {
288
                return QVariant::fromValue(scaleAndFrame(generateAvatar("", "sip:" + contactInfo.profileInfo.uri).get(), size, displayInformation, status));
289
            } else if (contactInfo.profileInfo.type == lrc::api::profile::Type::TEMPORARY && contactInfo.profileInfo.uri.empty()) {
290
                return QVariant::fromValue(scaleAndFrame(temporaryItemAvatar().get(), size, false, status, unreadMessages));
291 292 293
            } else if (!contactPhoto.empty()) {
                QByteArray byteArray(contactPhoto.c_str(), contactPhoto.length());
                QVariant photo = personPhoto(byteArray);
294
                return QVariant::fromValue(scaleAndFrame(photo.value<std::shared_ptr<GdkPixbuf>>().get(), size, displayInformation, status, unreadMessages));
295
            } else {
296
                return QVariant::fromValue(scaleAndFrame(generateAvatar(bestName, "ring:" + contactInfo.profileInfo.uri).get(), size, displayInformation, status, unreadMessages));
297 298
            }
        } catch (...) {}
299
    }
300
    return QVariant::fromValue(scaleAndFrame(generateAvatar("", "").get(), size, displayInformation));
301 302 303

}

304
QVariant
305
PixbufManipulator::numberCategoryIcon(const QVariant& p, const QSize& size, bool displayInformation, bool isPresent)
306 307 308
{
    Q_UNUSED(p)
    Q_UNUSED(size)
309
    Q_UNUSED(displayInformation)
310 311 312 313 314 315 316 317 318 319 320 321 322 323
    Q_UNUSED(isPresent)
    return QVariant();
}

QVariant
PixbufManipulator::securityIssueIcon(const QModelIndex& index)
{
    Q_UNUSED(index)
    return QVariant();
}

QByteArray
PixbufManipulator::toByteArray(const QVariant& pxm)
{
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
    std::shared_ptr<GdkPixbuf> pixbuf_photo = pxm.value<std::shared_ptr<GdkPixbuf>>();

    if(pixbuf_photo.get()) {
        gchar* png_buffer = nullptr;
        gsize png_buffer_size;
        GError *error = nullptr;

        gdk_pixbuf_save_to_buffer(pixbuf_photo.get(), &png_buffer, &png_buffer_size, "png", &error, NULL);
        QByteArray array = QByteArray(png_buffer, png_buffer_size);

        g_free(png_buffer);

        if (error != NULL) {
            g_warning("in toByteArray, gdk_pixbuf_save_to_buffer failed : %s\n", error->message);
            g_clear_error(&error);
        }

        return array;
    } else {
        g_debug("in toByteArray, failed to retrieve data from parameter pxm");
        return QByteArray();
    }
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
}

QVariant
PixbufManipulator::collectionIcon(const CollectionInterface* interface, PixmapManipulatorI::CollectionIconHint hint) const
{
    Q_UNUSED(interface)
    Q_UNUSED(hint)
    return QVariant();
}
QVariant
PixbufManipulator::securityLevelIcon(const SecurityEvaluationModel::SecurityLevel level) const
{
    Q_UNUSED(level)
    return QVariant();
}
QVariant
PixbufManipulator::historySortingCategoryIcon(const CategorizedHistoryModel::SortedProxy::Categories cat) const
{
    Q_UNUSED(cat)
    return QVariant();
}
QVariant
PixbufManipulator::contactSortingCategoryIcon(const CategorizedContactModel::SortedProxy::Categories cat) const
{
    Q_UNUSED(cat)
    return QVariant();
}
QVariant
PixbufManipulator::userActionIcon(const UserActionElement& state) const
{
    Q_UNUSED(state)
    return QVariant();
}

380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
QVariant PixbufManipulator::decorationRole(const QModelIndex& index)
{
    Q_UNUSED(index)
    return QVariant();
}

QVariant PixbufManipulator::decorationRole(const Call* c)
{
    Q_UNUSED(c)
    return QVariant();
}

QVariant PixbufManipulator::decorationRole(const ContactMethod* cm)
{
    Q_UNUSED(cm)
    return QVariant();
}

QVariant PixbufManipulator::decorationRole(const Person* p)
{
    Q_UNUSED(p)
    return QVariant();
}

404 405 406 407 408 409
QVariant PixbufManipulator::decorationRole(const Account* p)
{
    Q_UNUSED(p)
    return QVariant();
}

410 411 412 413 414 415 416 417
QVariant PixbufManipulator::decorationRole(const lrc::api::conversation::Info& conversation,
                                           const lrc::api::account::Info& accountInfo)
{
    Q_UNUSED(conversation)
    Q_UNUSED(accountInfo)
    return QVariant();
}

418
} // namespace Interfaces