plugin: implement PATH preference

Change-Id: If86856104409c9c6f8402e0c9229481d18c5b84f
This commit is contained in:
agsantos
2020-09-01 18:19:22 -04:00
parent 9c9bdafe9c
commit 90a1dbce27
21 changed files with 381 additions and 721 deletions

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24px" height="24px"><path d="M0 0h24v24H0z" fill="none"/><path d="M6 2c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8l-6-6H6zm7 7V3.5L18.5 9H13z"/></svg>

After

Width:  |  Height:  |  Size: 237 B

View File

@@ -136,7 +136,7 @@ HEADERS += ./src/smartlistmodel.h \
./src/qmladapterbase.h \ ./src/qmladapterbase.h \
./src/avadapter.h \ ./src/avadapter.h \
./src/contactadapter.h \ ./src/contactadapter.h \
./src/mediahandleradapter.h \ ./src/pluginadapter.h \
./src/settingsadapter.h \ ./src/settingsadapter.h \
./src/deviceitemlistmodel.h \ ./src/deviceitemlistmodel.h \
./src/pluginitemlistmodel.h \ ./src/pluginitemlistmodel.h \
@@ -150,7 +150,6 @@ HEADERS += ./src/smartlistmodel.h \
./src/videoinputdevicemodel.h \ ./src/videoinputdevicemodel.h \
./src/audiooutputdevicemodel.h \ ./src/audiooutputdevicemodel.h \
./src/pluginlistpreferencemodel.h \ ./src/pluginlistpreferencemodel.h \
./src/mediahandlerlistpreferencemodel.h \
./src/videoformatfpsmodel.h \ ./src/videoformatfpsmodel.h \
./src/videoformatresolutionmodel.h \ ./src/videoformatresolutionmodel.h \
./src/audiomanagerlistmodel.h \ ./src/audiomanagerlistmodel.h \
@@ -176,7 +175,7 @@ SOURCES += ./src/bannedlistmodel.cpp \
./src/previewrenderer.cpp \ ./src/previewrenderer.cpp \
./src/avadapter.cpp \ ./src/avadapter.cpp \
./src/contactadapter.cpp \ ./src/contactadapter.cpp \
./src/mediahandleradapter.cpp \ ./src/pluginadapter.cpp \
./src/settingsadapter.cpp \ ./src/settingsadapter.cpp \
./src/deviceitemlistmodel.cpp \ ./src/deviceitemlistmodel.cpp \
./src/pluginitemlistmodel.cpp \ ./src/pluginitemlistmodel.cpp \
@@ -190,7 +189,6 @@ SOURCES += ./src/bannedlistmodel.cpp \
./src/videoinputdevicemodel.cpp \ ./src/videoinputdevicemodel.cpp \
./src/audiooutputdevicemodel.cpp \ ./src/audiooutputdevicemodel.cpp \
./src/pluginlistpreferencemodel.cpp \ ./src/pluginlistpreferencemodel.cpp \
./src/mediahandlerlistpreferencemodel.cpp \
./src/videoformatfpsmodel.cpp \ ./src/videoformatfpsmodel.cpp \
./src/videoformatresolutionmodel.cpp \ ./src/videoformatresolutionmodel.cpp \
./src/audiomanagerlistmodel.cpp \ ./src/audiomanagerlistmodel.cpp \

View File

@@ -117,5 +117,6 @@
<file>images/icons/drafts-24px.svg</file> <file>images/icons/drafts-24px.svg</file>
<file>images/icons/person_add-24px.svg</file> <file>images/icons/person_add-24px.svg</file>
<file>images/icons/router-24px.svg</file> <file>images/icons/router-24px.svg</file>
<file>images/icons/insert_drive_file-24dp.svg</file>
</qresource> </qresource>
</RCC> </RCC>

View File

@@ -26,7 +26,7 @@
#include "bannedlistmodel.h" #include "bannedlistmodel.h"
#include "calladapter.h" #include "calladapter.h"
#include "contactadapter.h" #include "contactadapter.h"
#include "mediahandleradapter.h" #include "pluginadapter.h"
#include "conversationsadapter.h" #include "conversationsadapter.h"
#include "deviceitemlistmodel.h" #include "deviceitemlistmodel.h"
#include "pluginitemlistmodel.h" #include "pluginitemlistmodel.h"

View File

@@ -34,35 +34,35 @@ ItemDelegate {
enum Type { enum Type {
LIST, LIST,
USERLIST, PATH,
DEFAULT DEFAULT
} }
property string preferenceName: "" property string preferenceName: ""
property string preferenceSummary: "" property string preferenceSummary: ""
property string preferenceKey: ""
property int preferenceType: -1 property int preferenceType: -1
property string preferenceCurrentValue: "" property string preferenceCurrentValue: ""
property string preferenceNewValue: "" property string preferenceNewValue: ""
property string pluginId: "" property string pluginId: ""
property string currentPath: ""
property bool isImage: false
property var fileFilters: []
property PluginListPreferenceModel pluginListPreferenceModel property PluginListPreferenceModel pluginListPreferenceModel
signal btnPreferenceClicked signal btnPreferenceClicked
signal preferenceAdded
function getNewPreferenceValueSlot(index){ function getNewPreferenceValueSlot(index){
pluginListPreferenceModel.idx = index
preferenceNewValue = pluginListPreferenceModel.preferenceNewValue
switch (preferenceType){ switch (preferenceType){
case PreferenceItemDelegate.LIST: case PreferenceItemDelegate.LIST:
pluginListPreferenceModel.idx = index
preferenceNewValue = pluginListPreferenceModel.preferenceNewValue
btnPreferenceClicked() btnPreferenceClicked()
break break
case PreferenceItemDelegate.USERLIST: case PreferenceItemDelegate.PATH:
if(index == 0){ if(index == 0){
preferenceFilePathDialog.pluginListPreferenceModel = pluginListPreferenceModel
preferenceFilePathDialog.title = qsTr("Select An Image to " + preferenceName) preferenceFilePathDialog.title = qsTr("Select An Image to " + preferenceName)
preferenceFilePathDialog.nameFilters = [qsTr("PNG Files") + " (*.png)", qsTr( preferenceFilePathDialog.nameFilters = fileFilters
"All files") + " (*)"]
preferenceFilePathDialog.preferenceKey = pluginListPreferenceModel.preferenceKey
preferenceFilePathDialog.open() preferenceFilePathDialog.open()
} }
else else
@@ -76,36 +76,28 @@ ItemDelegate {
FileDialog { FileDialog {
id: preferenceFilePathDialog id: preferenceFilePathDialog
property string preferenceKey: ""
property PluginListPreferenceModel pluginListPreferenceModel
title: qsTr("Please choose a file") title: qsTr("Please choose a file")
folder: StandardPaths.writableLocation(StandardPaths.DownloadLocation) folder: "file://" + currentPath
onRejected: preferenceAdded()
onAccepted: { onAccepted: {
var url = ClientWrapper.utilsAdaptor.getAbsPath(fileUrl.toString()) var url = ClientWrapper.utilsAdaptor.getAbsPath(fileUrl.toString())
ClientWrapper.pluginModel.addValueToPreference(pluginId, preferenceKey, url) preferenceNewValue = url
pluginListPreferenceModel.populateLists() btnPreferenceClicked()
pluginListPreferenceModel.getCurrentSettingIndex()
preferenceAdded()
} }
} }
RowLayout{ RowLayout{
anchors.fill: parent anchors.fill: parent
Label{ Label {
visible: preferenceType === PreferenceItemDelegate.DEFAULT Layout.preferredWidth: root.width / 2
Layout.fillWidth: true Layout.alignment: Qt.AlignLeft | Qt.AlignVCenter
Layout.alignment: Qt.AlingVCenter | Qt.AligntLeft
Layout.leftMargin: 8 Layout.leftMargin: 8
font.pointSize: JamiTheme.settingsFontSize
font.kerning: true
font.bold: true
text: preferenceName text: preferenceName
font.pointSize: JamiTheme.settingsFontSize
ToolTip.visible: hovered
ToolTip.text: preferenceSummary
} }
HoverableRadiusButton{ HoverableRadiusButton{
@@ -135,19 +127,6 @@ ItemDelegate {
} }
} }
Label {
visible: preferenceType === PreferenceItemDelegate.LIST
Layout.preferredWidth: root.width / 2
Layout.alignment: Qt.AlignLeft | Qt.AlignVCenter
Layout.leftMargin: 8
text: preferenceName
font.pointSize: JamiTheme.settingsFontSize
ToolTip.visible: hovered
ToolTip.text: preferenceSummary
}
SettingParaCombobox { SettingParaCombobox {
id: listPreferenceComboBox id: listPreferenceComboBox
visible: preferenceType === PreferenceItemDelegate.LIST visible: preferenceType === PreferenceItemDelegate.LIST
@@ -167,35 +146,29 @@ ItemDelegate {
} }
} }
Label { HoverableRadiusButton {
visible: preferenceType === PreferenceItemDelegate.USERLIST id: pathPreferenceButton
Layout.preferredWidth: root.width / 2 visible: preferenceType === PreferenceItemDelegate.PATH
Layout.leftMargin: 8 Layout.preferredWidth: root.width / 2 - 16
Layout.alignment: Qt.AlignLeft | Qt.AlignVCenter Layout.maximumWidth: root.width / 2 - 16
text: preferenceName
font.pointSize: JamiTheme.settingsFontSize
ToolTip.visible: hovered
ToolTip.text: preferenceSummary
}
SettingParaCombobox {
id: userListPreferenceComboBox
visible: preferenceType === PreferenceItemDelegate.USERLIST
Layout.preferredWidth: root.width / 2 - 8
Layout.alignment: Qt.AlignRight | Qt.AlignVCenter Layout.alignment: Qt.AlignRight | Qt.AlignVCenter
Layout.rightMargin: 8 Layout.rightMargin: 30
Layout.preferredHeight: 30
font.pointSize: JamiTheme.settingsFontSize radius: height / 2
font.kerning: true
model: pluginListPreferenceModel icon.source: "qrc:/images/icons/round-folder-24px.svg"
currentIndex: pluginListPreferenceModel.getCurrentSettingIndex() icon.height: 24
textRole: qsTr("PreferenceValue") icon.width: 24
tooltipText: qsTr("Choose the preference")
onActivated: { toolTipText: qsTr("Press to choose an image file")
getNewPreferenceValueSlot(index) text: {
return ClientWrapper.utilsAdaptor.fileName(preferenceCurrentValue)
}
fontPointSize: JamiTheme.buttonFontSize
onClicked: {
getNewPreferenceValueSlot(0)
} }
} }
} }

View File

@@ -27,7 +27,7 @@ Popup {
id: root id: root
function toggleMediaHandlerSlot(mediaHandlerId, isLoaded) { function toggleMediaHandlerSlot(mediaHandlerId, isLoaded) {
ClientWrapper.pluginModel.toggleCallMediaHandler(mediaHandlerId, !isLoaded) ClientWrapper.pluginModel.toggleCallMediaHandler(mediaHandlerId, !isLoaded)
mediahandlerPickerListView.model = MediaHandlerAdapter.getMediaHandlerSelectableModel() mediahandlerPickerListView.model = PluginAdapter.getMediaHandlerSelectableModel()
} }
width: 350 width: 350
@@ -96,7 +96,7 @@ Popup {
Layout.preferredWidth: mediahandlerPickerPopupRect.width Layout.preferredWidth: mediahandlerPickerPopupRect.width
Layout.preferredHeight: 200 Layout.preferredHeight: 200
model: MediaHandlerAdapter.getMediaHandlerSelectableModel() model: PluginAdapter.getMediaHandlerSelectableModel()
clip: true clip: true
@@ -119,7 +119,7 @@ Popup {
onOpenPreferences: { onOpenPreferences: {
mediahandlerPreferencePickerListView.pluginId = pluginId mediahandlerPreferencePickerListView.pluginId = pluginId
mediahandlerPreferencePickerListView.mediaHandlerName = mediaHandlerName mediahandlerPreferencePickerListView.mediaHandlerName = mediaHandlerName
mediahandlerPreferencePickerListView.model = MediaHandlerAdapter.getMediaHandlerPreferencesModel(pluginId, mediaHandlerName) mediahandlerPreferencePickerListView.model = PluginAdapter.getPluginPreferencesModel(pluginId, mediaHandlerName)
stack.currentIndex = 1 stack.currentIndex = 1
} }
} }
@@ -204,20 +204,24 @@ Popup {
property string pluginId: "" property string pluginId: ""
property string mediaHandlerName: "" property string mediaHandlerName: ""
model: MediaHandlerAdapter.getMediaHandlerPreferencesModel(pluginId, mediaHandlerName) model: PluginAdapter.getPluginPreferencesModel(pluginId, mediaHandlerName)
clip: true clip: true
delegate: PreferenceItemDelegate { delegate: PreferenceItemDelegate {
id: mediaHandlerPreferenceDelegate id: mediaHandlerPreferenceDelegate
width: mediahandlerPreferencePickerListView.width width: mediahandlerPreferencePickerListView.width
height: 50 height: childrenRect.height
preferenceName: PreferenceName preferenceName: PreferenceName
preferenceSummary: PreferenceSummary preferenceSummary: PreferenceSummary
preferenceType: PreferenceType preferenceType: PreferenceType
preferenceCurrentValue: PreferenceCurrentValue preferenceCurrentValue: PreferenceCurrentValue
pluginId: PluginId pluginId: PluginId
currentPath: CurrentPath
preferenceKey : PreferenceKey
fileFilters: FileFilters
isImage: IsImage
pluginListPreferenceModel: PluginListPreferenceModel{ pluginListPreferenceModel: PluginListPreferenceModel{
id: pluginListPreferenceModel id: pluginListPreferenceModel
preferenceKey : PreferenceKey preferenceKey : PreferenceKey
@@ -227,13 +231,9 @@ Popup {
onClicked: mediahandlerPreferencePickerListView.currentIndex = index onClicked: mediahandlerPreferencePickerListView.currentIndex = index
onBtnPreferenceClicked: { onBtnPreferenceClicked: {
ClientWrapper.pluginModel.setPluginPreference(pluginListPreferenceModel.pluginId, ClientWrapper.pluginModel.setPluginPreference(pluginId, preferenceKey, preferenceNewValue)
pluginListPreferenceModel.preferenceKey, mediahandlerPreferencePickerListView.model = PluginAdapter.getPluginPreferencesModel(pluginId, mediahandlerPreferencePickerListView.mediaHandlerName)
pluginListPreferenceModel.preferenceNewValue)
mediahandlerPreferencePickerListView.model = MediaHandlerAdapter.getMediaHandlerPreferencesModel(pluginId, mediahandlerPreferencePickerListView.mediaHandlerName)
} }
onPreferenceAdded: mediahandlerPreferencePickerListView.model = MediaHandlerAdapter.getMediaHandlerPreferencesModel(pluginId, mediahandlerPreferencePickerListView.mediaHandlerName)
} }
ScrollIndicator.vertical: ScrollIndicator {} ScrollIndicator.vertical: ScrollIndicator {}
@@ -246,7 +246,7 @@ Popup {
onAboutToShow: { onAboutToShow: {
// Reset the model on each show. // Reset the model on each show.
mediahandlerPickerListView.model = MediaHandlerAdapter.getMediaHandlerSelectableModel() mediahandlerPickerListView.model = PluginAdapter.getMediaHandlerSelectableModel()
} }
background: Rectangle { background: Rectangle {

View File

@@ -1,61 +0,0 @@
/**
* Copyright (C) 2020 by Savoir-faire Linux
* Author: Aline Gondim Santos <aline.gondimsantos@savoirfairelinux.com>
*
* 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 "mediahandleradapter.h"
#include "lrcinstance.h"
MediaHandlerAdapter::MediaHandlerAdapter(QObject* parent)
: QmlAdapterBase(parent)
{}
QVariant
MediaHandlerAdapter::getMediaHandlerSelectableModel()
{
/*
* Called from qml every time contact picker refreshes.
*/
mediaHandlerListModel_.reset(new MediaHandlerItemListModel(this));
return QVariant::fromValue(mediaHandlerListModel_.get());
}
QVariant
MediaHandlerAdapter::getMediaHandlerPreferencesModel(QString pluginId, QString mediaHandlerName)
{
/*
* Called from qml every time contact picker refreshes.
*/
mediaHandlerPreferenceItemListModel_.reset(new PreferenceItemListModel(this));
mediaHandlerPreferenceItemListModel_->setMediaHandlerName(mediaHandlerName);
mediaHandlerPreferenceItemListModel_->setPluginId(pluginId);
return QVariant::fromValue(mediaHandlerPreferenceItemListModel_.get());
}
QVariant
MediaHandlerAdapter::getMediaHandlerPreferencesSelectableModel(QString pluginId)
{
/*
* Called from qml every time contact picker refreshes.
*/
mediaHandlerListPreferenceModel_.reset(new MediaHandlerListPreferenceModel(this));
mediaHandlerListPreferenceModel_->setPluginId(pluginId);
return QVariant::fromValue(mediaHandlerListPreferenceModel_.get());
}

View File

@@ -1,154 +0,0 @@
/**
* Copyright (C) 2019-2020 by Savoir-faire Linux
* Author: Aline Gondim Santos <aline.gondimsantos@savoirfairelinux.com>
*
* 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 "mediahandlerlistpreferencemodel.h"
#include <regex>
MediaHandlerListPreferenceModel::MediaHandlerListPreferenceModel(QObject* parent)
: QAbstractListModel(parent)
{}
MediaHandlerListPreferenceModel::~MediaHandlerListPreferenceModel() {}
void
MediaHandlerListPreferenceModel::populateLists()
{
preferenceValuesList_.clear();
preferenceList_.clear();
const auto preferences = LRCInstance::pluginModel().getPluginPreferences(pluginId_);
for (const auto& preference : preferences) {
if (preference["key"] == preferenceKey_) {
auto entries = preference["entries"];
auto entriesValues = preference["entryValues"];
std::string entry = entries.toStdString();
std::string entryValues = entriesValues.toStdString();
std::string delimiter = ",";
size_t pos = 0;
std::string token;
while ((pos = entry.find(delimiter)) != std::string::npos) {
preferenceList_.emplace_back(entry.substr(0, pos));
entry.erase(0, pos + delimiter.length());
}
preferenceList_.emplace_back(entry.substr(0, pos));
while ((pos = entryValues.find(delimiter)) != std::string::npos) {
preferenceValuesList_.emplace_back(entryValues.substr(0, pos));
entryValues.erase(0, pos + delimiter.length());
}
preferenceValuesList_.emplace_back(entryValues.substr(0, pos));
}
}
getCurrentSettingIndex();
}
int
MediaHandlerListPreferenceModel::rowCount(const QModelIndex& parent) const
{
if (!parent.isValid()) {
/// Count
return preferenceList_.size();
}
/// A valid QModelIndex returns 0 as no entry has sub-elements.
return 0;
}
int
MediaHandlerListPreferenceModel::columnCount(const QModelIndex& parent) const
{
Q_UNUSED(parent);
/// Only need one column.
return 1;
}
QVariant
MediaHandlerListPreferenceModel::data(const QModelIndex& index, int role) const
{
if (!index.isValid() || preferenceList_.size() <= index.row()) {
return QVariant();
}
switch (role) {
case Role::PreferenceValue:
return QVariant(QString::fromStdString(preferenceList_.at(index.row())));
case Role::PreferenceEntryValue:
return QVariant(QString::fromStdString(preferenceValuesList_.at(index.row())));
}
return QVariant();
}
QHash<int, QByteArray>
MediaHandlerListPreferenceModel::roleNames() const
{
QHash<int, QByteArray> roles;
roles[PreferenceValue] = "PreferenceValue";
roles[PreferenceEntryValue] = "PreferenceEntryValue";
return roles;
}
QModelIndex
MediaHandlerListPreferenceModel::index(int row, int column, const QModelIndex& parent) const
{
Q_UNUSED(parent);
if (column != 0) {
return QModelIndex();
}
if (row >= 0 && row < rowCount()) {
return createIndex(row, column);
}
return QModelIndex();
}
QModelIndex
MediaHandlerListPreferenceModel::parent(const QModelIndex& child) const
{
Q_UNUSED(child);
return QModelIndex();
}
Qt::ItemFlags
MediaHandlerListPreferenceModel::flags(const QModelIndex& index) const
{
auto flags = QAbstractItemModel::flags(index) | Qt::ItemNeverHasChildren | Qt::ItemIsSelectable;
if (!index.isValid()) {
return QAbstractItemModel::flags(index);
}
return flags;
}
void
MediaHandlerListPreferenceModel::reset()
{
beginResetModel();
endResetModel();
}
int
MediaHandlerListPreferenceModel::getCurrentSettingIndex()
{
auto resultList = match(index(0, 0), PreferenceEntryValue, preferenceCurrentValue());
int resultRowIndex = 0;
if (resultList.size() > 0) {
resultRowIndex = resultList[0].row();
}
return resultRowIndex;
}

View File

@@ -1,102 +0,0 @@
/**
* Copyright (C) 2020 by Savoir-faire Linux
* Author: Aline Gondim Santos <aline.gondimsantos@savoirfairelinux.com>
*
* 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/>.
*/
#pragma once
#include <QAbstractItemModel>
#include "api/pluginmodel.h"
#include "lrcinstance.h"
class MediaHandlerListPreferenceModel : public QAbstractListModel
{
Q_OBJECT
Q_PROPERTY(QString pluginId READ pluginId WRITE setPluginId)
Q_PROPERTY(QString preferenceKey READ preferenceKey WRITE setPreferenceKey)
Q_PROPERTY(QString preferenceNewValue READ preferenceNewValue WRITE setPreferenceNewValue)
Q_PROPERTY(int idx READ idx WRITE setIdx)
Q_PROPERTY(int optSize READ optSize)
public:
enum Role { PreferenceValue = Qt::UserRole + 1, PreferenceEntryValue };
Q_ENUM(Role)
explicit MediaHandlerListPreferenceModel(QObject* parent = 0);
~MediaHandlerListPreferenceModel();
/*
* QAbstractListModel override.
*/
int rowCount(const QModelIndex& parent = QModelIndex()) const override;
int columnCount(const QModelIndex& parent) const override;
QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override;
/*
* Override role name as access point in qml.
*/
QHash<int, QByteArray> roleNames() const override;
QModelIndex index(int row, int column = 0, const QModelIndex& parent = QModelIndex()) const;
QModelIndex parent(const QModelIndex& child) const;
Qt::ItemFlags flags(const QModelIndex& index) const;
/*
* This function is to reset the model when there's new account added.
*/
Q_INVOKABLE void reset();
/*
* This function is to get the current preference value
*/
Q_INVOKABLE int getCurrentSettingIndex();
Q_INVOKABLE void populateLists();
void setPreferenceNewValue(const QString preferenceNewValue)
{
preferenceNewValue_ = preferenceNewValue;
}
void setPreferenceKey(const QString preferenceKey) { preferenceKey_ = preferenceKey; }
void setPluginId(const QString pluginId)
{
pluginId_ = pluginId;
populateLists();
}
void setIdx(const int index) { idx_ = index; }
int idx() { return idx_; }
QString preferenceCurrentValue()
{
return LRCInstance::pluginModel().getPluginPreferencesValues(pluginId_)[preferenceKey_];
}
QString preferenceNewValue()
{
preferenceNewValue_ = QString::fromStdString(preferenceValuesList_[idx_]);
return preferenceNewValue_;
}
QString preferenceKey() { return preferenceKey_; }
QString pluginId() { return pluginId_; }
int optSize() { return preferenceValuesList_.size(); }
private:
QString pluginId_ = "";
QString preferenceKey_ = "";
QString preferenceNewValue_ = "";
std::vector<std::string> preferenceValuesList_;
std::vector<std::string> preferenceList_;
int idx_ = 0;
};

49
src/pluginadapter.cpp Normal file
View File

@@ -0,0 +1,49 @@
/*!
* Copyright (C) 2020 by Savoir-faire Linux
* Author: Aline Gondim Santos <aline.gondimsantos@savoirfairelinux.com>
*
* 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 "pluginadapter.h"
#include "lrcinstance.h"
PluginAdapter::PluginAdapter(QObject* parent)
: QmlAdapterBase(parent)
{}
QVariant
PluginAdapter::getMediaHandlerSelectableModel()
{
mediaHandlerListModel_.reset(new MediaHandlerItemListModel(this));
return QVariant::fromValue(mediaHandlerListModel_.get());
}
QVariant
PluginAdapter::getPluginSelectableModel()
{
pluginItemListModel_.reset(new PluginItemListModel(this));
return QVariant::fromValue(pluginItemListModel_.get());
}
QVariant
PluginAdapter::getPluginPreferencesModel(const QString& pluginId, const QString& mediaHandlerName)
{
preferenceItemListModel_.reset(new PreferenceItemListModel(this));
preferenceItemListModel_->setMediaHandlerName(mediaHandlerName);
preferenceItemListModel_->setPluginId(pluginId);
return QVariant::fromValue(preferenceItemListModel_.get());
}

View File

@@ -19,31 +19,32 @@
#pragma once #pragma once
#include "qmladapterbase.h" #include "qmladapterbase.h"
#include "pluginitemlistmodel.h"
#include "mediahandleritemlistmodel.h" #include "mediahandleritemlistmodel.h"
#include "mediahandlerlistpreferencemodel.h" #include "pluginlistpreferencemodel.h"
#include "preferenceitemlistmodel.h" #include "preferenceitemlistmodel.h"
#include <QObject> #include <QObject>
#include <QSortFilterProxyModel> #include <QSortFilterProxyModel>
#include <QString> #include <QString>
class MediaHandlerAdapter final : public QmlAdapterBase class PluginAdapter final : public QmlAdapterBase
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit MediaHandlerAdapter(QObject* parent = nullptr); explicit PluginAdapter(QObject* parent = nullptr);
~MediaHandlerAdapter() = default; ~PluginAdapter() = default;
protected: protected:
void safeInit() override {}; void safeInit() override {};
Q_INVOKABLE QVariant getMediaHandlerSelectableModel(); Q_INVOKABLE QVariant getMediaHandlerSelectableModel();
Q_INVOKABLE QVariant getMediaHandlerPreferencesModel(QString pluginId, QString mediaHandlerName); Q_INVOKABLE QVariant getPluginSelectableModel();
Q_INVOKABLE QVariant getMediaHandlerPreferencesSelectableModel(QString pluginId); Q_INVOKABLE QVariant getPluginPreferencesModel(const QString& pluginId,
const QString& mediaHandlerName = "");
private: private:
std::unique_ptr<MediaHandlerItemListModel> mediaHandlerListModel_; std::unique_ptr<MediaHandlerItemListModel> mediaHandlerListModel_;
std::unique_ptr<PreferenceItemListModel> mediaHandlerPreferenceItemListModel_; std::unique_ptr<PreferenceItemListModel> preferenceItemListModel_;
std::unique_ptr<MediaHandlerListPreferenceModel> mediaHandlerListPreferenceModel_; std::unique_ptr<PluginItemListModel> pluginItemListModel_;
}; };

View File

@@ -33,7 +33,9 @@ PluginListPreferenceModel::populateLists()
const auto preferences = LRCInstance::pluginModel().getPluginPreferences(pluginId_); const auto preferences = LRCInstance::pluginModel().getPluginPreferences(pluginId_);
for (const auto& preference : preferences) { for (const auto& preference : preferences) {
if (preference["key"] == preferenceKey_) { if (preference["key"] == preferenceKey_) {
preferenceList_ = preference["entries"].split(","); if (preference.find("entries") != preference.end()
&& preference.find("entryValues") != preference.end())
preferenceList_ = preference["entries"].split(",");
preferenceValuesList_ = preference["entryValues"].split(","); preferenceValuesList_ = preference["entryValues"].split(",");
break; break;
} }

View File

@@ -17,10 +17,11 @@
*/ */
#include "preferenceitemlistmodel.h" #include "preferenceitemlistmodel.h"
#include "utils.h"
#include <map> #include <map>
std::map<QString, int> mapType {{QString("List"), PreferenceItemListModel::Type::LIST}, std::map<QString, int> mapType {{QString("List"), PreferenceItemListModel::Type::LIST},
{QString("UserList"), PreferenceItemListModel::Type::USERLIST}}; {QString("Path"), PreferenceItemListModel::Type::PATH}};
PreferenceItemListModel::PreferenceItemListModel(QObject* parent) PreferenceItemListModel::PreferenceItemListModel(QObject* parent)
: QAbstractListModel(parent) : QAbstractListModel(parent)
@@ -55,14 +56,27 @@ PreferenceItemListModel::data(const QModelIndex& index, int role) const
} }
auto details = preferenceList_.at(index.row()); auto details = preferenceList_.at(index.row());
int type = Type::DEFAULT;
auto it = mapType.find(details["type"]);
if (it != mapType.end()) {
type = mapType[details["type"]];
}
QString preferenceCurrent = LRCInstance::pluginModel().getPluginPreferencesValues( QString preferenceCurrent = LRCInstance::pluginModel().getPluginPreferencesValues(
pluginId_)[details["key"]]; pluginId_)[details["key"]];
int type = Type::DEFAULT;
QString currentPath = "";
QStringList acceptedFiles = {};
bool checkImage = false;
auto it = mapType.find(details["type"]);
if (it != mapType.end()) {
type = mapType[details["type"]];
if (type == Type::PATH) {
currentPath = preferenceCurrent;
currentPath.truncate(preferenceCurrent.lastIndexOf("/"));
QStringList mimeTypeList = details["mimeType"].split(',');
for (auto& mimeType : mimeTypeList) {
QString fileExt = mimeType.mid(mimeType.lastIndexOf("/") + 1);
acceptedFiles.append((fileExt.toUpper() + " Files") + " (*." + fileExt + ")");
checkImage = UtilsAdapter().isImage(fileExt);
}
}
}
switch (role) { switch (role) {
case Role::PreferenceKey: case Role::PreferenceKey:
return QVariant(details["key"]); return QVariant(details["key"]);
@@ -76,6 +90,12 @@ PreferenceItemListModel::data(const QModelIndex& index, int role) const
return QVariant(pluginId_); return QVariant(pluginId_);
case Role::PreferenceCurrentValue: case Role::PreferenceCurrentValue:
return QVariant(preferenceCurrent); return QVariant(preferenceCurrent);
case Role::CurrentPath:
return QVariant(currentPath);
case Role::FileFilters:
return QVariant(acceptedFiles);
case Role::IsImage:
return QVariant(checkImage);
} }
return QVariant(); return QVariant();
} }
@@ -90,6 +110,9 @@ PreferenceItemListModel::roleNames() const
roles[PreferenceType] = "PreferenceType"; roles[PreferenceType] = "PreferenceType";
roles[PluginId] = "PluginId"; roles[PluginId] = "PluginId";
roles[PreferenceCurrentValue] = "PreferenceCurrentValue"; roles[PreferenceCurrentValue] = "PreferenceCurrentValue";
roles[CurrentPath] = "CurrentPath";
roles[FileFilters] = "FileFilters";
roles[IsImage] = "IsImage";
return roles; return roles;
} }
@@ -167,23 +190,10 @@ PreferenceItemListModel::preferencesCount()
} else { } else {
auto preferences = LRCInstance::pluginModel().getPluginPreferences(pluginId_); auto preferences = LRCInstance::pluginModel().getPluginPreferences(pluginId_);
for (auto& preference : preferences) { for (auto& preference : preferences) {
std::string scope = preference["scope"].toStdString(); QStringList scopeList = preference["scope"].split(",");
std::string delimiter = ","; if (scopeList.contains(mediaHandlerName_))
size_t pos = 0;
std::string token;
while ((pos = scope.find(delimiter)) != std::string::npos) {
token = scope.substr(0, pos);
if (token == mediaHandlerName_.toStdString()) {
preferenceList_.push_back(preference);
break;
}
scope.erase(0, pos + delimiter.length());
}
token = scope.substr(0, pos);
if (token == mediaHandlerName_.toStdString())
preferenceList_.push_back(preference); preferenceList_.push_back(preference);
} }
return preferenceList_.size(); return preferenceList_.size();
} }
} }

View File

@@ -38,12 +38,15 @@ public:
PreferenceSummary, PreferenceSummary,
PreferenceType, PreferenceType,
PluginId, PluginId,
PreferenceCurrentValue PreferenceCurrentValue,
CurrentPath,
FileFilters,
IsImage
}; };
typedef enum { typedef enum {
LIST, LIST,
USERLIST, PATH,
DEFAULT, DEFAULT,
} Type; } Type;

View File

@@ -32,9 +32,8 @@
#include "conversationsadapter.h" #include "conversationsadapter.h"
#include "deviceitemlistmodel.h" #include "deviceitemlistmodel.h"
#include "distantrenderer.h" #include "distantrenderer.h"
#include "mediahandleradapter.h" #include "pluginadapter.h"
#include "mediahandleritemlistmodel.h" #include "mediahandleritemlistmodel.h"
#include "mediahandlerlistpreferencemodel.h"
#include "messagesadapter.h" #include "messagesadapter.h"
#include "namedirectory.h" #include "namedirectory.h"
#include "preferenceitemlistmodel.h" #include "preferenceitemlistmodel.h"
@@ -117,7 +116,6 @@ void registerTypes()
QML_REGISTERTYPE(VideoFormatResolutionModel, 1, 0); QML_REGISTERTYPE(VideoFormatResolutionModel, 1, 0);
QML_REGISTERTYPE(VideoFormatFpsModel, 1, 0); QML_REGISTERTYPE(VideoFormatFpsModel, 1, 0);
QML_REGISTERTYPE(PluginListPreferenceModel, 1, 0); QML_REGISTERTYPE(PluginListPreferenceModel, 1, 0);
QML_REGISTERTYPE(MediaHandlerListPreferenceModel, 1, 0);
/* /*
* Register QQuickItem type. * Register QQuickItem type.
@@ -141,7 +139,7 @@ void registerTypes()
QML_REGISTERSINGLETONTYPE("net.jami.Models", ConversationsAdapter, 1, 0); QML_REGISTERSINGLETONTYPE("net.jami.Models", ConversationsAdapter, 1, 0);
QML_REGISTERSINGLETONTYPE("net.jami.Models", AvAdapter, 1, 0); QML_REGISTERSINGLETONTYPE("net.jami.Models", AvAdapter, 1, 0);
QML_REGISTERSINGLETONTYPE("net.jami.Models", ContactAdapter, 1, 0); QML_REGISTERSINGLETONTYPE("net.jami.Models", ContactAdapter, 1, 0);
QML_REGISTERSINGLETONTYPE("net.jami.Models", MediaHandlerAdapter, 1, 0); QML_REGISTERSINGLETONTYPE("net.jami.Models", PluginAdapter, 1, 0);
QML_REGISTERSINGLETONTYPE("net.jami.Models", ClientWrapper, 1, 0); QML_REGISTERSINGLETONTYPE("net.jami.Models", ClientWrapper, 1, 0);

View File

@@ -120,7 +120,7 @@ ItemDelegate {
} }
ToolTip.visible: hovered ToolTip.visible: hovered
ToolTip.text: qsTr("Show preferences") ToolTip.text: qsTr("Show/Hide preferences")
onClicked: btnPreferencesPluginClicked() onClicked: btnPreferencesPluginClicked()
} }

View File

@@ -32,12 +32,10 @@ Rectangle {
enum Type { enum Type {
LIST, LIST,
USERLIST, PATH,
DEFAULT DEFAULT
} }
signal updatePluginList
property string pluginName: "" property string pluginName: ""
property string pluginIcon: "" property string pluginIcon: ""
property string pluginId: "" property string pluginId: ""
@@ -45,14 +43,6 @@ Rectangle {
visible: false visible: false
function updatePreferenceListDisplayed(){
// settings
preferenceItemListModel.pluginId = pluginId
preferenceItemListModel.reset()
var size = 50 * preferenceItemListModel.preferencesCount
pluginPreferenceView.height = size
}
function resetPluginSlot(){ function resetPluginSlot(){
resetPluginMessageBox.open() resetPluginMessageBox.open()
} }
@@ -65,8 +55,7 @@ Rectangle {
} else { } else {
ClientWrapper.pluginModel.resetPluginPreferencesValues(pluginId) ClientWrapper.pluginModel.resetPluginPreferencesValues(pluginId)
} }
updatePluginList() pluginPreferenceView.model = PluginAdapter.getPluginPreferencesModel(pluginId)
updatePreferenceListDisplayed()
} }
function uninstallPluginSlot(){ function uninstallPluginSlot(){
@@ -75,7 +64,6 @@ Rectangle {
function uninstallPlugin(){ function uninstallPlugin(){
ClientWrapper.pluginModel.uninstallPlugin(pluginId) ClientWrapper.pluginModel.uninstallPlugin(pluginId)
updatePluginList()
} }
function setPreference(pluginId, preferenceKey, preferenceNewValue) function setPreference(pluginId, preferenceKey, preferenceNewValue)
@@ -115,10 +103,6 @@ Rectangle {
onAccepted: resetPlugin() onAccepted: resetPlugin()
} }
PreferenceItemListModel {
id: preferenceItemListModel
}
ColumnLayout { ColumnLayout {
anchors.left: root.left anchors.left: root.left
anchors.right: root.right anchors.right: root.right
@@ -195,19 +179,23 @@ Rectangle {
Layout.minimumHeight: 0 Layout.minimumHeight: 0
Layout.preferredHeight: childrenRect.height + 30 Layout.preferredHeight: childrenRect.height + 30
model: preferenceItemListModel model: PluginAdapter.getPluginPreferencesModel(pluginId)
delegate: PreferenceItemDelegate{ delegate: PreferenceItemDelegate{
id: preferenceItemDelegate id: preferenceItemDelegate
width: pluginPreferenceView.width width: pluginPreferenceView.width
height: 50 height: childrenRect.height
preferenceName: PreferenceName preferenceName: PreferenceName
preferenceSummary: PreferenceSummary preferenceSummary: PreferenceSummary
preferenceType: PreferenceType preferenceType: PreferenceType
preferenceCurrentValue: PreferenceCurrentValue preferenceCurrentValue: PreferenceCurrentValue
pluginId: PluginId pluginId: PluginId
currentPath: CurrentPath
preferenceKey: PreferenceKey
fileFilters: FileFilters
isImage: IsImage
pluginListPreferenceModel: PluginListPreferenceModel{ pluginListPreferenceModel: PluginListPreferenceModel{
id: pluginListPreferenceModel id: pluginListPreferenceModel
preferenceKey : PreferenceKey preferenceKey : PreferenceKey
@@ -218,12 +206,9 @@ Rectangle {
pluginPreferenceView.currentIndex = index pluginPreferenceView.currentIndex = index
} }
onBtnPreferenceClicked: { onBtnPreferenceClicked: {
setPreference(pluginListPreferenceModel.pluginId, setPreference(pluginId, preferenceKey, preferenceNewValue)
pluginListPreferenceModel.preferenceKey, pluginPreferenceView.model = PluginAdapter.getPluginPreferencesModel(pluginId)
pluginListPreferenceModel.preferenceNewValue)
updatePreferenceListDisplayed()
} }
onPreferenceAdded: preferenceItemListModel.reset()
} }
} }
} }

View File

@@ -33,13 +33,6 @@ Rectangle {
visible: false visible: false
function updatePluginListDisplayed() {
// settings
pluginItemListModel.reset()
var size = 50 * pluginItemListModel.pluginsCount
pluginListView.height = size + 15
}
function openPluginFileSlot(){ function openPluginFileSlot(){
pluginPathDialog.open() pluginPathDialog.open()
} }
@@ -52,7 +45,6 @@ Rectangle {
loaded = ClientWrapper.pluginModel.loadPlugin(pluginId) loaded = ClientWrapper.pluginModel.loadPlugin(pluginId)
if(pluginListPreferencesView.pluginId === pluginId) if(pluginListPreferencesView.pluginId === pluginId)
pluginListPreferencesView.isLoaded = loaded pluginListPreferencesView.isLoaded = loaded
updatePluginListDisplayed()
} }
function openPreferencesPluginSlot(pluginName, pluginIcon, pluginId, isLoaded){ function openPreferencesPluginSlot(pluginName, pluginIcon, pluginId, isLoaded){
@@ -67,13 +59,11 @@ Rectangle {
pluginListPreferencesView.pluginId = pluginId pluginListPreferencesView.pluginId = pluginId
pluginListPreferencesView.isLoaded = isLoaded pluginListPreferencesView.isLoaded = isLoaded
} }
pluginListPreferencesView.updatePreferenceListDisplayed()
} }
function hidePreferences(){ function hidePreferences(){
pluginListPreferencesView.pluginId = "" pluginListPreferencesView.pluginId = ""
pluginListPreferencesView.visible = false pluginListPreferencesView.visible = false
pluginListPreferencesView.updatePreferenceListDisplayed()
} }
JamiFileDialog { JamiFileDialog {
@@ -97,7 +87,6 @@ Rectangle {
onAccepted: { onAccepted: {
var url = ClientWrapper.utilsAdaptor.getAbsPath(file.toString()) var url = ClientWrapper.utilsAdaptor.getAbsPath(file.toString())
ClientWrapper.pluginModel.installPlugin(url, true) ClientWrapper.pluginModel.installPlugin(url, true)
updatePluginListDisplayed()
} }
} }
@@ -122,8 +111,8 @@ Rectangle {
id: installButton id: installButton
Layout.alignment: Qt.AlignCenter Layout.alignment: Qt.AlignCenter
Layout.preferredWidth: preferredWidth Layout.preferredWidth: JamiTheme.preferredFieldWidth
Layout.preferredHeight: preferredHeight Layout.preferredHeight: JamiTheme.preferredFieldHeight
color: JamiTheme.buttonTintedBlack color: JamiTheme.buttonTintedBlack
hoveredColor: JamiTheme.buttonTintedBlackHovered hoveredColor: JamiTheme.buttonTintedBlackHovered
@@ -149,9 +138,7 @@ Rectangle {
Layout.minimumHeight: 0 Layout.minimumHeight: 0
Layout.preferredHeight: childrenRect.height Layout.preferredHeight: childrenRect.height
model: PluginItemListModel{ model: PluginAdapter.getPluginSelectableModel()
id: pluginItemListModel
}
delegate: PluginItemDelegate{ delegate: PluginItemDelegate{
id: pluginItemDelegate id: pluginItemDelegate

View File

@@ -33,9 +33,6 @@ Rectangle {
// settings // settings
enabledplugin.checked = ClientWrapper.pluginModel.getPluginsEnabled() enabledplugin.checked = ClientWrapper.pluginModel.getPluginsEnabled()
pluginListSettingsView.visible = enabledplugin.checked pluginListSettingsView.visible = enabledplugin.checked
if (pluginListSettingsView.visible) {
pluginListSettingsView.updatePluginListDisplayed()
}
} }
function slotSetPluginEnabled(state){ function slotSetPluginEnabled(state){
@@ -114,9 +111,7 @@ Rectangle {
slotSetPluginEnabled(checked) slotSetPluginEnabled(checked)
pluginListSettingsView.visible = checked pluginListSettingsView.visible = checked
if (pluginListSettingsView.visible) { if (!pluginListSettingsView.visible) {
pluginListSettingsView.updatePluginListDisplayed()
} else {
ClientWrapper.pluginModel.toggleCallMediaHandler("", true) ClientWrapper.pluginModel.toggleCallMediaHandler("", true)
pluginListSettingsView.hidePreferences() pluginListSettingsView.hidePreferences()
} }
@@ -144,10 +139,6 @@ Rectangle {
Layout.rightMargin: 16 Layout.rightMargin: 16
Layout.minimumHeight: 0 Layout.minimumHeight: 0
Layout.preferredHeight: childrenRect.height Layout.preferredHeight: childrenRect.height
onUpdatePluginList:{
pluginListSettingsView.updatePluginListDisplayed()
}
} }
} }
} }

View File

@@ -55,7 +55,7 @@
#include <QtConcurrent/QtConcurrent> #include <QtConcurrent/QtConcurrent>
bool bool
Utils::CreateStartupLink(const std::wstring &wstrAppName) Utils::CreateStartupLink(const std::wstring& wstrAppName)
{ {
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
TCHAR szPath[MAX_PATH]; TCHAR szPath[MAX_PATH];
@@ -80,19 +80,19 @@ Utils::CreateLink(LPCWSTR lpszPathObj, LPCWSTR lpszPathLink)
{ {
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
HRESULT hres; HRESULT hres;
IShellLink *psl; IShellLink* psl;
hres = CoCreateInstance(CLSID_ShellLink, hres = CoCreateInstance(CLSID_ShellLink,
NULL, NULL,
CLSCTX_INPROC_SERVER, CLSCTX_INPROC_SERVER,
IID_IShellLink, IID_IShellLink,
(LPVOID *) &psl); (LPVOID*) &psl);
if (SUCCEEDED(hres)) { if (SUCCEEDED(hres)) {
IPersistFile *ppf; IPersistFile* ppf;
psl->SetPath(lpszPathObj); psl->SetPath(lpszPathObj);
psl->SetArguments(TEXT("--minimized")); psl->SetArguments(TEXT("--minimized"));
hres = psl->QueryInterface(IID_IPersistFile, (LPVOID *) &ppf); hres = psl->QueryInterface(IID_IPersistFile, (LPVOID*) &ppf);
if (SUCCEEDED(hres)) { if (SUCCEEDED(hres)) {
hres = ppf->Save(lpszPathLink, TRUE); hres = ppf->Save(lpszPathLink, TRUE);
ppf->Release(); ppf->Release();
@@ -108,7 +108,7 @@ Utils::CreateLink(LPCWSTR lpszPathObj, LPCWSTR lpszPathLink)
} }
void void
Utils::DeleteStartupLink(const std::wstring &wstrAppName) Utils::DeleteStartupLink(const std::wstring& wstrAppName)
{ {
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
TCHAR startupPath[MAX_PATH]; TCHAR startupPath[MAX_PATH];
@@ -122,7 +122,7 @@ Utils::DeleteStartupLink(const std::wstring &wstrAppName)
} }
bool bool
Utils::CheckStartupLink(const std::wstring &wstrAppName) Utils::CheckStartupLink(const std::wstring& wstrAppName)
{ {
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
TCHAR startupPath[MAX_PATH]; TCHAR startupPath[MAX_PATH];
@@ -136,8 +136,8 @@ Utils::CheckStartupLink(const std::wstring &wstrAppName)
#endif #endif
} }
const char * const char*
Utils::WinGetEnv(const char *name) Utils::WinGetEnv(const char* name)
{ {
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
const DWORD buffSize = 65535; const DWORD buffSize = 65535;
@@ -184,8 +184,10 @@ Utils::removeOldVersions()
qDebug() << "Found startup link for Ring. Removing it and killing Ring.exe."; qDebug() << "Found startup link for Ring. Removing it and killing Ring.exe.";
Utils::DeleteStartupLink(TEXT("Ring")); Utils::DeleteStartupLink(TEXT("Ring"));
QProcess process; QProcess process;
process.start("taskkill", QStringList() process.start("taskkill",
<< "/im" << "Ring.exe" << "/f"); QStringList() << "/im"
<< "Ring.exe"
<< "/f");
process.waitForFinished(); process.waitForFinished();
} }
@@ -213,7 +215,7 @@ Utils::GenGUID()
{ {
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
GUID gidReference; GUID gidReference;
wchar_t *str; wchar_t* str;
HRESULT hCreateGuid = CoCreateGuid(&gidReference); HRESULT hCreateGuid = CoCreateGuid(&gidReference);
if (hCreateGuid == S_OK) { if (hCreateGuid == S_OK) {
StringFromCLSID(gidReference, &str); StringFromCLSID(gidReference, &str);
@@ -245,7 +247,7 @@ Utils::GetISODate()
} }
void void
Utils::InvokeMailto(const QString &subject, const QString &body, const QString &attachement) Utils::InvokeMailto(const QString& subject, const QString& body, const QString& attachement)
{ {
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
HKEY hKey; HKEY hKey;
@@ -263,7 +265,7 @@ Utils::InvokeMailto(const QString &subject, const QString &body, const QString &
} }
QString QString
Utils::getContactImageString(const QString &accountId, const QString &uid) Utils::getContactImageString(const QString& accountId, const QString& uid)
{ {
return QString::fromLatin1( return QString::fromLatin1(
Utils::QImageToByteArray( Utils::QImageToByteArray(
@@ -298,7 +300,7 @@ Utils::getCirclePhoto(const QImage original, int sizePhoto)
} }
void void
Utils::setStackWidget(QStackedWidget *stack, QWidget *widget) Utils::setStackWidget(QStackedWidget* stack, QWidget* widget)
{ {
if (stack->indexOf(widget) != -1 && stack->currentWidget() != widget) { if (stack->indexOf(widget) != -1 && stack->currentWidget() != widget) {
stack->setCurrentWidget(widget); stack->setCurrentWidget(widget);
@@ -306,10 +308,10 @@ Utils::setStackWidget(QStackedWidget *stack, QWidget *widget)
} }
void void
Utils::showSystemNotification(QWidget *widget, Utils::showSystemNotification(QWidget* widget,
const QString &message, const QString& message,
long delay, long delay,
const QString &triggeredAccountId) const QString& triggeredAccountId)
{ {
if (!AppSettingsManager::getValue(Settings::Key::EnableNotifications).toBool()) { if (!AppSettingsManager::getValue(Settings::Key::EnableNotifications).toBool()) {
qWarning() << "Notifications are disabled"; qWarning() << "Notifications are disabled";
@@ -321,11 +323,11 @@ Utils::showSystemNotification(QWidget *widget,
} }
void void
Utils::showSystemNotification(QWidget *widget, Utils::showSystemNotification(QWidget* widget,
const QString &sender, const QString& sender,
const QString &message, const QString& message,
long delay, long delay,
const QString &triggeredAccountId) const QString& triggeredAccountId)
{ {
if (!AppSettingsManager::getValue(Settings::Key::EnableNotifications).toBool()) { if (!AppSettingsManager::getValue(Settings::Key::EnableNotifications).toBool()) {
qWarning() << "Notifications are disabled"; qWarning() << "Notifications are disabled";
@@ -337,14 +339,14 @@ Utils::showSystemNotification(QWidget *widget,
} }
QSize QSize
Utils::getRealSize(QScreen *screen) Utils::getRealSize(QScreen* screen)
{ {
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
DEVMODE dmThisScreen; DEVMODE dmThisScreen;
ZeroMemory(&dmThisScreen, sizeof(dmThisScreen)); ZeroMemory(&dmThisScreen, sizeof(dmThisScreen));
EnumDisplaySettings((const wchar_t *) screen->name().utf16(), EnumDisplaySettings((const wchar_t*) screen->name().utf16(),
ENUM_CURRENT_SETTINGS, ENUM_CURRENT_SETTINGS,
(DEVMODE *) &dmThisScreen); (DEVMODE*) &dmThisScreen);
return QSize(dmThisScreen.dmPelsWidth, dmThisScreen.dmPelsHeight); return QSize(dmThisScreen.dmPelsWidth, dmThisScreen.dmPelsHeight);
#else #else
return {}; return {};
@@ -352,7 +354,7 @@ Utils::getRealSize(QScreen *screen)
} }
void void
Utils::forceDeleteAsync(const QString &path) Utils::forceDeleteAsync(const QString& path)
{ {
/* /*
* Keep deleting file until the process holding it let go, * Keep deleting file until the process holding it let go,
@@ -362,7 +364,7 @@ Utils::forceDeleteAsync(const QString &path)
QFile file(path); QFile file(path);
if (!QFile::exists(path)) if (!QFile::exists(path))
return; return;
int retries{0}; int retries {0};
while (!file.remove() && retries < 5) { while (!file.remove() && retries < 5) {
qDebug().noquote() << "\n" << file.errorString() << "\n"; qDebug().noquote() << "\n" << file.errorString() << "\n";
QThread::msleep(10); QThread::msleep(10);
@@ -371,7 +373,7 @@ Utils::forceDeleteAsync(const QString &path)
}); });
} }
UtilsAdapter & UtilsAdapter&
UtilsAdapter::instance() UtilsAdapter::instance()
{ {
static auto instance = new UtilsAdapter; static auto instance = new UtilsAdapter;
@@ -439,21 +441,21 @@ Utils::cleanUpdateFiles()
*/ */
QString dir = QString(Utils::WinGetEnv("TEMP")); QString dir = QString(Utils::WinGetEnv("TEMP"));
QDir log_dir(dir, {"jami*.log"}); QDir log_dir(dir, {"jami*.log"});
for (const QString &filename : log_dir.entryList()) { for (const QString& filename : log_dir.entryList()) {
log_dir.remove(filename); log_dir.remove(filename);
} }
QDir msi_dir(dir, {"jami*.msi"}); QDir msi_dir(dir, {"jami*.msi"});
for (const QString &filename : msi_dir.entryList()) { for (const QString& filename : msi_dir.entryList()) {
msi_dir.remove(filename); msi_dir.remove(filename);
} }
QDir version_dir(dir, {"version"}); QDir version_dir(dir, {"version"});
for (const QString &filename : version_dir.entryList()) { for (const QString& filename : version_dir.entryList()) {
version_dir.remove(filename); version_dir.remove(filename);
} }
} }
void void
Utils::checkForUpdates(bool withUI, QWidget *parent) Utils::checkForUpdates(bool withUI, QWidget* parent)
{ {
Q_UNUSED(withUI) Q_UNUSED(withUI)
Q_UNUSED(parent) Q_UNUSED(parent)
@@ -463,7 +465,7 @@ Utils::checkForUpdates(bool withUI, QWidget *parent)
} }
void void
Utils::applyUpdates(bool updateToBeta, QWidget *parent) Utils::applyUpdates(bool updateToBeta, QWidget* parent)
{ {
Q_UNUSED(updateToBeta) Q_UNUSED(updateToBeta)
Q_UNUSED(parent) Q_UNUSED(parent)
@@ -473,7 +475,7 @@ Utils::applyUpdates(bool updateToBeta, QWidget *parent)
} }
inline QString inline QString
removeEndlines(const QString &str) removeEndlines(const QString& str)
{ {
QString trimmed(str); QString trimmed(str);
trimmed.remove(QChar('\n')); trimmed.remove(QChar('\n'));
@@ -482,8 +484,8 @@ removeEndlines(const QString &str)
} }
QString QString
Utils::bestIdForConversation(const lrc::api::conversation::Info &conv, Utils::bestIdForConversation(const lrc::api::conversation::Info& conv,
const lrc::api::ConversationModel &model) const lrc::api::ConversationModel& model)
{ {
auto contact = model.owner.contactModel->getContact(conv.participants[0]); auto contact = model.owner.contactModel->getContact(conv.participants[0]);
if (!contact.registeredName.isEmpty()) { if (!contact.registeredName.isEmpty()) {
@@ -493,7 +495,7 @@ Utils::bestIdForConversation(const lrc::api::conversation::Info &conv,
} }
QString QString
Utils::bestIdForAccount(const lrc::api::account::Info &account) Utils::bestIdForAccount(const lrc::api::account::Info& account)
{ {
if (!account.registeredName.isEmpty()) { if (!account.registeredName.isEmpty()) {
return removeEndlines(account.registeredName); return removeEndlines(account.registeredName);
@@ -502,7 +504,7 @@ Utils::bestIdForAccount(const lrc::api::account::Info &account)
} }
QString QString
Utils::bestNameForAccount(const lrc::api::account::Info &account) Utils::bestNameForAccount(const lrc::api::account::Info& account)
{ {
if (account.profileInfo.alias.isEmpty()) { if (account.profileInfo.alias.isEmpty()) {
return bestIdForAccount(account); return bestIdForAccount(account);
@@ -511,7 +513,7 @@ Utils::bestNameForAccount(const lrc::api::account::Info &account)
} }
QString QString
Utils::bestIdForContact(const lrc::api::contact::Info &contact) Utils::bestIdForContact(const lrc::api::contact::Info& contact)
{ {
if (!contact.registeredName.isEmpty()) { if (!contact.registeredName.isEmpty()) {
return removeEndlines(contact.registeredName); return removeEndlines(contact.registeredName);
@@ -520,7 +522,7 @@ Utils::bestIdForContact(const lrc::api::contact::Info &contact)
} }
QString QString
Utils::bestNameForContact(const lrc::api::contact::Info &contact) Utils::bestNameForContact(const lrc::api::contact::Info& contact)
{ {
auto alias = removeEndlines(contact.profileInfo.alias); auto alias = removeEndlines(contact.profileInfo.alias);
if (alias.length() == 0) { if (alias.length() == 0) {
@@ -530,8 +532,8 @@ Utils::bestNameForContact(const lrc::api::contact::Info &contact)
} }
QString QString
Utils::bestNameForConversation(const lrc::api::conversation::Info &conv, Utils::bestNameForConversation(const lrc::api::conversation::Info& conv,
const lrc::api::ConversationModel &model) const lrc::api::ConversationModel& model)
{ {
try { try {
auto contact = model.owner.contactModel->getContact(conv.participants[0]); auto contact = model.owner.contactModel->getContact(conv.participants[0]);
@@ -549,7 +551,7 @@ Utils::bestNameForConversation(const lrc::api::conversation::Info &conv,
* Returns empty string if only infoHash is available, second best identifier otherwise. * Returns empty string if only infoHash is available, second best identifier otherwise.
*/ */
QString QString
Utils::secondBestNameForAccount(const lrc::api::account::Info &account) Utils::secondBestNameForAccount(const lrc::api::account::Info& account)
{ {
auto alias = removeEndlines(account.profileInfo.alias); auto alias = removeEndlines(account.profileInfo.alias);
auto registeredName = removeEndlines(account.registeredName); auto registeredName = removeEndlines(account.registeredName);
@@ -580,8 +582,8 @@ Utils::secondBestNameForAccount(const lrc::api::account::Info &account)
} }
lrc::api::profile::Type lrc::api::profile::Type
Utils::profileType(const lrc::api::conversation::Info &conv, Utils::profileType(const lrc::api::conversation::Info& conv,
const lrc::api::ConversationModel &model) const lrc::api::ConversationModel& model)
{ {
try { try {
auto contact = model.owner.contactModel->getContact(conv.participants[0]); auto contact = model.owner.contactModel->getContact(conv.participants[0]);
@@ -592,7 +594,7 @@ Utils::profileType(const lrc::api::conversation::Info &conv,
} }
std::string std::string
Utils::formatTimeString(const std::time_t &timestamp) Utils::formatTimeString(const std::time_t& timestamp)
{ {
std::time_t now = std::time(nullptr); std::time_t now = std::time(nullptr);
char interactionDay[64]; char interactionDay[64];
@@ -609,14 +611,14 @@ Utils::formatTimeString(const std::time_t &timestamp)
} }
bool bool
Utils::isInteractionGenerated(const lrc::api::interaction::Type &type) Utils::isInteractionGenerated(const lrc::api::interaction::Type& type)
{ {
return type == lrc::api::interaction::Type::CALL return type == lrc::api::interaction::Type::CALL
|| type == lrc::api::interaction::Type::CONTACT; || type == lrc::api::interaction::Type::CONTACT;
} }
bool bool
Utils::isContactValid(const QString &contactUid, const lrc::api::ConversationModel &model) Utils::isContactValid(const QString& contactUid, const lrc::api::ConversationModel& model)
{ {
const auto contact = model.owner.contactModel->getContact(contactUid); const auto contact = model.owner.contactModel->getContact(contactUid);
return (contact.profileInfo.type == lrc::api::profile::Type::PENDING return (contact.profileInfo.type == lrc::api::profile::Type::PENDING
@@ -627,7 +629,7 @@ Utils::isContactValid(const QString &contactUid, const lrc::api::ConversationMod
} }
bool bool
Utils::getReplyMessageBox(QWidget *widget, const QString &title, const QString &text) Utils::getReplyMessageBox(QWidget* widget, const QString& title, const QString& text)
{ {
if (QMessageBox::question(widget, title, text, QMessageBox::Yes | QMessageBox::No) if (QMessageBox::question(widget, title, text, QMessageBox::Yes | QMessageBox::No)
== QMessageBox::Yes) == QMessageBox::Yes)
@@ -636,8 +638,8 @@ Utils::getReplyMessageBox(QWidget *widget, const QString &title, const QString &
} }
QImage QImage
Utils::conversationPhoto(const QString &convUid, Utils::conversationPhoto(const QString& convUid,
const lrc::api::account::Info &accountInfo, const lrc::api::account::Info& accountInfo,
bool filtered) bool filtered)
{ {
auto* convModel = LRCInstance::getCurrentConversationModel(); auto* convModel = LRCInstance::getCurrentConversationModel();
@@ -651,7 +653,7 @@ Utils::conversationPhoto(const QString &convUid,
} }
QColor QColor
Utils::getAvatarColor(const QString &canonicalUri) Utils::getAvatarColor(const QString& canonicalUri)
{ {
if (canonicalUri.isEmpty()) { if (canonicalUri.isEmpty()) {
return JamiAvatarTheme::defaultAvatarColor_; return JamiAvatarTheme::defaultAvatarColor_;
@@ -667,10 +669,11 @@ Utils::getAvatarColor(const QString &canonicalUri)
/* Generate a QImage representing a dummy user avatar, when user doesn't provide it. /* 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. * 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. * The color of the letter is computed from the circle color to be visible whaterver be the circle
* color.
*/ */
QImage QImage
Utils::fallbackAvatar(const QSize size, const QString &canonicalUriStr, const QString &letterStr) Utils::fallbackAvatar(const QSize size, const QString& canonicalUriStr, const QString& letterStr)
{ {
/* /*
* We start with a transparent avatar. * We start with a transparent avatar.
@@ -740,7 +743,7 @@ Utils::fallbackAvatar(const QSize size, const QString &canonicalUriStr, const QS
} }
QImage QImage
Utils::fallbackAvatar(const QSize size, const std::string &alias, const std::string &uri) Utils::fallbackAvatar(const QSize size, const std::string& alias, const std::string& uri)
{ {
return fallbackAvatar(size, QString::fromStdString(uri), QString::fromStdString(alias)); return fallbackAvatar(size, QString::fromStdString(uri), QString::fromStdString(alias));
} }
@@ -756,7 +759,7 @@ Utils::QImageToByteArray(QImage image)
} }
QImage QImage
Utils::cropImage(const QImage &img) Utils::cropImage(const QImage& img)
{ {
QRect rect; QRect rect;
auto w = img.width(); auto w = img.width();
@@ -768,7 +771,7 @@ Utils::cropImage(const QImage &img)
} }
QPixmap QPixmap
Utils::pixmapFromSvg(const QString &svg_resource, const QSize &size) Utils::pixmapFromSvg(const QString& svg_resource, const QSize& size)
{ {
QSvgRenderer svgRenderer(svg_resource); QSvgRenderer svgRenderer(svg_resource);
QPixmap pixmap(size); QPixmap pixmap(size);
@@ -799,10 +802,10 @@ Utils::setupQRCode(QString ringID, int margin)
painter.setPen(QPen(Qt::black, 0.1, Qt::SolidLine, Qt::FlatCap, Qt::MiterJoin)); painter.setPen(QPen(Qt::black, 0.1, Qt::SolidLine, Qt::FlatCap, Qt::MiterJoin));
painter.setBrush(Qt::black); painter.setBrush(Qt::black);
painter.fillRect(QRect(0, 0, qrwidth, qrwidth), Qt::white); painter.fillRect(QRect(0, 0, qrwidth, qrwidth), Qt::white);
unsigned char *p; unsigned char* p;
p = rcode->data; p = rcode->data;
for (int y = 0; y < rcode->width; y++) { for (int y = 0; y < rcode->width; y++) {
unsigned char *row = (p + (y * rcode->width)); unsigned char* row = (p + (y * rcode->width));
for (int x = 0; x < rcode->width; x++) { for (int x = 0; x < rcode->width; x++) {
if (*(row + x) & 0x1) { if (*(row + x) & 0x1) {
painter.drawRect(margin + x, margin + y, 1, 1); painter.drawRect(margin + x, margin + y, 1, 1);
@@ -849,7 +852,7 @@ Utils::formattedTime(int duration)
} }
QByteArray QByteArray
Utils::QByteArrayFromFile(const QString &filename) Utils::QByteArrayFromFile(const QString& filename)
{ {
QFile file(filename); QFile file(filename);
if (file.open(QIODevice::ReadOnly)) { if (file.open(QIODevice::ReadOnly)) {
@@ -861,7 +864,7 @@ Utils::QByteArrayFromFile(const QString &filename)
} }
QPixmap QPixmap
Utils::generateTintedPixmap(const QString &filename, QColor color) Utils::generateTintedPixmap(const QString& filename, QColor color)
{ {
QPixmap px(filename); QPixmap px(filename);
QImage tmpImage = px.toImage(); QImage tmpImage = px.toImage();
@@ -875,7 +878,7 @@ Utils::generateTintedPixmap(const QString &filename, QColor color)
} }
QPixmap QPixmap
Utils::generateTintedPixmap(const QPixmap &pix, QColor color) Utils::generateTintedPixmap(const QPixmap& pix, QColor color)
{ {
QPixmap px = pix; QPixmap px = pix;
QImage tmpImage = px.toImage(); QImage tmpImage = px.toImage();
@@ -889,13 +892,13 @@ Utils::generateTintedPixmap(const QPixmap &pix, QColor color)
} }
QImage QImage
Utils::scaleAndFrame(const QImage photo, const QSize &size) Utils::scaleAndFrame(const QImage photo, const QSize& size)
{ {
return photo.scaled(size, Qt::KeepAspectRatio, Qt::SmoothTransformation); return photo.scaled(size, Qt::KeepAspectRatio, Qt::SmoothTransformation);
} }
QImage QImage
Utils::accountPhoto(const lrc::api::account::Info &accountInfo, const QSize &size) Utils::accountPhoto(const lrc::api::account::Info& accountInfo, const QSize& size)
{ {
QImage photo; QImage photo;
if (!accountInfo.profileInfo.avatar.isEmpty()) { if (!accountInfo.profileInfo.avatar.isEmpty()) {
@@ -935,14 +938,14 @@ Utils::humanFileSize(qint64 fileSize)
} }
const QString const QString
UtilsAdapter::getBestName(const QString &accountId, const QString &uid) UtilsAdapter::getBestName(const QString& accountId, const QString& uid)
{ {
auto* convModel = LRCInstance::getAccountInfo(accountId).conversationModel.get(); auto* convModel = LRCInstance::getAccountInfo(accountId).conversationModel.get();
return Utils::bestNameForConversation(convModel->getConversationForUID(uid), *convModel); return Utils::bestNameForConversation(convModel->getConversationForUID(uid), *convModel);
} }
const QString const QString
UtilsAdapter::getBestId(const QString &accountId, const QString &uid) UtilsAdapter::getBestId(const QString& accountId, const QString& uid)
{ {
auto* convModel = LRCInstance::getAccountInfo(accountId).conversationModel.get(); auto* convModel = LRCInstance::getAccountInfo(accountId).conversationModel.get();
return Utils::bestIdForConversation(convModel->getConversationForUID(uid), *convModel); return Utils::bestIdForConversation(convModel->getConversationForUID(uid), *convModel);
@@ -951,13 +954,13 @@ UtilsAdapter::getBestId(const QString &accountId, const QString &uid)
int int
UtilsAdapter::getTotalUnreadMessages() UtilsAdapter::getTotalUnreadMessages()
{ {
int totalUnreadMessages{0}; int totalUnreadMessages {0};
if (LRCInstance::getCurrentAccountInfo().profileInfo.type != lrc::api::profile::Type::SIP) { if (LRCInstance::getCurrentAccountInfo().profileInfo.type != lrc::api::profile::Type::SIP) {
auto* convModel = LRCInstance::getCurrentConversationModel(); auto* convModel = LRCInstance::getCurrentConversationModel();
auto ringConversations = convModel->getFilteredConversations(lrc::api::profile::Type::RING); auto ringConversations = convModel->getFilteredConversations(lrc::api::profile::Type::RING);
std::for_each(ringConversations.begin(), std::for_each(ringConversations.begin(),
ringConversations.end(), ringConversations.end(),
[&totalUnreadMessages](const auto &conversation) { [&totalUnreadMessages](const auto& conversation) {
totalUnreadMessages += conversation.unreadMessages; totalUnreadMessages += conversation.unreadMessages;
}); });
} }
@@ -967,24 +970,24 @@ UtilsAdapter::getTotalUnreadMessages()
int int
UtilsAdapter::getTotalPendingRequest() UtilsAdapter::getTotalPendingRequest()
{ {
auto &accountInfo = LRCInstance::getCurrentAccountInfo(); auto& accountInfo = LRCInstance::getCurrentAccountInfo();
return accountInfo.contactModel->pendingRequestCount(); return accountInfo.contactModel->pendingRequestCount();
} }
void void
UtilsAdapter::setConversationFilter(const QString &filter) UtilsAdapter::setConversationFilter(const QString& filter)
{ {
LRCInstance::getCurrentConversationModel()->setFilter(filter); LRCInstance::getCurrentConversationModel()->setFilter(filter);
} }
void void
UtilsAdapter::clearConversationHistory(const QString &accountId, const QString &uid) UtilsAdapter::clearConversationHistory(const QString& accountId, const QString& uid)
{ {
LRCInstance::getAccountInfo(accountId).conversationModel->clearHistory(uid); LRCInstance::getAccountInfo(accountId).conversationModel->clearHistory(uid);
} }
void void
UtilsAdapter::removeConversation(const QString &accountId, const QString &uid, bool banContact) UtilsAdapter::removeConversation(const QString& accountId, const QString& uid, bool banContact)
{ {
LRCInstance::getAccountInfo(accountId).conversationModel->removeConversation(uid, banContact); LRCInstance::getAccountInfo(accountId).conversationModel->removeConversation(uid, banContact);
} }
@@ -1020,9 +1023,9 @@ UtilsAdapter::getAccountListSize()
} }
void void
UtilsAdapter::setCurrentCall(const QString &accountId, const QString &convUid) UtilsAdapter::setCurrentCall(const QString& accountId, const QString& convUid)
{ {
auto &accInfo = LRCInstance::getAccountInfo(accountId); auto& accInfo = LRCInstance::getAccountInfo(accountId);
const auto convInfo = accInfo.conversationModel->getConversationForUID(convUid); const auto convInfo = accInfo.conversationModel->getConversationForUID(convUid);
accInfo.callModel->setCurrentCall(convInfo.callId); accInfo.callModel->setCurrentCall(convInfo.callId);
} }
@@ -1048,9 +1051,9 @@ UtilsAdapter::hasVideoCall()
} }
const QString const QString
UtilsAdapter::getCallId(const QString &accountId, const QString &convUid) UtilsAdapter::getCallId(const QString& accountId, const QString& convUid)
{ {
auto &accInfo = LRCInstance::getAccountInfo(accountId); auto& accInfo = LRCInstance::getAccountInfo(accountId);
const auto convInfo = accInfo.conversationModel->getConversationForUID(convUid); const auto convInfo = accInfo.conversationModel->getConversationForUID(convUid);
if (convInfo.uid.isEmpty()) { if (convInfo.uid.isEmpty()) {
@@ -1072,10 +1075,9 @@ UtilsAdapter::getCallStatusStr(int statusInt)
return lrc::api::call::to_string(status); return lrc::api::call::to_string(status);
} }
// returns true if name is valid registered name // returns true if name is valid registered name
bool bool
UtilsAdapter::validateRegNameForm(const QString &regName) UtilsAdapter::validateRegNameForm(const QString& regName)
{ {
QRegularExpression regExp(" "); QRegularExpression regExp(" ");
@@ -1111,3 +1113,11 @@ UtilsAdapter::checkShowPluginsButton()
return LRCInstance::pluginModel().getPluginsEnabled() return LRCInstance::pluginModel().getPluginsEnabled()
&& (LRCInstance::pluginModel().listLoadedPlugins().size() > 0); && (LRCInstance::pluginModel().listLoadedPlugins().size() > 0);
} }
bool
UtilsAdapter::isImage(const QString& fileExt) const
{
if (fileExt == "png" || fileExt == "jpg" || fileExt == "jpeg")
return true;
return false;
}

View File

@@ -49,7 +49,7 @@
#include <windows.h> #include <windows.h>
#undef ERROR #undef ERROR
#else #else
#define LPCWSTR char * #define LPCWSTR char*
#endif #endif
#include "api/account.h" #include "api/account.h"
@@ -57,8 +57,8 @@
#include "api/contactmodel.h" #include "api/contactmodel.h"
#include "api/conversationmodel.h" #include "api/conversationmodel.h"
static const QSize IMAGE_SIZE{128, 128}; static const QSize IMAGE_SIZE {128, 128};
static float CURRENT_SCALING_RATIO{1.0}; static float CURRENT_SCALING_RATIO {1.0};
#ifdef BETA #ifdef BETA
static constexpr bool isBeta = true; static constexpr bool isBeta = true;
@@ -71,30 +71,30 @@ namespace Utils {
/* /*
* System. * System.
*/ */
bool CreateStartupLink(const std::wstring &wstrAppName); bool CreateStartupLink(const std::wstring& wstrAppName);
void DeleteStartupLink(const std::wstring &wstrAppName); void DeleteStartupLink(const std::wstring& wstrAppName);
bool CreateLink(LPCWSTR lpszPathObj, LPCWSTR lpszPathLink); bool CreateLink(LPCWSTR lpszPathObj, LPCWSTR lpszPathLink);
bool CheckStartupLink(const std::wstring &wstrAppName); bool CheckStartupLink(const std::wstring& wstrAppName);
void removeOldVersions(); void removeOldVersions();
const char *WinGetEnv(const char *name); const char* WinGetEnv(const char* name);
QString GetRingtonePath(); QString GetRingtonePath();
QString GenGUID(); QString GenGUID();
QString GetISODate(); QString GetISODate();
void InvokeMailto(const QString &subject, void InvokeMailto(const QString& subject,
const QString &body, const QString& body,
const QString &attachement = QString()); const QString& attachement = QString());
void setStackWidget(QStackedWidget *stack, QWidget *widget); void setStackWidget(QStackedWidget* stack, QWidget* widget);
void showSystemNotification(QWidget *widget, void showSystemNotification(QWidget* widget,
const QString &message, const QString& message,
long delay = 5000, long delay = 5000,
const QString &triggeredAccountId = ""); const QString& triggeredAccountId = "");
void showSystemNotification(QWidget *widget, void showSystemNotification(QWidget* widget,
const QString &sender, const QString& sender,
const QString &message, const QString& message,
long delay = 5000, long delay = 5000,
const QString &triggeredAccountId = ""); const QString& triggeredAccountId = "");
QSize getRealSize(QScreen *screen); QSize getRealSize(QScreen* screen);
void forceDeleteAsync(const QString &path); void forceDeleteAsync(const QString& path);
QString getChangeLog(); QString getChangeLog();
QString getProjectCredits(); QString getProjectCredits();
float getCurrentScalingRatio(); float getCurrentScalingRatio();
@@ -104,56 +104,56 @@ void setCurrentScalingRatio(float ratio);
* Updates. * Updates.
*/ */
void cleanUpdateFiles(); void cleanUpdateFiles();
void checkForUpdates(bool withUI, QWidget *parent = nullptr); void checkForUpdates(bool withUI, QWidget* parent = nullptr);
void applyUpdates(bool updateToBeta, QWidget *parent = nullptr); void applyUpdates(bool updateToBeta, QWidget* parent = nullptr);
/* /*
* Names. * Names.
*/ */
QString bestIdForConversation(const lrc::api::conversation::Info &conv, QString bestIdForConversation(const lrc::api::conversation::Info& conv,
const lrc::api::ConversationModel &model); const lrc::api::ConversationModel& model);
QString bestIdForAccount(const lrc::api::account::Info &account); QString bestIdForAccount(const lrc::api::account::Info& account);
QString bestNameForAccount(const lrc::api::account::Info &account); QString bestNameForAccount(const lrc::api::account::Info& account);
QString bestIdForContact(const lrc::api::contact::Info &contact); QString bestIdForContact(const lrc::api::contact::Info& contact);
QString bestNameForContact(const lrc::api::contact::Info &contact); QString bestNameForContact(const lrc::api::contact::Info& contact);
QString bestNameForConversation(const lrc::api::conversation::Info &conv, QString bestNameForConversation(const lrc::api::conversation::Info& conv,
const lrc::api::ConversationModel &model); const lrc::api::ConversationModel& model);
/* /*
* Returns empty string if only infoHash is available. * Returns empty string if only infoHash is available.
*/ */
QString secondBestNameForAccount(const lrc::api::account::Info &account); QString secondBestNameForAccount(const lrc::api::account::Info& account);
lrc::api::profile::Type profileType(const lrc::api::conversation::Info &conv, lrc::api::profile::Type profileType(const lrc::api::conversation::Info& conv,
const lrc::api::ConversationModel &model); const lrc::api::ConversationModel& model);
/* /*
* Interactions. * Interactions.
*/ */
std::string formatTimeString(const std::time_t &timestamp); std::string formatTimeString(const std::time_t& timestamp);
bool isInteractionGenerated(const lrc::api::interaction::Type &interaction); bool isInteractionGenerated(const lrc::api::interaction::Type& interaction);
bool isContactValid(const QString &contactUid, const lrc::api::ConversationModel &model); bool isContactValid(const QString& contactUid, const lrc::api::ConversationModel& model);
bool getReplyMessageBox(QWidget *widget, const QString &title, const QString &text); bool getReplyMessageBox(QWidget* widget, const QString& title, const QString& text);
/* /*
* Image. * Image.
*/ */
QString getContactImageString(const QString &accountId, const QString &uid); QString getContactImageString(const QString& accountId, const QString& uid);
QImage getCirclePhoto(const QImage original, int sizePhoto); QImage getCirclePhoto(const QImage original, int sizePhoto);
QImage conversationPhoto(const QString &convUid, QImage conversationPhoto(const QString& convUid,
const lrc::api::account::Info &accountInfo, const lrc::api::account::Info& accountInfo,
bool filtered = false); bool filtered = false);
QColor getAvatarColor(const QString &canonicalUri); QColor getAvatarColor(const QString& canonicalUri);
QImage fallbackAvatar(const QSize size, QImage fallbackAvatar(const QSize size,
const QString &canonicalUriStr, const QString& canonicalUriStr,
const QString &letterStr = QString()); const QString& letterStr = QString());
QImage fallbackAvatar(const QSize size, const std::string &alias, const std::string &uri); QImage fallbackAvatar(const QSize size, const std::string& alias, const std::string& uri);
QByteArray QImageToByteArray(QImage image); QByteArray QImageToByteArray(QImage image);
QByteArray QByteArrayFromFile(const QString &filename); QByteArray QByteArrayFromFile(const QString& filename);
QPixmap generateTintedPixmap(const QString &filename, QColor color); QPixmap generateTintedPixmap(const QString& filename, QColor color);
QPixmap generateTintedPixmap(const QPixmap &pix, QColor color); QPixmap generateTintedPixmap(const QPixmap& pix, QColor color);
QImage scaleAndFrame(const QImage photo, const QSize &size = IMAGE_SIZE); QImage scaleAndFrame(const QImage photo, const QSize& size = IMAGE_SIZE);
QImage accountPhoto(const lrc::api::account::Info &accountInfo, const QSize &size = IMAGE_SIZE); QImage accountPhoto(const lrc::api::account::Info& accountInfo, const QSize& size = IMAGE_SIZE);
QImage cropImage(const QImage &img); QImage cropImage(const QImage& img);
QPixmap pixmapFromSvg(const QString &svg_resource, const QSize &size); QPixmap pixmapFromSvg(const QString& svg_resource, const QSize& size);
QImage setupQRCode(QString ringID, int margin); QImage setupQRCode(QString ringID, int margin);
/* /*
@@ -161,9 +161,9 @@ QImage setupQRCode(QString ringID, int margin);
*/ */
template<typename T> template<typename T>
void void
fillRoundRectPath(QPainter &painter, fillRoundRectPath(QPainter& painter,
const T &brushType, const T& brushType,
const QRect &rectToDraw, const QRect& rectToDraw,
qreal cornerRadius, qreal cornerRadius,
int xTransFormOffset = 0, int xTransFormOffset = 0,
int yTransFormOffset = 0) int yTransFormOffset = 0)
@@ -196,10 +196,10 @@ class OneShotDisconnectConnection : public QObject
Q_OBJECT Q_OBJECT
public: public:
explicit OneShotDisconnectConnection(const QObject *sender, explicit OneShotDisconnectConnection(const QObject* sender,
const char *signal, const char* signal,
QMetaObject::Connection *connection, QMetaObject::Connection* connection,
QObject *parent = nullptr) QObject* parent = nullptr)
: QObject(parent) : QObject(parent)
{ {
connection_ = connection; connection_ = connection;
@@ -223,8 +223,7 @@ public:
} }
public slots: public slots:
void void slotOneShotDisconnectConnection()
slotOneShotDisconnectConnection()
{ {
if (connection_) { if (connection_) {
QObject::disconnect(*connection_); QObject::disconnect(*connection_);
@@ -238,19 +237,19 @@ public slots:
} }
private: private:
QMetaObject::Connection *connection_; QMetaObject::Connection* connection_;
QMetaObject::Connection *disconnectConnection_; QMetaObject::Connection* disconnectConnection_;
}; };
template<typename Func1, typename Func2> template<typename Func1, typename Func2>
void void
oneShotConnect(const typename QtPrivate::FunctionPointer<Func1>::Object *sender, oneShotConnect(const typename QtPrivate::FunctionPointer<Func1>::Object* sender,
Func1 signal, Func1 signal,
Func2 slot) Func2 slot)
{ {
QMetaObject::Connection *const connection = new QMetaObject::Connection; QMetaObject::Connection* const connection = new QMetaObject::Connection;
*connection = QObject::connect(sender, signal, slot); *connection = QObject::connect(sender, signal, slot);
QMetaObject::Connection *const disconnectConnection = new QMetaObject::Connection; QMetaObject::Connection* const disconnectConnection = new QMetaObject::Connection;
*disconnectConnection = QObject::connect(sender, signal, [connection, disconnectConnection] { *disconnectConnection = QObject::connect(sender, signal, [connection, disconnectConnection] {
if (connection) { if (connection) {
QObject::disconnect(*connection); QObject::disconnect(*connection);
@@ -265,14 +264,14 @@ oneShotConnect(const typename QtPrivate::FunctionPointer<Func1>::Object *sender,
template<typename Func1, typename Func2> template<typename Func1, typename Func2>
void void
oneShotConnect(const typename QtPrivate::FunctionPointer<Func1>::Object *sender, oneShotConnect(const typename QtPrivate::FunctionPointer<Func1>::Object* sender,
Func1 signal, Func1 signal,
const typename QtPrivate::FunctionPointer<Func2>::Object *receiver, const typename QtPrivate::FunctionPointer<Func2>::Object* receiver,
Func2 slot) Func2 slot)
{ {
QMetaObject::Connection *const connection = new QMetaObject::Connection; QMetaObject::Connection* const connection = new QMetaObject::Connection;
*connection = QObject::connect(sender, signal, receiver, slot); *connection = QObject::connect(sender, signal, receiver, slot);
QMetaObject::Connection *const disconnectConnection = new QMetaObject::Connection; QMetaObject::Connection* const disconnectConnection = new QMetaObject::Connection;
*disconnectConnection = QObject::connect(sender, signal, [connection, disconnectConnection] { *disconnectConnection = QObject::connect(sender, signal, [connection, disconnectConnection] {
if (connection) { if (connection) {
QObject::disconnect(*connection); QObject::disconnect(*connection);
@@ -286,11 +285,11 @@ oneShotConnect(const typename QtPrivate::FunctionPointer<Func1>::Object *sender,
} }
inline void inline void
oneShotConnect(const QObject *sender, const char *signal, const QObject *receiver, const char *slot) oneShotConnect(const QObject* sender, const char* signal, const QObject* receiver, const char* slot)
{ {
QMetaObject::Connection *const connection = new QMetaObject::Connection; QMetaObject::Connection* const connection = new QMetaObject::Connection;
*connection = QObject::connect(sender, signal, receiver, slot); *connection = QObject::connect(sender, signal, receiver, slot);
OneShotDisconnectConnection *disconnectConnection = new OneShotDisconnectConnection(sender, OneShotDisconnectConnection* disconnectConnection = new OneShotDisconnectConnection(sender,
signal, signal,
connection); connection);
Q_UNUSED(disconnectConnection) Q_UNUSED(disconnectConnection)
@@ -299,33 +298,29 @@ oneShotConnect(const QObject *sender, const char *signal, const QObject *receive
template<class T> template<class T>
class Blocker class Blocker
{ {
T *blocked; T* blocked;
bool previous; bool previous;
public: public:
Blocker(T *blocked) Blocker(T* blocked)
: blocked(blocked) : blocked(blocked)
, previous(blocked->blockSignals(true)) , previous(blocked->blockSignals(true))
{} {}
~Blocker() { blocked->blockSignals(previous); } ~Blocker() { blocked->blockSignals(previous); }
T * T* operator->() { return blocked; }
operator->()
{
return blocked;
}
}; };
template<class T> template<class T>
inline Blocker<T> inline Blocker<T>
whileBlocking(T *blocked) whileBlocking(T* blocked)
{ {
return Blocker<T>(blocked); return Blocker<T>(blocked);
} }
template<typename T> template<typename T>
void void
setElidedText(T *object, setElidedText(T* object,
const QString &text, const QString& text,
Qt::TextElideMode mode = Qt::ElideMiddle, Qt::TextElideMode mode = Qt::ElideMiddle,
int padding = 32) int padding = 32)
{ {
@@ -355,48 +350,30 @@ class UtilsAdapter : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit UtilsAdapter(QObject *parent = nullptr) explicit UtilsAdapter(QObject* parent = nullptr)
: QObject(parent) : QObject(parent)
{ {
clipboard_ = QApplication::clipboard(); clipboard_ = QApplication::clipboard();
} }
~UtilsAdapter() {} ~UtilsAdapter() {}
///Singleton /// Singleton
static UtilsAdapter &instance(); static UtilsAdapter& instance();
Q_INVOKABLE const QString Q_INVOKABLE const QString getChangeLog() { return Utils::getChangeLog(); }
getChangeLog()
{
return Utils::getChangeLog();
}
Q_INVOKABLE const QString Q_INVOKABLE const QString getProjectCredits() { return Utils::getProjectCredits(); }
getProjectCredits()
{
return Utils::getProjectCredits();
}
Q_INVOKABLE const QString Q_INVOKABLE const QString getVersionStr() { return QString(VERSION_STRING); }
getVersionStr()
{
return QString(VERSION_STRING);
}
Q_INVOKABLE void Q_INVOKABLE void setText(QString text) { clipboard_->setText(text, QClipboard::Clipboard); }
setText(QString text)
{
clipboard_->setText(text, QClipboard::Clipboard);
}
Q_INVOKABLE const QString Q_INVOKABLE const QString qStringFromFile(const QString& filename)
qStringFromFile(const QString &filename)
{ {
return Utils::QByteArrayFromFile(filename); return Utils::QByteArrayFromFile(filename);
} }
Q_INVOKABLE const QString Q_INVOKABLE const QString getStyleSheet(const QString& name, const QString& source)
getStyleSheet(const QString &name, const QString &source)
{ {
auto simplifiedCSS = source.simplified().replace("'", "\""); auto simplifiedCSS = source.simplified().replace("'", "\"");
QString s = QString::fromLatin1("(function() {" QString s = QString::fromLatin1("(function() {"
@@ -410,88 +387,66 @@ public:
return s; return s;
} }
Q_INVOKABLE const QString Q_INVOKABLE const QString getCachePath()
getCachePath()
{ {
QDir dataDir(QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation)); QDir dataDir(QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation));
dataDir.cdUp(); dataDir.cdUp();
return dataDir.absolutePath() + "/jami"; return dataDir.absolutePath() + "/jami";
} }
Q_INVOKABLE bool Q_INVOKABLE bool createStartupLink() { return Utils::CreateStartupLink(L"Jami"); }
createStartupLink() Q_INVOKABLE QString GetRingtonePath() { return Utils::GetRingtonePath(); }
{ Q_INVOKABLE bool checkStartupLink() { return Utils::CheckStartupLink(L"Jami"); }
return Utils::CreateStartupLink(L"Jami");
}
Q_INVOKABLE QString
GetRingtonePath()
{
return Utils::GetRingtonePath();
}
Q_INVOKABLE bool
checkStartupLink()
{
return Utils::CheckStartupLink(L"Jami");
}
Q_INVOKABLE const QString Q_INVOKABLE const QString getContactImageString(const QString& accountId, const QString& uid)
getContactImageString(const QString &accountId, const QString &uid)
{ {
return Utils::getContactImageString(accountId, uid); return Utils::getContactImageString(accountId, uid);
} }
Q_INVOKABLE void removeConversation(const QString &accountId, Q_INVOKABLE void removeConversation(const QString& accountId,
const QString &uid, const QString& uid,
bool banContact = false); bool banContact = false);
Q_INVOKABLE void clearConversationHistory(const QString &accountId, const QString &uid); Q_INVOKABLE void clearConversationHistory(const QString& accountId, const QString& uid);
Q_INVOKABLE void setConversationFilter(const QString &filter); Q_INVOKABLE void setConversationFilter(const QString& filter);
Q_INVOKABLE int getTotalUnreadMessages(); Q_INVOKABLE int getTotalUnreadMessages();
Q_INVOKABLE int getTotalPendingRequest(); Q_INVOKABLE int getTotalPendingRequest();
Q_INVOKABLE const QString getBestName(const QString &accountId, const QString &uid); Q_INVOKABLE const QString getBestName(const QString& accountId, const QString& uid);
Q_INVOKABLE const QString getBestId(const QString &accountId, const QString &uid); Q_INVOKABLE const QString getBestId(const QString& accountId, const QString& uid);
Q_INVOKABLE const QString getCurrAccId(); Q_INVOKABLE const QString getCurrAccId();
Q_INVOKABLE const QString getCurrConvId(); Q_INVOKABLE const QString getCurrConvId();
Q_INVOKABLE void makePermanentCurrentConv(); Q_INVOKABLE void makePermanentCurrentConv();
Q_INVOKABLE const QStringList getCurrAccList(); Q_INVOKABLE const QStringList getCurrAccList();
Q_INVOKABLE int getAccountListSize(); Q_INVOKABLE int getAccountListSize();
Q_INVOKABLE void setCurrentCall(const QString &accountId, const QString &convUid); Q_INVOKABLE void setCurrentCall(const QString& accountId, const QString& convUid);
Q_INVOKABLE void startPreviewing(bool force); Q_INVOKABLE void startPreviewing(bool force);
Q_INVOKABLE void stopPreviewing(); Q_INVOKABLE void stopPreviewing();
Q_INVOKABLE bool hasVideoCall(); Q_INVOKABLE bool hasVideoCall();
Q_INVOKABLE const QString getCallId(const QString &accountId, const QString &convUid); Q_INVOKABLE const QString getCallId(const QString& accountId, const QString& convUid);
Q_INVOKABLE const QString getCallStatusStr(int statusInt); Q_INVOKABLE const QString getCallStatusStr(int statusInt);
Q_INVOKABLE QString getStringUTF8(QString string); Q_INVOKABLE QString getStringUTF8(QString string);
Q_INVOKABLE bool validateRegNameForm(const QString &regName); Q_INVOKABLE bool validateRegNameForm(const QString& regName);
Q_INVOKABLE QString getRecordQualityString(int value); Q_INVOKABLE QString getRecordQualityString(int value);
Q_INVOKABLE QString getCurrentPath(); Q_INVOKABLE QString getCurrentPath();
Q_INVOKABLE QString Q_INVOKABLE QString stringSimplifier(QString input) { return input.simplified(); }
stringSimplifier(QString input)
{
return input.simplified();
}
Q_INVOKABLE QString Q_INVOKABLE QString toNativeSeparators(QString inputDir)
toNativeSeparators(QString inputDir)
{ {
return QDir::toNativeSeparators(inputDir); return QDir::toNativeSeparators(inputDir);
} }
Q_INVOKABLE QString Q_INVOKABLE QString toFileInfoName(QString inputFileName)
toFileInfoName(QString inputFileName)
{ {
QFileInfo fi(inputFileName); QFileInfo fi(inputFileName);
return fi.fileName(); return fi.fileName();
} }
Q_INVOKABLE QString Q_INVOKABLE QString toFileAbsolutepath(QString inputFileName)
toFileAbsolutepath(QString inputFileName)
{ {
QFileInfo fi(inputFileName); QFileInfo fi(inputFileName);
return fi.absolutePath(); return fi.absolutePath();
} }
Q_INVOKABLE QString Q_INVOKABLE QString getAbsPath(QString path)
getAbsPath(QString path)
{ {
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
return path.replace("file:///", "").replace("\n", "").replace("\r", ""); return path.replace("file:///", "").replace("\n", "").replace("\r", "");
@@ -500,8 +455,7 @@ public:
#endif #endif
} }
Q_INVOKABLE QString Q_INVOKABLE QString getCroppedImageBase64FromFile(QString fileName, int size)
getCroppedImageBase64FromFile(QString fileName, int size)
{ {
auto image = Utils::cropImage(QImage(fileName)); auto image = Utils::cropImage(QImage(fileName));
auto croppedImage = image.scaled(size, auto croppedImage = image.scaled(size,
@@ -513,7 +467,21 @@ public:
Q_INVOKABLE bool checkShowPluginsButton(); Q_INVOKABLE bool checkShowPluginsButton();
Q_INVOKABLE QString fileName(const QString& path)
{
QFileInfo fi(path);
return fi.fileName();
}
Q_INVOKABLE QString getExt(const QString& path)
{
QFileInfo fi(path);
return fi.completeSuffix();
}
Q_INVOKABLE bool isImage(const QString& fileExt) const;
private: private:
QClipboard *clipboard_; QClipboard* clipboard_;
}; };
Q_DECLARE_METATYPE(UtilsAdapter *) Q_DECLARE_METATYPE(UtilsAdapter*)