1
0
mirror of https://github.com/qTox/qTox.git synced 2024-03-22 14:00:36 +08:00

Fix coding style and add copyright header

* added copyright header to src/platform/statusnotifier/enums.c
* 'switch(' → 'switch ('
* use Allman style

----
for / if / while / switch () {
 ↓
for / if / while / switch ()
{
----

----
for / if / while ()
{
    1_line;
}
 ↓
for / if / while ()
    1_line;

----

----
for / if / while ()
    1_line;
line_out_of_loop;
 ↓
for / if / while ()
    1_line;

line_out_of_loop;
----
This commit is contained in:
Zetok Zalbavar 2015-03-21 08:59:28 +00:00
parent f95291af3e
commit f3aa3073b0
No known key found for this signature in database
GPG Key ID: C953D3880212068A
15 changed files with 303 additions and 158 deletions

View File

@ -171,6 +171,7 @@ void Core::make_tox()
toxOptions.proxy_type = TOX_PROXY_SOCKS5;
else if (proxyType == ProxyType::ptHTTP)
toxOptions.proxy_type = TOX_PROXY_HTTP;
uint16_t sz = CString::fromString(proxyAddr, (unsigned char*)toxOptions.proxy_address);
toxOptions.proxy_address[sz] = 0;
toxOptions.proxy_port = proxyPort;
@ -260,6 +261,7 @@ void Core::start()
QString id = getSelfId().toString();
if (!id.isEmpty())
emit idSet(id);
setStatusMessage(tr("Toxing on qTox")); // this also solves the not updating issue
setUsername(tr("qTox User"));
}
@ -309,7 +311,9 @@ void Core::start()
setAvatar(TOX_AVATAR_FORMAT_PNG, data);
}
else
{
qDebug() << "Core: Error loading self avatar";
}
ready = true;
@ -340,7 +344,9 @@ void Core::process()
#endif
if (checkConnection())
{
tolerance = CORE_DISCONNECT_TOLERANCE;
}
else if (!(--tolerance))
{
bootstrapDht();
@ -356,13 +362,16 @@ bool Core::checkConnection()
//static int count = 0;
bool toxConnected = tox_isconnected(tox);
if (toxConnected && !isConnected) {
if (toxConnected && !isConnected)
{
qDebug() << "Core: Connected to DHT";
emit connected();
isConnected = true;
//if (count) qDebug() << "Core: disconnect count:" << count;
//count = 0;
} else if (!toxConnected && isConnected) {
}
else if (!toxConnected && isConnected)
{
qDebug() << "Core: Disconnected to DHT";
emit disconnected();
isConnected = false;
@ -430,7 +439,8 @@ void Core::onStatusMessageChanged(Tox*/* tox*/, int friendId, const uint8_t* cMe
void Core::onUserStatusChanged(Tox*/* tox*/, int friendId, uint8_t userstatus, void* core)
{
Status status;
switch (userstatus) {
switch (userstatus)
{
case TOX_USERSTATUS_NONE:
status = Status::Online;
break;
@ -474,7 +484,9 @@ void Core::onConnectionStatusChanged(Tox*/* tox*/, int friendId, uint8_t status,
emit static_cast<Core*>(core)->fileTransferBrokenUnbroken(f, true);
}
}
} else {
}
else
{
for (ToxFile& f : fileRecvQueue)
{
if (f.friendId == friendId && f.status == ToxFile::BROKEN)
@ -536,6 +548,7 @@ void Core::onGroupTitleChange(Tox*, int groupnumber, int peernumber, const uint8
QString author;
if (peernumber >= 0)
author = core->getGroupPeerName(groupnumber, peernumber);
emit core->groupTitleChanged(groupnumber, author, CString::toString(title, len));
}
@ -749,9 +762,12 @@ void Core::onReadReceiptCallback(Tox*, int32_t friendnumber, uint32_t receipt, v
void Core::acceptFriendRequest(const QString& userId)
{
int friendId = tox_add_friend_norequest(tox, CUserId(userId).data());
if (friendId == -1) {
if (friendId == -1)
{
emit failedToAddFriend(userId);
} else {
}
else
{
saveConfiguration();
emit friendAdded(friendId, userId);
}
@ -782,6 +798,7 @@ void Core::requestFriendship(const QString& friendAddress, const QString& messag
QString inviteStr = tr("/me offers friendship.");
if (message.length())
inviteStr = tr("/me offers friendship, \"%1\"").arg(message);
HistoryKeeper::getInstance()->addChatEntry(userId, inviteStr, getSelfId().publicKey, QDateTime::currentDateTime(), true);
emit friendAdded(friendId, userId);
}
@ -1035,9 +1052,13 @@ void Core::removeFriend(int friendId, bool fake)
{
if (!isReady() || fake)
return;
if (tox_del_friend(tox, friendId) == -1) {
if (tox_del_friend(tox, friendId) == -1)
{
emit failedToRemoveFriend(friendId);
} else {
}
else
{
saveConfiguration();
emit friendRemoved(friendId);
}
@ -1047,6 +1068,7 @@ void Core::removeGroup(int groupId, bool fake)
{
if (!isReady() || fake)
return;
tox_del_groupchat(tox, groupId);
if (groupCalls[groupId].active)
@ -1060,6 +1082,7 @@ QString Core::getUsername() const
uint8_t* name = new uint8_t[size];
if (tox_get_self_name(tox, name) == size)
sname = CString::toString(name, size);
delete[] name;
return sname;
}
@ -1068,9 +1091,12 @@ void Core::setUsername(const QString& username)
{
CString cUsername(username);
if (tox_set_name(tox, cUsername.data(), cUsername.size()) == -1) {
if (tox_set_name(tox, cUsername.data(), cUsername.size()) == -1)
{
emit failedToSetUsername(username);
} else {
}
else
{
emit usernameSet(username);
saveConfiguration();
}
@ -1130,6 +1156,7 @@ QString Core::getStatusMessage() const
uint8_t* name = new uint8_t[size];
if (tox_get_self_status_message(tox, name, size) == size)
sname = CString::toString(name, size);
delete[] name;
return sname;
}
@ -1138,9 +1165,12 @@ void Core::setStatusMessage(const QString& message)
{
CString cMessage(message);
if (tox_set_status_message(tox, cMessage.data(), cMessage.size()) == -1) {
if (tox_set_status_message(tox, cMessage.data(), cMessage.size()) == -1)
{
emit failedToSetStatusMessage(message);
} else {
}
else
{
saveConfiguration();
emit statusMessageSet(message);
}
@ -1149,7 +1179,8 @@ void Core::setStatusMessage(const QString& message)
void Core::setStatus(Status status)
{
TOX_USERSTATUS userstatus;
switch (status) {
switch (status)
{
case Status::Online:
userstatus = TOX_USERSTATUS_NONE;
break;
@ -1164,10 +1195,13 @@ void Core::setStatus(Status status)
break;
}
if (tox_set_user_status(tox, userstatus) == 0) {
if (tox_set_user_status(tox, userstatus) == 0)
{
saveConfiguration();
emit statusSet(status);
} else {
}
else
{
emit failedToSetStatus(status);
}
}
@ -1186,11 +1220,14 @@ QString Core::sanitize(QString name)
QList<QChar> banned = {'/', '\\', ':', '<', '>', '"', '|', '?', '*'};
for (QChar c : banned)
name.replace(c, '_');
// also remove leading and trailing periods
if (name[0] == '.')
name[0] = '_';
if (name.endsWith('.'))
name[name.length()-1] = '_';
return name;
}
@ -1201,18 +1238,21 @@ bool Core::loadConfiguration(QString path)
QFile configurationFile(path);
qDebug() << "Core::loadConfiguration: reading from " << path;
if (!configurationFile.exists()) {
if (!configurationFile.exists())
{
qWarning() << "The Tox configuration file was not found";
return true;
}
if (!configurationFile.open(QIODevice::ReadOnly)) {
if (!configurationFile.open(QIODevice::ReadOnly))
{
qCritical() << "File " << path << " cannot be opened";
return true;
}
qint64 fileSize = configurationFile.size();
if (fileSize > 0) {
if (fileSize > 0)
{
QByteArray data = configurationFile.readAll();
int error = tox_load(tox, reinterpret_cast<uint8_t *>(data.data()), data.size());
if (error < 0)
@ -1272,6 +1312,7 @@ void Core::saveConfiguration()
QDir directory(dir);
if (!directory.exists() && !directory.mkpath(directory.absolutePath())) {
qCritical() << "Error while creating directory " << dir;
return;
}
@ -1329,30 +1370,35 @@ void Core::switchConfiguration(const QString& profile)
void Core::loadFriends()
{
const uint32_t friendCount = tox_count_friendlist(tox);
if (friendCount > 0) {
if (friendCount > 0)
{
// assuming there are not that many friends to fill up the whole stack
int32_t *ids = new int32_t[friendCount];
tox_get_friendlist(tox, ids, friendCount);
uint8_t clientId[TOX_PUBLIC_KEY_SIZE];
for (int32_t i = 0; i < static_cast<int32_t>(friendCount); ++i) {
if (tox_get_client_id(tox, ids[i], clientId) == 0) {
for (int32_t i = 0; i < static_cast<int32_t>(friendCount); ++i)
{
if (tox_get_client_id(tox, ids[i], clientId) == 0)
{
emit friendAdded(ids[i], CUserId::toString(clientId));
const int nameSize = tox_get_name_size(tox, ids[i]);
if (nameSize > 0) {
if (nameSize > 0)
{
uint8_t *name = new uint8_t[nameSize];
if (tox_get_name(tox, ids[i], name) == nameSize) {
if (tox_get_name(tox, ids[i], name) == nameSize)
emit friendUsernameChanged(ids[i], CString::toString(name, nameSize));
}
delete[] name;
}
const int statusMessageSize = tox_get_status_message_size(tox, ids[i]);
if (statusMessageSize > 0) {
if (statusMessageSize > 0)
{
uint8_t *statusMessage = new uint8_t[statusMessageSize];
if (tox_get_status_message(tox, ids[i], statusMessage, statusMessageSize) == statusMessageSize) {
if (tox_get_status_message(tox, ids[i], statusMessage, statusMessageSize) == statusMessageSize)
emit friendStatusMessageChanged(ids[i], CString::toString(statusMessage, statusMessageSize));
}
delete[] statusMessage;
}
@ -1366,9 +1412,8 @@ void Core::loadFriends()
void Core::checkLastOnline(int friendId) {
const uint64_t lastOnline = tox_get_last_online(tox, friendId);
if (lastOnline > 0) {
if (lastOnline > 0)
emit friendLastSeenChanged(friendId, QDateTime::fromTime_t(lastOnline));
}
}
int Core::getGroupNumberPeers(int groupId) const
@ -1425,6 +1470,7 @@ QList<QString> Core::getGroupPeerNames(int groupId) const
}
for (int i=0; i<nPeers; i++)
names.push_back(CString::toString(namesArray[i], lengths[i]));
return names;
}
@ -1579,26 +1625,18 @@ void Core::groupInviteFriend(int friendId, int groupId)
void Core::createGroup(uint8_t type)
{
if (type == TOX_GROUPCHAT_TYPE_TEXT)
{
emit emptyGroupCreated(tox_add_groupchat(tox));
}
else if (type == TOX_GROUPCHAT_TYPE_AV)
{
emit emptyGroupCreated(toxav_add_av_groupchat(tox, &Audio::playGroupAudioQueued, this));
}
else
{
qWarning() << "Core::createGroup: Unknown type "<<type;
}
}
bool Core::hasFriendWithAddress(const QString &addr) const
{
// Valid length check
if (addr.length() != (TOX_FRIEND_ADDRESS_SIZE * 2))
{
return false;
}
QString pubkey = addr.left(TOX_PUBLIC_KEY_SIZE * 2);
return hasFriendWithPublicKey(pubkey);
@ -1608,9 +1646,7 @@ bool Core::hasFriendWithPublicKey(const QString &pubkey) const
{
// Valid length check
if (pubkey.length() != (TOX_PUBLIC_KEY_SIZE * 2))
{
return false;
}
bool found = false;
const uint32_t friendCount = tox_count_friendlist(tox);
@ -1672,9 +1708,10 @@ QList<CString> Core::splitMessage(const QString &message, int maxLen)
splitPos = maxLen;
if (ba_message[splitPos] & 0x80)
{
do {
do
splitPos--;
} while (!(ba_message[splitPos] & 0x40));
while (!(ba_message[splitPos] & 0x40));
}
splitPos--;
}

View File

@ -107,6 +107,7 @@ QByteArray Core::encryptData(const QByteArray& data, PasswordType passtype)
{
if (!pwsaltedkeys[passtype])
return QByteArray();
uint8_t encrypted[data.size() + tox_pass_encryption_extra_length()];
if (tox_pass_key_encrypt(reinterpret_cast<const uint8_t*>(data.data()), data.size(), pwsaltedkeys[passtype], encrypted) == -1)
{
@ -120,6 +121,7 @@ QByteArray Core::decryptData(const QByteArray& data, PasswordType passtype)
{
if (!pwsaltedkeys[passtype])
return QByteArray();
int sz = data.size() - tox_pass_encryption_extra_length();
uint8_t decrypted[sz];
int decr_size = tox_pass_key_decrypt(reinterpret_cast<const uint8_t*>(data.data()), data.size(), pwsaltedkeys[passtype], decrypted);
@ -183,7 +185,9 @@ bool Core::loadEncryptedSave(QByteArray& data)
dialogtxt = tr("The profile password failed. Please try another?", "used only when pw set before load() doesn't work");
}
else
{
dialogtxt = a;
}
uint8_t salt[tox_pass_salt_length()];
tox_get_salt(reinterpret_cast<uint8_t *>(data.data()), salt);
@ -198,11 +202,14 @@ bool Core::loadEncryptedSave(QByteArray& data)
return false;
}
else
{
setPassword(pw, ptMain, salt);
}
error = tox_encrypted_key_load(tox, reinterpret_cast<uint8_t *>(data.data()), data.size(), pwsaltedkeys[ptMain]);
dialogtxt = a + "\n" + b;
} while (error != 0);
}
while (error != 0);
Settings::getInstance().setEncryptTox(true);
return true;
@ -232,10 +239,12 @@ void Core::checkEncryptedHistory()
{
if (!exists || HistoryKeeper::checkPassword())
return;
dialogtxt = tr("The chat history password failed. Please try another?", "used only when pw set before load() doesn't work");
}
else
dialogtxt = a;
dialogtxt += "\n" + c;
if (pwsaltedkeys[ptMain])
@ -263,11 +272,14 @@ void Core::checkEncryptedHistory()
return;
}
else
{
setPassword(pw, ptHistory, reinterpret_cast<uint8_t*>(salt.data()));
}
error = exists && !HistoryKeeper::checkPassword();
dialogtxt = a + "\n" + c + "\n" + b;
} while (error);
}
while (error);
}
void Core::saveConfiguration(const QString& path)
@ -282,7 +294,8 @@ void Core::saveConfiguration(const QString& path)
}
QSaveFile configurationFile(path);
if (!configurationFile.open(QIODevice::WriteOnly)) {
if (!configurationFile.open(QIODevice::WriteOnly))
{
qCritical() << "File " << path << " cannot be opened";
return;
}
@ -318,7 +331,9 @@ void Core::saveConfiguration(const QString& path)
}
}
else
{
tox_save(tox, data);
}
configurationFile.write(reinterpret_cast<char *>(data), fileSize);
configurationFile.commit();

View File

@ -372,7 +372,8 @@ void HistoryKeeper::setSyncType(Db::syncType sType)
{
QString syncCmd;
switch (sType) {
switch (sType)
{
case Db::syncType::stFull:
syncCmd = "FULL";
break;

View File

@ -179,15 +179,17 @@ int main(int argc, char *argv[])
sudoprocess->start(sudo); //Where the magic actually happens, safety checks ^
sudoprocess->waitForFinished();
if (old_app.removeRecursively()) { //We've just deleted the running program
if (old_app.removeRecursively()) //We've just deleted the running program
{
qDebug() << "OS X: Cleaned up old directory";
} else {
}
else
{
qDebug() << "OS X: This should never happen, the directory failed to delete";
}
if (fork() != 0) { //Forking is required otherwise it won't actually cleanly launch
if (fork() != 0) //Forking is required otherwise it won't actually cleanly launch
return EXIT_UPDATE_MACX;
}
qtoxprocess->start(qtox);
@ -259,6 +261,7 @@ int main(int argc, char *argv[])
uint32_t dest = 0;
if (parser.isSet("p"))
dest = Settings::getInstance().getCurrentProfileId();
time_t event = ipc.postEvent("activate", QByteArray(), dest);
if (ipc.waitUntilAccepted(event, 2))
{

View File

@ -67,20 +67,18 @@ void FlowLayout::addItem(QLayoutItem *item)
int FlowLayout::horizontalSpacing() const
{
if (m_hSpace >= 0) {
if (m_hSpace >= 0)
return m_hSpace;
} else {
else
return smartSpacing(QStyle::PM_LayoutHorizontalSpacing);
}
}
int FlowLayout::verticalSpacing() const
{
if (m_vSpace >= 0) {
if (m_vSpace >= 0)
return m_vSpace;
} else {
else
return smartSpacing(QStyle::PM_LayoutVerticalSpacing);
}
}
int FlowLayout::count() const
@ -149,18 +147,22 @@ int FlowLayout::doLayout(const QRect &rect, bool testOnly) const
int lineHeight = 0;
QLayoutItem *item;
foreach (item, itemList) {
foreach (item, itemList)
{
QWidget *wid = item->widget();
int spaceX = horizontalSpacing();
if (spaceX == -1)
spaceX = wid->style()->layoutSpacing(
QSizePolicy::PushButton, QSizePolicy::PushButton, Qt::Horizontal);
int spaceY = verticalSpacing();
if (spaceY == -1)
spaceY = wid->style()->layoutSpacing(
QSizePolicy::PushButton, QSizePolicy::PushButton, Qt::Vertical);
int nextX = x + item->sizeHint().width() + spaceX;
if (nextX - spaceX > effectiveRect.right() && lineHeight > 0) {
if (nextX - spaceX > effectiveRect.right() && lineHeight > 0)
{
x = effectiveRect.x();
y = y + lineHeight + spaceY;
nextX = x + item->sizeHint().width() + spaceX;
@ -178,12 +180,17 @@ int FlowLayout::doLayout(const QRect &rect, bool testOnly) const
int FlowLayout::smartSpacing(QStyle::PixelMetric pm) const
{
QObject *parent = this->parent();
if (!parent) {
if (!parent)
{
return -1;
} else if (parent->isWidgetType()) {
}
else if (parent->isWidgetType())
{
QWidget *pw = static_cast<QWidget *>(parent);
return pw->style()->pixelMetric(pm, 0, pw);
} else {
}
else
{
return static_cast<QLayout *>(parent)->spacing();
}
}

View File

@ -54,6 +54,7 @@ Settings& Settings::getInstance()
{
if (!settings)
settings = new Settings();
return *settings;
}
@ -91,7 +92,9 @@ QString Settings::detectProfile()
{
profile = askProfiles();
if (profile.isEmpty())
{
return "";
}
else
{
switchProfile(profile);
@ -111,6 +114,7 @@ QList<QString> Settings::searchProfiles()
dir.setNameFilters(QStringList("*.tox"));
for (QFileInfo file : dir.entryInfoList())
out += file.completeBaseName();
return out;
}
@ -153,7 +157,9 @@ void Settings::load()
ps.endGroup();
}
else
{
makeToxPortable = false;
}
QDir dir(getSettingsDirPath());
QString filePath = dir.filePath(FILENAME);
@ -177,7 +183,8 @@ void Settings::load()
useCustomDhtList = true;
qDebug() << "Using custom bootstrap nodes list";
int serverListSize = s.beginReadArray("dhtServerList");
for (int i = 0; i < serverListSize; i ++) {
for (int i = 0; i < serverListSize; i ++)
{
s.setArrayIndex(i);
DhtServer server;
server.name = s.value("name").toString();
@ -189,7 +196,9 @@ void Settings::load()
s.endArray();
}
else
{
useCustomDhtList=false;
}
s.endGroup();
s.beginGroup("General");
@ -225,9 +234,9 @@ void Settings::load()
s.beginGroup("Widgets");
QList<QString> objectNames = s.childKeys();
for (const QString& name : objectNames) {
for (const QString& name : objectNames)
widgetSettings[name] = s.value(name).toByteArray();
}
s.endGroup();
s.beginGroup("GUI");
@ -279,7 +288,8 @@ void Settings::load()
QSettings rcs(":/conf/settings.ini", QSettings::IniFormat);
rcs.beginGroup("DHT Server");
int serverListSize = rcs.beginReadArray("dhtServerList");
for (int i = 0; i < serverListSize; i ++) {
for (int i = 0; i < serverListSize; i ++)
{
rcs.setArrayIndex(i);
DhtServer server;
server.name = rcs.value("name").toString();
@ -354,7 +364,8 @@ void Settings::saveGlobal(QString path)
s.beginGroup("DHT Server");
s.setValue("useCustomList", useCustomDhtList);
s.beginWriteArray("dhtServerList", dhtServerList.size());
for (int i = 0; i < dhtServerList.size(); i ++) {
for (int i = 0; i < dhtServerList.size(); i ++)
{
s.setArrayIndex(i);
s.setValue("name", dhtServerList[i].name);
s.setValue("userId", dhtServerList[i].userId);
@ -393,9 +404,9 @@ void Settings::saveGlobal(QString path)
s.beginGroup("Widgets");
const QList<QString> widgetNames = widgetSettings.keys();
for (const QString& name : widgetNames) {
for (const QString& name : widgetNames)
s.setValue(name, widgetSettings.value(name));
}
s.endGroup();
s.beginGroup("GUI");
@ -499,12 +510,15 @@ QPixmap Settings::getSavedAvatar(const QString &ownerId)
QString filePath = dir.filePath("avatar_"+ownerId.left(64));
if (!QFileInfo(filePath).exists()) // try without truncation, for old self avatars
filePath = dir.filePath("avatar_"+ownerId);
pic.load(filePath);
saveAvatar(pic, ownerId);
QFile::remove(filePath);
}
else
{
pic.load(filePath);
}
return pic;
}
@ -524,6 +538,7 @@ void Settings::saveAvatarHash(const QByteArray& hash, const QString& ownerId)
QFile file(dir.filePath("avatars/"+ownerId.left(64)+".hash"));
if (!file.open(QIODevice::WriteOnly))
return;
file.write(hash);
file.close();
}
@ -535,6 +550,7 @@ QByteArray Settings::getAvatarHash(const QString& ownerId)
QFile file(dir.filePath("avatars/"+ownerId.left(64)+".hash"));
if (!file.open(QIODevice::ReadOnly))
return QByteArray();
QByteArray out = file.readAll();
file.close();
return out;
@ -824,6 +840,7 @@ void Settings::setAutoAwayTime(int newValue)
{
if (newValue < 0)
newValue = 10;
autoAwayTime = newValue;
}
@ -833,9 +850,7 @@ QString Settings::getAutoAcceptDir(const ToxID& id) const
auto it = friendLst.find(key);
if (it != friendLst.end())
{
return it->autoAcceptDir;
}
return QString();
}
@ -848,7 +863,9 @@ void Settings::setAutoAcceptDir(const ToxID &id, const QString& dir)
if (it != friendLst.end())
{
it->autoAcceptDir = dir;
} else {
}
else
{
updateFriendAdress(id.toString());
setAutoAcceptDir(id, dir);
}
@ -1084,9 +1101,7 @@ QString Settings::getFriendAdress(const QString &publicKey) const
QString key = ToxID::fromString(publicKey).publicKey;
auto it = friendLst.find(key);
if (it != friendLst.end())
{
return it->addr;
}
return QString();
}
@ -1098,7 +1113,9 @@ void Settings::updateFriendAdress(const QString &newAddr)
if (it != friendLst.end())
{
it->addr = newAddr;
} else {
}
else
{
friendProp fp;
fp.addr = newAddr;
fp.alias = "";
@ -1112,9 +1129,7 @@ QString Settings::getFriendAlias(const ToxID &id) const
QString key = id.publicKey;
auto it = friendLst.find(key);
if (it != friendLst.end())
{
return it->alias;
}
return QString();
}
@ -1126,7 +1141,9 @@ void Settings::setFriendAlias(const ToxID &id, const QString &alias)
if (it != friendLst.end())
{
it->alias = alias;
} else {
}
else
{
friendProp fp;
fp.addr = key;
fp.alias = alias;

View File

@ -206,9 +206,8 @@ QIcon SmileyPack::getCachedSmiley(const QString &key)
// cache it if needed
QString file = filenameTable.value(key);
if (!iconCache.contains(file)) {
if (!iconCache.contains(file))
cacheSmiley(file);
}
return iconCache.value(file);
}

View File

@ -1,4 +1,18 @@
/*
Copyright (C) 2015 by Project Tox <https://tox.im>
This file is part of qTox, a Qt-based graphical interface for Tox.
This program is libre 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 COPYING file for more details.
*/
#include "enums.h"
@ -6,7 +20,8 @@ GType
status_notifier_error_get_type (void)
{
static GType etype = 0;
if (etype == 0) {
if (etype == 0)
{
static const GEnumValue values[] = {
{ STATUS_NOTIFIER_ERROR_NO_CONNECTION, "STATUS_NOTIFIER_ERROR_NO_CONNECTION", "connection" },
{ STATUS_NOTIFIER_ERROR_NO_NAME, "STATUS_NOTIFIER_ERROR_NO_NAME", "name" },
@ -22,7 +37,8 @@ GType
status_notifier_state_get_type (void)
{
static GType etype = 0;
if (etype == 0) {
if (etype == 0)
{
static const GEnumValue values[] = {
{ STATUS_NOTIFIER_STATE_NOT_REGISTERED, "STATUS_NOTIFIER_STATE_NOT_REGISTERED", "not-registered" },
{ STATUS_NOTIFIER_STATE_REGISTERING, "STATUS_NOTIFIER_STATE_REGISTERING", "registering" },
@ -38,7 +54,8 @@ GType
status_notifier_icon_get_type (void)
{
static GType etype = 0;
if (etype == 0) {
if (etype == 0)
{
static const GEnumValue values[] = {
{ STATUS_NOTIFIER_ICON, "STATUS_NOTIFIER_ICON", "status-notifier-icon" },
{ STATUS_NOTIFIER_ATTENTION_ICON, "STATUS_NOTIFIER_ATTENTION_ICON", "status-notifier-attention-icon" },
@ -55,7 +72,8 @@ GType
status_notifier_category_get_type (void)
{
static GType etype = 0;
if (etype == 0) {
if (etype == 0)
{
static const GEnumValue values[] = {
{ STATUS_NOTIFIER_CATEGORY_APPLICATION_STATUS, "STATUS_NOTIFIER_CATEGORY_APPLICATION_STATUS", "application-status" },
{ STATUS_NOTIFIER_CATEGORY_COMMUNICATIONS, "STATUS_NOTIFIER_CATEGORY_COMMUNICATIONS", "communications" },
@ -71,7 +89,8 @@ GType
status_notifier_status_get_type (void)
{
static GType etype = 0;
if (etype == 0) {
if (etype == 0)
{
static const GEnumValue values[] = {
{ STATUS_NOTIFIER_STATUS_PASSIVE, "STATUS_NOTIFIER_STATUS_PASSIVE", "passive" },
{ STATUS_NOTIFIER_STATUS_ACTIVE, "STATUS_NOTIFIER_STATUS_ACTIVE", "active" },
@ -86,7 +105,8 @@ GType
status_notifier_scroll_orientation_get_type (void)
{
static GType etype = 0;
if (etype == 0) {
if (etype == 0)
{
static const GEnumValue values[] = {
{ STATUS_NOTIFIER_SCROLL_ORIENTATION_HORIZONTAL, "STATUS_NOTIFIER_SCROLL_ORIENTATION_HORIZONTAL", "horizontal" },
{ STATUS_NOTIFIER_SCROLL_ORIENTATION_VERTICAL, "STATUS_NOTIFIER_SCROLL_ORIENTATION_VERTICAL", "vertical" },
@ -96,6 +116,3 @@ status_notifier_scroll_orientation_get_type (void)
}
return etype;
}

View File

@ -58,35 +58,45 @@ QByteArray ToxDNS::fetchLastTextRecord(const QString& record, bool silent)
qApp->processEvents();
QThread::msleep(100);
}
if (timeout >= 30) {
if (timeout >= 30)
{
dns.abort();
if (!silent)
showWarning(tr("The connection timed out","The DNS gives the Tox ID associated to toxme.se addresses"));
return result;
}
if (dns.error() == QDnsLookup::NotFoundError) {
if (dns.error() == QDnsLookup::NotFoundError)
{
if (!silent)
showWarning(tr("This address does not exist","The DNS gives the Tox ID associated to toxme.se addresses"));
return result;
}
else if (dns.error() != QDnsLookup::NoError) {
else if (dns.error() != QDnsLookup::NoError)
{
if (!silent)
showWarning(tr("Error while looking up DNS","The DNS gives the Tox ID associated to toxme.se addresses"));
return result;
}
const QList<QDnsTextRecord> textRecords = dns.textRecords();
if (textRecords.isEmpty()) {
if (textRecords.isEmpty())
{
if (!silent)
showWarning(tr("No text record found", "Error with the DNS"));
return result;
}
const QList<QByteArray> textRecordValues = textRecords.last().values();
if (textRecordValues.length() != 1) {
if (textRecordValues.length() != 1)
{
if (!silent)
showWarning(tr("Unexpected number of values in text record", "Error with the DNS"));
return result;
}
@ -104,7 +114,8 @@ QString ToxDNS::queryTox1(const QString& record, bool silent)
// Check toxdns protocol version
int verx = entry.indexOf("v=");
if (verx) {
if (verx)
{
verx += 2;
int verend = entry.indexOf(';', verx);
if (verend)
@ -114,6 +125,7 @@ QString ToxDNS::queryTox1(const QString& record, bool silent)
{
if (!silent)
showWarning(tr("The version of Tox DNS used by this server is not supported", "Error with the DNS"));
return toxId;
}
}
@ -121,23 +133,29 @@ QString ToxDNS::queryTox1(const QString& record, bool silent)
// Get the tox id
int idx = entry.indexOf("id=");
if (idx < 0) {
if (idx < 0)
{
if (!silent)
showWarning(tr("The DNS lookup does not contain any Tox ID", "Error with the DNS"));
return toxId;
}
idx += 3;
if (entry.length() < idx + static_cast<int>(TOX_ID_LENGTH)) {
if (entry.length() < idx + static_cast<int>(TOX_ID_LENGTH))
{
if (!silent)
showWarning(tr("The DNS lookup does not contain a valid Tox ID", "Error with the DNS"));
return toxId;
}
toxId = entry.mid(idx, TOX_ID_LENGTH);
if (!ToxID::isToxId(toxId)) {
if (!ToxID::isToxId(toxId))
{
if (!silent)
showWarning(tr("The DNS lookup does not contain a valid Tox ID", "Error with the DNS"));
return toxId;
}
@ -178,7 +196,8 @@ QString ToxDNS::queryTox3(const tox3_server& server, const QString &record, bool
// Check toxdns protocol version
verx = entry.indexOf("v=");
if (verx!=-1) {
if (verx!=-1)
{
verx += 2;
int verend = entry.indexOf(';', verx);
if (verend!=-1)
@ -194,7 +213,8 @@ QString ToxDNS::queryTox3(const tox3_server& server, const QString &record, bool
// Get and decrypt the tox id
idx = entry.indexOf("id=");
if (idx < 0) {
if (idx < 0)
{
qWarning() << "queryTox3: Server "<<server.name<<" returned an empty id, using tox1 as a fallback";
goto fallbackOnTox1;
}
@ -217,6 +237,7 @@ QString ToxDNS::queryTox3(const tox3_server& server, const QString &record, bool
fallbackOnTox1:
if (tox_dns3)
tox_dns3_kill(tox_dns3);
#if TOX1_SILENT_FALLBACK
toxIdStr = queryTox1(record, silent);
#elif TOX1_ASK_FALLBACK
@ -226,6 +247,7 @@ Should tox1 be used anyway?\n\
If unsure, press No, so that request to ToxDNS service will not be made using unsecure protocol."), QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
if (btn == QMessageBox::Yes)
queryTox1(record, silent);
#endif
return toxIdStr;
}
@ -234,12 +256,17 @@ ToxID ToxDNS::resolveToxAddress(const QString &address, bool silent)
{
ToxID toxId;
if (address.isEmpty()) {
if (address.isEmpty())
{
return toxId;
} else if (ToxID::isToxId(address)) {
}
else if (ToxID::isToxId(address))
{
toxId = ToxID::fromString(address);
return toxId;
} else {
}
else
{
// If we're querying one of our pinned server, do a tox3 request directly
QString servname = address.mid(address.indexOf('@')+1);
for (const ToxDNS::tox3_server& pin : ToxDNS::pinnedServers)
@ -272,6 +299,7 @@ Should tox1 be used anyway?\n\
If unsure, press No, so that request to ToxDNS service will not be made using unsecure protocol."), QMessageBox::Ok|QMessageBox::No, QMessageBox::No);
if (btn == QMessageBox::Ok)
toxId = ToxID::fromString(queryTox1(address, silent));
#else
return toxId;
#endif

View File

@ -84,16 +84,22 @@ void AddFriendForm::onSendTriggered()
{
QString id = toxId.text().trimmed();
if (id.isEmpty()) {
if (id.isEmpty())
{
GUI::showWarning(tr("Couldn't add friend"), tr("Please fill in a valid Tox ID","Tox ID of the friend you're sending a friend request to"));
} else if (ToxID::isToxId(id)) {
}
else if (ToxID::isToxId(id))
{
if (id.toUpper() == Core::getInstance()->getSelfId().toString().toUpper())
GUI::showWarning(tr("Couldn't add friend"), tr("You can't add yourself as a friend!","When trying to add your own Tox ID as friend"));
else
emit friendRequested(id, getMessage());
this->toxId.clear();
this->message.clear();
} else {
}
else
{
if (Settings::getInstance().getProxyType() != ProxyType::ptNone)
{
QMessageBox::StandardButton btn = QMessageBox::warning(main, "qTox", tr("qTox needs to use the Tox DNS, but can't do it through a proxy.\n\

View File

@ -110,8 +110,10 @@ void GroupChatForm::onSendTriggered()
emit sendAction(group->getGroupId(), msg);
}
else
{
emit sendMessage(group->getGroupId(), msg);
}
}
else
addSelfMessage(msg, msg.startsWith("/me "), QDateTime::currentDateTime(), true);
}
@ -150,6 +152,7 @@ void GroupChatForm::onUserListChanged()
QLabel* label = orderizer[names[i]];
if (i != nNames - 1)
label->setText(label->text() + ", ");
namesListLayout->addWidget(label);
}

View File

@ -64,12 +64,14 @@ void TabCompleter::buildCompletionList()
void TabCompleter::complete()
{
if (!enabled) {
if (!enabled)
{
buildCompletionList();
enabled = true;
}
if (nextCompletion != completionMap.end()) {
if (nextCompletion != completionMap.end())
{
// clear previous completion
auto cur = msgEdit->textCursor();
cur.setPosition(cur.selectionEnd());
@ -85,13 +87,16 @@ void TabCompleter::complete()
nextCompletion++;
// we're completing the first word of the line
if (msgEdit->textCursor().position() == lastCompletionLength) {
if (msgEdit->textCursor().position() == lastCompletionLength)
{
msgEdit->insertPlainText(nickSuffix);
lastCompletionLength += nickSuffix.length();
}
}
else { // we're at the end of the list -> start over again
if (!completionMap.isEmpty()) {
else
{ // we're at the end of the list -> start over again
if (!completionMap.isEmpty())
{
nextCompletion = completionMap.begin();
complete();
}

View File

@ -71,6 +71,7 @@ bool toxActivateEventHandler(const QByteArray&)
{
if (!Widget::getInstance()->isActiveWindow())
Widget::getInstance()->forceShow();
return true;
}
@ -247,7 +248,9 @@ void Widget::updateIcons()
QString status;
if (eventIcon)
{
status = "event";
}
else
{
status = ui->statusButton->property("status").toString();
@ -273,6 +276,7 @@ Widget::~Widget()
AutoUpdater::abortUpdates();
if (icon)
icon->hide();
hideMainForms();
delete profileForm;
delete settingsWidget;
@ -295,6 +299,7 @@ Widget* Widget::getInstance()
if (!instance)
instance = new Widget();
return instance;
}
@ -319,10 +324,8 @@ void Widget::changeEvent(QEvent *event)
if (event->type() == QEvent::WindowStateChange)
{
if (isMinimized() && Settings::getInstance().getMinimizeToTray())
{
this->hide();
}
}
}
void Widget::resizeEvent(QResizeEvent *event)
@ -427,9 +430,7 @@ void Widget::confirmExecutableOpen(const QFileInfo file)
if (dangerousExtensions.contains(file.suffix()))
{
if (!GUI::askQuestion(tr("Executable file", "popup title"), tr("You have asked qTox to open an executable file. Executable files can potentially damage your computer. Are you sure want to open this file?", "popup text"), false, true))
{
return;
}
// The user wants to run this file, so make it executable and run it
QFile(file.filePath()).setPermissions(file.permissions() | QFile::ExeOwner | QFile::ExeUser | QFile::ExeGroup | QFile::ExeOther);
@ -513,13 +514,12 @@ void Widget::hideMainForms()
QLayoutItem* item;
while ((item = ui->mainHead->layout()->takeAt(0)) != 0)
item->widget()->hide();
while ((item = ui->mainContent->layout()->takeAt(0)) != 0)
item->widget()->hide();
if (activeChatroomWidget != nullptr)
{
activeChatroomWidget->setAsInactiveChatroom();
}
}
void Widget::onUsernameChanged(const QString& newUsername, const QString& oldUsername)
@ -639,7 +639,8 @@ void Widget::onFriendStatusChanged(int friendId, Status status)
&& Settings::getInstance().getStatusChangeNotificationEnabled())
{
QString fStatus = "";
switch(f->getStatus()){
switch (f->getStatus())
{
case Status::Away:
fStatus = tr("away", "contact status"); break;
case Status::Busy:
@ -689,9 +690,8 @@ void Widget::onChatroomWidgetClicked(GenericChatroomWidget *widget)
hideMainForms();
widget->setChatForm(*ui);
if (activeChatroomWidget != nullptr)
{
activeChatroomWidget->setAsInactiveChatroom();
}
activeChatroomWidget = widget;
widget->setAsActiveChatroom();
setWindowTitle(widget->getName());
@ -762,6 +762,7 @@ void Widget::playRingtone()
{
if (ui->statusButton->property("status").toString() == "busy")
return;
QApplication::alert(this);
static QFile sndFile1(":audio/ToxicIncomingCall.pcm"); // for whatever reason this plays slower/downshifted from what any other program plays the file as... but whatever
@ -902,7 +903,9 @@ void Widget::onGroupNamelistChanged(int groupnumber, int peernumber, uint8_t Cha
// g->getChatForm()->addSystemInfoMessage(tr("%1 has left the chat").arg(name), "white", QDateTime::currentDateTime());
}
else if (change == TOX_CHAT_CHANGE_PEER_NAME) // core overwrites old name before telling us it changed...
{
g->updatePeer(peernumber,Nexus::getCore()->getGroupPeerName(groupnumber, peernumber));
}
}
void Widget::onGroupTitleChanged(int groupnumber, const QString& author, const QString& title)
@ -989,7 +992,7 @@ bool Widget::isFriendWidgetCurActiveWidget(Friend* f)
bool Widget::event(QEvent * e)
{
switch(e->type())
switch (e->type())
{
case QEvent::WindowActivate:
if (activeChatroomWidget != nullptr)
@ -1034,7 +1037,9 @@ void Widget::onUserAwayCheck()
}
}
else if (autoAwayActive)
{
autoAwayActive = false;
}
#endif
}
@ -1077,11 +1082,15 @@ void Widget::onTryCreateTrayIcon()
setHidden(Settings::getInstance().getAutostartInTray());
}
else
{
show();
}
}
else if (!isVisible())
{
show();
}
}
else
{
disconnect(timer, &QTimer::timeout, this, &Widget::onTryCreateTrayIcon);
@ -1133,6 +1142,7 @@ void Widget::onFriendTypingChanged(int friendId, bool isTyping)
Friend* f = FriendList::findFriend(friendId);
if (!f)
return;
f->getChatForm()->setFriendTyping(isTyping);
}
@ -1166,9 +1176,7 @@ void Widget::processOfflineMsgs()
{
QList<Friend*> frnds = FriendList::getAllFriends();
for (Friend *f : frnds)
{
f->getChatForm()->getOfflineMsgEngine()->deliverOfflineMsgs();
}
OfflineMsgEngine::globalMutex.unlock();
}
@ -1178,9 +1186,7 @@ void Widget::clearAllReceipts()
{
QList<Friend*> frnds = FriendList::getAllFriends();
for (Friend *f : frnds)
{
f->getChatForm()->getOfflineMsgEngine()->removeAllReciepts();
}
}
void Widget::reloadTheme()

View File

@ -21,7 +21,8 @@ QList<QString> scanDir(QDir dir)
QList<QString> files;
QStack<QString> stack;
stack.push(dir.absolutePath());
while (!stack.isEmpty()) {
while (!stack.isEmpty())
{
QString sSubdir = stack.pop();
QDir subdir(sSubdir);
@ -29,11 +30,13 @@ QList<QString> scanDir(QDir dir)
QList<QString> sublist = subdir.entryList(QDir::Files);
for (QString& file : sublist)
file = dir.relativeFilePath(sSubdir + '/' + file);
files += sublist;
QFileInfoList infoEntries = subdir.entryInfoList(QStringList(),
QDir::AllDirs | QDir::NoSymLinks | QDir::NoDotAndDotDot);
for (int i = 0; i < infoEntries.size(); i++) {
for (int i = 0; i < infoEntries.size(); i++)
{
QFileInfo& item = infoEntries[i];
stack.push(item.absoluteFilePath());
}
@ -131,4 +134,3 @@ int main(int argc, char* argv[])
flistFile.close();
return 0;
}

View File

@ -43,9 +43,7 @@ Widget::Widget(QWidget *parent) :
// Updates only for supported platforms
if (!supported)
{
fatalError(tr("The qTox updater is not supported on this platform."));
}
QMetaObject::invokeMethod(this, "update", Qt::QueuedConnection);
}
@ -107,6 +105,7 @@ void Widget::update()
QFile updateFlistFile(updateDirStr+"flist");
if (!updateFlistFile.open(QIODevice::ReadOnly))
fatalError(tr("The update is incomplete."));
QByteArray updateFlistData = updateFlistFile.readAll();
updateFlistFile.close();
@ -120,9 +119,8 @@ void Widget::update()
if (!QFile::exists(updateDirStr+fileMeta.installpath))
fatalError(tr("The update is incomplete."));
if (diff.size() == 0){
if (diff.size() == 0)
fatalError(tr("The diff list is empty."));
}
setProgress(5);
@ -137,6 +135,7 @@ void Widget::update()
QFile fileFile(updateDirStr+fileMeta.installpath);
if (!fileFile.open(QIODevice::ReadOnly))
fatalError(tr("Update files are unreadable."));
file.data = fileFile.readAll();
fileFile.close();