utils.cpp 19.3 KB
Newer Older
1
/***************************************************************************
2
 * Copyright (C) 2015-2019 by Savoir-faire Linux                           *
3
 * Author: Edric Ladent Milaret <edric.ladent-milaret@savoirfairelinux.com>*
4
 * Author: Andreas Traczyk <andreas.traczyk@savoirfairelinux.com>          *
5
 * Author: Isa Nanic <isa.nanic@savoirfairelinux.com                       *
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
 *                                                                         *
 * 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, see <http://www.gnu.org/licenses/>.   *
 **************************************************************************/

#include "utils.h"

23
#ifdef Q_OS_WIN
24
#include <windows.h>
25 26 27 28 29 30 31
#include <lmcons.h>
#include <shobjidl.h>
#include <shlguid.h>
#include <shlobj.h>
#include <shlwapi.h>
#endif

32 33 34
//Qt
#include <QObject>
#include <QErrorMessage>
Edric Milaret's avatar
Edric Milaret committed
35
#include <QPainter>
36 37
#include <QStackedWidget>
#include <QPropertyAnimation>
38
#include <QApplication>
39
#include <QFile>
40

Andreas Traczyk's avatar
Andreas Traczyk committed
41
#include <globalinstances.h>
42

Andreas Traczyk's avatar
Andreas Traczyk committed
43
#include "pixbufmanipulator.h"
44
#include "globalsystemtray.h"
45
#include "lrcinstance.h"
46

47
bool
48 49
Utils::CreateStartupLink()
{
50
#ifdef Q_OS_WIN
51 52 53 54
    TCHAR szPath[MAX_PATH];
    GetModuleFileName(NULL, szPath, MAX_PATH);

    std::wstring programPath(szPath);
55

56 57
    TCHAR startupPath[MAX_PATH];
    SHGetFolderPathW(NULL, CSIDL_STARTUP, NULL, 0, startupPath);
58

59
    std::wstring linkPath(startupPath);
60
    linkPath += TEXT("\\Jami.lnk");
61 62

    return Utils::CreateLink(programPath.c_str(), linkPath.c_str());
63 64 65
#else
    return true;
#endif
66 67 68 69
}

bool
Utils::CreateLink(LPCWSTR lpszPathObj, LPCWSTR lpszPathLink) {
70
#ifdef Q_OS_WIN
71 72 73 74 75 76 77 78 79
    HRESULT hres;
    IShellLink* psl;

    hres = CoCreateInstance(CLSID_ShellLink, NULL,
                            CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID*)&psl);
    if (SUCCEEDED(hres))
    {
        IPersistFile* ppf;
        psl->SetPath(lpszPathObj);
80
        psl->SetArguments(TEXT("--minimized"));
81 82 83 84 85 86 87 88 89 90

        hres = psl->QueryInterface(IID_IPersistFile, (LPVOID*)&ppf);
        if (SUCCEEDED(hres))
        {
            hres = ppf->Save(lpszPathLink, TRUE);
            ppf->Release();
        }
        psl->Release();
    }
    return hres;
91
#else
92 93
    Q_UNUSED(lpszPathObj)
    Q_UNUSED(lpszPathLink)
94 95
    return true;
#endif
96 97 98 99
}

void
Utils::DeleteStartupLink() {
100
#ifdef Q_OS_WIN
101 102
    TCHAR startupPath[MAX_PATH];
    SHGetFolderPathW(NULL, CSIDL_STARTUP, NULL, 0, startupPath);
103

104
    std::wstring linkPath(startupPath);
105
    linkPath += TEXT("\\Jami.lnk");
106 107

    DeleteFile(linkPath.c_str());
108
#endif
109 110 111 112
}

bool
Utils::CheckStartupLink() {
113
#ifdef Q_OS_WIN
114 115
    TCHAR startupPath[MAX_PATH];
    SHGetFolderPathW(NULL, CSIDL_STARTUP, NULL, 0, startupPath);
116

117
    std::wstring linkPath(startupPath);
118
    linkPath += TEXT("\\Jami.lnk");
119
    return PathFileExists(linkPath.c_str());
120 121 122
#else
    return true;
#endif
123 124
}

125 126
QString
Utils::GetRingtonePath() {
127
#ifdef Q_OS_WIN
128 129 130 131
    TCHAR workingDirectory[MAX_PATH];
    GetCurrentDirectory(MAX_PATH, workingDirectory);

    QString ringtonePath = QString::fromWCharArray(workingDirectory);
132
    ringtonePath += QStringLiteral("\\ringtones\\default.opus");
133
    return ringtonePath;
134 135 136
#else
    return QString("/usr/local");
#endif
137 138
}

139 140
QString
Utils::GenGUID() {
141
#ifdef Q_OS_WIN
142 143 144 145 146 147 148 149 150
    GUID gidReference;
    wchar_t *str;
    HRESULT hCreateGuid = CoCreateGuid(&gidReference);
    if (hCreateGuid == S_OK) {
        StringFromCLSID(gidReference, &str);
        auto gStr = QString::fromWCharArray(str);
        return gStr.remove("{").remove("}").toLower();
    }
    else
151
        return QString();
152 153 154 155 156 157 158
#else
    return QString("");
#endif
}

QString
Utils::GetISODate() {
159
#ifdef Q_OS_WIN
160 161 162 163 164
    SYSTEMTIME lt;
    GetSystemTime(&lt);
    return QString("%1-%2-%3T%4:%5:%6Z").arg(lt.wYear).arg(lt.wMonth,2,10,QChar('0')).arg(lt.wDay,2,10,QChar('0'))
            .arg(lt.wHour,2,10,QChar('0')).arg(lt.wMinute,2,10,QChar('0')).arg(lt.wSecond,2,10,QChar('0'));
#else
165 166 167 168
    return QString();
#endif
}

169 170 171 172
void
Utils::InvokeMailto(const QString& subject,
                    const QString& body,
                    const QString& attachement) {
173 174 175 176 177 178 179 180 181 182 183 184 185
#ifdef Q_OS_WIN
    HKEY hKey;
    LONG lRes = RegOpenKeyExW(HKEY_CLASSES_ROOT, L"mailto", 0, KEY_READ, &hKey);
    if (lRes != ERROR_FILE_NOT_FOUND) {
        auto addr = QString("mailto:?subject=%1&body=%2").arg(subject).arg(body);
        if (not attachement.isEmpty())
            addr += QString("&attachement=%1").arg(attachement);
        ShellExecute(nullptr, L"open", addr.toStdWString().c_str(), NULL, NULL, SW_SHOWNORMAL);
    } else {
        QErrorMessage errorMessage;
        errorMessage.showMessage(QObject::tr("No default mail client found"));
    }
#endif
186
}
Edric Milaret's avatar
Edric Milaret committed
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208

QImage
Utils::getCirclePhoto(const QImage original, int sizePhoto)
{
    QImage target(sizePhoto, sizePhoto, QImage::Format_ARGB32_Premultiplied);
    target.fill(Qt::transparent);

    QPainter painter(&target);
    painter.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);
    painter.setBrush(QBrush(Qt::white));
    auto scaledPhoto = original
            .scaled(sizePhoto, sizePhoto, Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation)
            .convertToFormat(QImage::Format_ARGB32_Premultiplied);
    int margin = 0;
    if (scaledPhoto.width() > sizePhoto) {
        margin = (scaledPhoto.width() - sizePhoto) / 2;
    }
    painter.drawEllipse(0, 0, sizePhoto, sizePhoto);
    painter.setCompositionMode(QPainter::CompositionMode_SourceIn);
    painter.drawImage(0, 0, scaledPhoto, margin, 0);
    return target;
}
209 210

void
211
Utils::setStackWidget(QStackedWidget* stack, QWidget* widget)
212
{
213
    if (stack->indexOf(widget) != -1 && stack->currentWidget() != widget) {
214 215 216
        stack->setCurrentWidget(widget);
    }
}
217 218 219

void Utils::showSystemNotification(QWidget* widget, const QString & message, long delay)
{
Andreas Traczyk's avatar
Andreas Traczyk committed
220 221 222 223 224 225 226 227 228 229 230 231
    GlobalSystemTray::instance().showMessage(message, "", QIcon(":images/jami.png"));
    QApplication::alert(widget, delay);
}

void Utils::showSystemNotification(QWidget* widget,
    const QString & sender,
    const QString & message,
    long delay)
{
    QIcon();
    GlobalSystemTray::instance()
        .showMessage(sender, message, QIcon(":images/jami.png"));
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
    QApplication::alert(widget, delay);
}

// new lrc helpers

inline std::string
removeEndlines(const std::string& str)
{
    std::string trimmed(str);
    trimmed.erase(std::remove(trimmed.begin(), trimmed.end(), '\n'), trimmed.end());
    trimmed.erase(std::remove(trimmed.begin(), trimmed.end(), '\r'), trimmed.end());
    return trimmed;
}

std::string
Utils::bestIdForConversation(const lrc::api::conversation::Info& conv, const lrc::api::ConversationModel& model)
{
    auto contact = model.owner.contactModel->getContact(conv.participants[0]);
    if (!contact.registeredName.empty()) {
        return removeEndlines(contact.registeredName);
    }
    return removeEndlines(contact.profileInfo.uri);
}

std::string
Utils::bestIdForAccount(const lrc::api::account::Info& account)
{
    if (!account.registeredName.empty()) {
        return removeEndlines(account.registeredName);
    }
    return removeEndlines(account.profileInfo.uri);
}

std::string
Utils::bestNameForAccount(const lrc::api::account::Info& account)
{
    if (account.profileInfo.alias.empty()) {
        return bestIdForAccount(account);
    }
    return account.profileInfo.alias;
}

std::string
Utils::bestIdForContact(const lrc::api::contact::Info& contact)
{
    if (!contact.registeredName.empty()) {
        return removeEndlines(contact.registeredName);
    }
    return removeEndlines(contact.profileInfo.uri);
}

std::string
Utils::bestNameForContact(const lrc::api::contact::Info& contact)
{
    auto alias = removeEndlines(contact.profileInfo.alias);
    if (alias.length() == 0) {
        return bestIdForContact(contact);
    }
    return alias;
}

std::string
Utils::bestNameForConversation(const lrc::api::conversation::Info& conv, const lrc::api::ConversationModel& model)
{
    auto contact = model.owner.contactModel->getContact(conv.participants[0]);
    auto alias = removeEndlines(contact.profileInfo.alias);
    if (alias.length() == 0) {
        return bestIdForConversation(conv, model);
    }
    return alias;
}

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
// returns empty string if only infoHash is available, second best identifier otherwise
std::string
Utils::secondBestNameForAccount(const lrc::api::account::Info& account)
{
    auto alias = removeEndlines(account.profileInfo.alias);
    auto registeredName = removeEndlines(account.registeredName);
    auto infoHash = account.profileInfo.uri;

    if (!alias.length() == 0) { // if alias exists
        if (!registeredName.length() == 0) { // if registeredName exists
            return registeredName;
        }
        else {
            return infoHash;
        }
    }
    else {
        if (!registeredName.length() == 0) { // if registeredName exists
            return infoHash;
        }
        else {
            return "";
        }
    }
}

330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 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 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
lrc::api::profile::Type
Utils::profileType(const lrc::api::conversation::Info& conv, const lrc::api::ConversationModel& model)
{
    try {
        auto contact = model.owner.contactModel->getContact(conv.participants[0]);
        return contact.profileInfo.type;
    }
    catch (...) {
        return lrc::api::profile::Type::INVALID;
    }
}

std::string
Utils::formatTimeString(const std::time_t& timestamp)
{
    std::time_t now = std::time(nullptr);
    char interactionDay[64];
    char nowDay[64];
    std::strftime(interactionDay, sizeof(interactionDay), "%D", std::localtime(&timestamp));
    std::strftime(nowDay, sizeof(nowDay), "%D", std::localtime(&now));
    if (std::string(interactionDay) == std::string(nowDay)) {
        char interactionTime[64];
        std::strftime(interactionTime, sizeof(interactionTime), "%R", std::localtime(&timestamp));
        return interactionTime;
    }
    else {
        return interactionDay;
    }
}

lrc::api::ConversationModel::ConversationQueue::const_iterator
Utils::getConversationFromUid(const std::string& uid, const lrc::api::ConversationModel& model) {
    return std::find_if(model.allFilteredConversations().begin(), model.allFilteredConversations().end(),
        [&](const lrc::api::conversation::Info& conv) {
            return uid == conv.uid;
        });
}

lrc::api::ConversationModel::ConversationQueue::const_iterator
Utils::getConversationFromUri(const std::string& uri, const lrc::api::ConversationModel& model) {
    return std::find_if(model.allFilteredConversations().begin(), model.allFilteredConversations().end(),
        [&](const lrc::api::conversation::Info& conv) {
            return uri == conv.participants[0];
        });
}

bool
Utils::isInteractionGenerated(const lrc::api::interaction::Type& type)
{
    return  type == lrc::api::interaction::Type::CALL ||
            type == lrc::api::interaction::Type::CONTACT;
}

bool
Utils::isContactValid(const std::string& contactUid, const lrc::api::ConversationModel& model)
{
    auto contact = model.owner.contactModel->getContact(contactUid);
    return  (contact.profileInfo.type == lrc::api::profile::Type::PENDING ||
            contact.profileInfo.type == lrc::api::profile::Type::TEMPORARY ||
            contact.profileInfo.type == lrc::api::profile::Type::RING ||
            contact.profileInfo.type == lrc::api::profile::Type::SIP) &&
            !contact.profileInfo.uri.empty();
}

QImage
Utils::conversationPhoto(const std::string & convUid, const lrc::api::account::Info& accountInfo)
{
397 398 399 400 401
    auto convInfo = getConversationFromUid(convUid, false);
    if (!convInfo.uid.empty()) {
        return GlobalInstances::pixmapManipulator()
            .decorationRole(convInfo, accountInfo)
            .value<QImage>();
402
    }
403
    return QImage();
404
}
405

Andreas Traczyk's avatar
Andreas Traczyk committed
406 407 408 409 410 411 412 413 414 415 416 417 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 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
QColor
Utils::getAvatarColor(const QString& canonicalUri) {
    if (canonicalUri.isEmpty()) {
        return RingTheme::defaultAvatarColor_;
    }
    auto h = QString(QCryptographicHash::hash(canonicalUri.toLocal8Bit(), QCryptographicHash::Md5).toHex());
    if (h.isEmpty() || h.isNull()) {
        return RingTheme::defaultAvatarColor_;
    }
    auto colorIndex = std::string("0123456789abcdef").find(h.at(0).toLatin1());
    return RingTheme::avatarColors_[colorIndex];
}

// Generate a QImage representing a dummy user avatar, when user doesn't provide it.
// Current rendering is a flat colored circle with a centered letter.
// The color of the letter is computed from the circle color to be visible whaterver be the circle color.
QImage
Utils::fallbackAvatar(const QSize size, const QString& canonicalUriStr, const QString& letterStr)
{
    // We start with a transparent avatar
    QImage avatar(size, QImage::Format_ARGB32);
    avatar.fill(Qt::transparent);

    // We pick a color based on the passed character
    QColor avColor = getAvatarColor(canonicalUriStr);

    // We draw a circle with this color
    QPainter painter(&avatar);
    painter.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);
    painter.setPen(Qt::transparent);
    painter.setBrush(avColor.lighter(110));
    painter.drawEllipse(avatar.rect());

    // If a letter was passed, then we paint a letter in the circle,
    // otherwise we draw the default avatar icon
    QString letterStrCleaned(letterStr);
    letterStrCleaned.remove(QRegExp("[\\n\\t\\r]"));
    if (!letterStr.isEmpty()) {
        auto letter = letterStr.at(0).toUpper().toLatin1();
        QFont font("Arial", avatar.height() / 2.66667, QFont::Medium);
        painter.setFont(font);
        painter.setPen(Qt::white);
        painter.drawText(avatar.rect(), QString(letter), QTextOption(Qt::AlignCenter));
    } else {
        QRect overlayRect = avatar.rect();
        qreal margin = (0.05 * overlayRect.width());
        overlayRect.moveLeft(overlayRect.left() + margin * 0.5);
        overlayRect.moveTop(overlayRect.top() + margin * 0.5);
        overlayRect.setWidth(overlayRect.width() - margin);
        overlayRect.setHeight(overlayRect.height() - margin);
        painter.drawPixmap(overlayRect, QPixmap(":/images/default_avatar_overlay.svg"));
    }

    return avatar;
}

QImage
Utils::fallbackAvatar(const QSize size, const ContactMethod* cm)
{
    if (cm == nullptr) {
        return QImage();
    }
    QImage image;
    auto letterStr = QString();
    if (cm->uri().userinfo() != cm->bestName()) {
        letterStr = cm->bestName();
    }
    image = fallbackAvatar(size,
        cm->uri().full(),
        letterStr);
    return image;
}

QImage
Utils::fallbackAvatar(const QSize size, const std::string& alias, const std::string& uri)
{
    return fallbackAvatar(size,
        QString::fromStdString(uri),
        QString::fromStdString(alias));
}

QByteArray
Utils::QImageToByteArray(QImage image)
{
    QByteArray ba;
    QBuffer buffer(&ba);
    buffer.open(QIODevice::WriteOnly);
    image.save(&buffer, "PNG");
    return ba;
}

QImage
Utils::cropImage(const QImage& img)
{
    QRect rect;
    auto w = img.width();
    auto h = img.height();
    if (w > h) {
        return img.copy({ (w - h) / 2, 0, h, h });
    }
    return img.copy({ 0, (h - w) / 2, w, w });
}

509 510 511 512 513 514 515 516 517 518
QByteArray
Utils::QByteArrayFromFile(const QString& filename)
{
    QFile file(filename);
    if (file.open(QIODevice::ReadOnly)) {
        return file.readAll();
    } else {
        qDebug() << "can't open file";
        return QByteArray();
    }
Andreas Traczyk's avatar
Andreas Traczyk committed
519 520 521 522 523 524 525 526 527 528 529 530 531 532
}

QPixmap
Utils::generateTintedPixmap(const QString& filename, QColor color)
{
    QPixmap px(filename);
    QImage tmpImage = px.toImage();
    for (int y = 0; y < tmpImage.height(); y++) {
        for (int x = 0; x < tmpImage.width(); x++) {
            color.setAlpha(tmpImage.pixelColor(x, y).alpha());
            tmpImage.setPixelColor(x, y, color);
        }
    }
    return QPixmap::fromImage(tmpImage);
533 534
}

Andreas Traczyk's avatar
Andreas Traczyk committed
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
QImage
Utils::scaleAndFrame(const QImage photo, const QSize& size)
{
    return photo.scaled(size, Qt::KeepAspectRatio, Qt::SmoothTransformation);
}

QImage
Utils::accountPhoto(const lrc::api::account::Info& accountInfo, const QSize& size)
{
    QImage photo;
    if (!accountInfo.profileInfo.avatar.empty()) {
        QByteArray ba = QByteArray::fromStdString(accountInfo.profileInfo.avatar);
        photo = GlobalInstances::pixmapManipulator().personPhoto(ba, nullptr).value<QImage>();
    } else {
        auto bestId = bestIdForAccount(accountInfo);
        auto bestName = bestNameForAccount(accountInfo);
        QString letterStr = bestId == bestName ? QString() : QString::fromStdString(bestName);
        photo = fallbackAvatar(size,
            QString::fromStdString("ring:" + bestId),
            letterStr);
    }
    return scaleAndFrame(photo, size);
}

559 560
lrc::api::conversation::Info
Utils::getConversationFromCallId(const std::string & callId)
561 562
{
    auto convModel = LRCInstance::getCurrentConversationModel();
563 564 565 566 567 568 569 570 571 572
    using namespace lrc::api::profile;
    for (int i = toUnderlyingValue(Type::RING); i <= toUnderlyingValue(Type::TEMPORARY); ++i) {
        auto filter = toEnum<lrc::api::profile::Type>(i);
        auto conversations = convModel->getFilteredConversations(filter);
        auto conv = std::find_if(conversations.begin(), conversations.end(),
            [&](const lrc::api::conversation::Info& conv) {
                return callId == conv.callId;
            });
        if (conv != conversations.end()) {
            return *conv;
573 574
        }
    }
575
    return lrc::api::conversation::Info();
Andreas Traczyk's avatar
Andreas Traczyk committed
576
}
577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605

lrc::api::conversation::Info
Utils::getSelectedConversation()
{
    return getConversationFromUid(LRCInstance::getSelectedConvUid(), false);
}

lrc::api::conversation::Info
Utils::getConversationFromUid(const std::string & convUid, bool filtered)
{
    auto convModel = LRCInstance::getCurrentConversationModel();
    if (filtered) {
        auto conversation = getConversationFromUid(convUid, *convModel);
    } else {
        using namespace lrc::api::profile;
        for (int i = toUnderlyingValue(Type::RING); i <= toUnderlyingValue(Type::TEMPORARY); ++i) {
            auto filter = toEnum<lrc::api::profile::Type>(i);
            auto conversations = convModel->getFilteredConversations(filter);
            auto conv = std::find_if(conversations.begin(), conversations.end(),
                [&](const lrc::api::conversation::Info& conv) {
                    return convUid == conv.uid;
                });
            if (conv != conversations.end()) {
                return *conv;
            }
        }
    }
    return lrc::api::conversation::Info();
}
Andreas Traczyk's avatar
Andreas Traczyk committed
606 607 608 609 610 611 612 613 614 615 616 617

void
Utils::swapQListWidgetItems(QListWidget* list, bool down)
{
    QListWidgetItem *current = list->currentItem();
    int currIndex = list->row(current);
    QListWidgetItem *other = list->item(list->row(current) + (down ? 1 : -1));
    int otherIndex = list->row(other);
    QListWidgetItem *temp = list->takeItem(otherIndex);
    down ? list->insertItem(currIndex, temp) : list->insertItem(otherIndex, current);
    down ? list->insertItem(otherIndex, current) : list->insertItem(currIndex, temp);
}