From c1e01710b48a89af390c945e18bd3a7e6089207a Mon Sep 17 00:00:00 2001 From: noavarice Date: Sun, 2 Apr 2017 23:37:05 +0300 Subject: [PATCH] refactor: returned correct code format --- src/core/core.cpp | 205 ++++++++++++++--------------------- src/widget/form/chatform.cpp | 80 ++++++-------- 2 files changed, 113 insertions(+), 172 deletions(-) diff --git a/src/core/core.cpp b/src/core/core.cpp index 89366abda..809f40774 100644 --- a/src/core/core.cpp +++ b/src/core/core.cpp @@ -73,9 +73,7 @@ Core::~Core() if (QThread::currentThread() == coreThread) { killTimers(false); } else { - QMetaObject::invokeMethod(this, - "killTimers", - Qt::BlockingQueuedConnection, + QMetaObject::invokeMethod(this, "killTimers", Qt::BlockingQueuedConnection, Q_ARG(bool, false)); } } @@ -378,7 +376,7 @@ bool Core::checkConnection() if (toxConnected && !isConnected) { qDebug() << "Connected to the DHT"; emit connected(); - } else if (!toxConnected && isConnected){ + } else if (!toxConnected && isConnected) { qDebug() << "Disconnected from the DHT"; emit disconnected(); } @@ -403,12 +401,12 @@ void Core::bootstrapDht() int i = 0; static int j = qrand() % listSize; // i think the more we bootstrap, the more we jitter because the more we overwrite nodes - while (i < 2) - { + while (i < 2) { const DhtServer& dhtServer = dhtServerList[j % listSize]; - qDebug() << QString("Connecting to %1:%2 (%3)").arg(QString(dhtServer.address.toLatin1()), - QString::number(dhtServer.port), - dhtServer.name); + QString dhtServerAddress = dhtServer.address.toLatin1(); + QString port = QString::number(dhtServer.port); + QString name = dhtServer.name; + qDebug() << QString("Connecting to %1:%2 (%3)").arg(dhtServerAddress, port, name); QByteArray address = dhtServer.address.toLatin1(); ToxPk pk{dhtServer.userId.toLatin1()}; @@ -427,23 +425,16 @@ void Core::bootstrapDht() } } -void Core::onFriendRequest(Tox*, - const uint8_t* cFriendPk, - const uint8_t* cMessage, - size_t cMessageSize, - void* core) +void Core::onFriendRequest(Tox*, const uint8_t* cFriendPk, const uint8_t* cMessage, + size_t cMessageSize, void* core) { ToxPk friendPk(cFriendPk); QString requestMessage = ToxString(cMessage, cMessageSize).getQString(); emit static_cast(core)->friendRequestReceived(friendPk, requestMessage); } -void Core::onFriendMessage(Tox*, - uint32_t friendId, - TOX_MESSAGE_TYPE type, - const uint8_t* cMessage, - size_t cMessageSize, - void* core) +void Core::onFriendMessage(Tox*, uint32_t friendId, TOX_MESSAGE_TYPE type, const uint8_t* cMessage, + size_t cMessageSize, void* core) { bool isAction = (type == TOX_MESSAGE_TYPE_ACTION); QString msg = ToxString(cMessage, cMessageSize).getQString(); @@ -465,11 +456,8 @@ void Core::onFriendTypingChange(Tox*, uint32_t friendId, bool isTyping, void* co emit static_cast(core)->friendTypingChanged(friendId, isTyping); } -void Core::onStatusMessageChanged(Tox*, - uint32_t friendId, - const uint8_t* cMessage, - size_t cMessageSize, - void* core) +void Core::onStatusMessageChanged(Tox*, uint32_t friendId, const uint8_t* cMessage, + size_t cMessageSize, void* core) { QString message = ToxString(cMessage, cMessageSize).getQString(); emit static_cast(core)->friendStatusMessageChanged(friendId, message); @@ -507,16 +495,12 @@ void Core::onConnectionStatusChanged(Tox*, uint32_t friendId, TOX_CONNECTION sta } } -void Core::onGroupInvite(Tox*, - uint32_t friendId, - TOX_CONFERENCE_TYPE type, - const uint8_t* data, - size_t length, - void* vCore) +void Core::onGroupInvite(Tox*, uint32_t friendId, TOX_CONFERENCE_TYPE type, const uint8_t* data, + size_t length, void* vCore) { Core* core = static_cast(vCore); QByteArray pk((char*)data, length); - switch(type) { + switch (type) { case TOX_CONFERENCE_TYPE_TEXT: qDebug() << QString("Text group invite by %1").arg(friendId); emit core->groupInviteReceived(friendId, type, pk); @@ -532,13 +516,8 @@ void Core::onGroupInvite(Tox*, } } -void Core::onGroupMessage(Tox*, - uint32_t groupId, - uint32_t peerId, - TOX_MESSAGE_TYPE type, - const uint8_t* cMessage, - size_t length, - void* vCore) +void Core::onGroupMessage(Tox*, uint32_t groupId, uint32_t peerId, TOX_MESSAGE_TYPE type, + const uint8_t* cMessage, size_t length, void* vCore) { Core* core = static_cast(vCore); bool isAction = type == TOX_MESSAGE_TYPE_ACTION; @@ -546,11 +525,8 @@ void Core::onGroupMessage(Tox*, emit core->groupMessageReceived(groupId, peerId, message, isAction); } -void Core::onGroupNamelistChange(Tox*, - uint32_t groupId, - uint32_t peerId, - TOX_CONFERENCE_STATE_CHANGE change, - void* core) +void Core::onGroupNamelistChange(Tox*, uint32_t groupId, uint32_t peerId, + TOX_CONFERENCE_STATE_CHANGE change, void* core) { CoreAV* coreAv = static_cast(core)->getAv(); if (change == TOX_CONFERENCE_STATE_CHANGE_PEER_EXIT && coreAv->isGroupAvEnabled(groupId)) { @@ -561,12 +537,8 @@ void Core::onGroupNamelistChange(Tox*, emit static_cast(core)->groupNamelistChanged(groupId, peerId, change); } -void Core::onGroupTitleChange(Tox*, - uint32_t groupId, - uint32_t peerId, - const uint8_t* cTitle, - size_t length, - void* vCore) +void Core::onGroupTitleChange(Tox*, uint32_t groupId, uint32_t peerId, const uint8_t* cTitle, + size_t length, void* vCore) { Core* core = static_cast(vCore); QString author = core->getGroupPeerName(groupId, peerId); @@ -628,13 +600,15 @@ QString Core::getFriendRequestErrorMessage(const ToxId& friendId, const QString& void tryAddFriendRequestToHistory(const ToxId& friendId, const ToxPk& selfPk, const QString& msg) { Profile* profile = Nexus::getProfile(); - if (profile->isHistoryEnabled()) { - QString idStr = friendId.toString(); - QString inviteStr = Core::tr("/me offers friendship, \"%1\"").arg(msg); - QString pkStr = selfPk.toString(); - QDateTime datetime = QDateTime::currentDateTime(); - profile->getHistory()->addNewMessage(idStr, inviteStr, pkStr, datetime, true, QString()); + if (!profile->isHistoryEnabled()) { + return; } + + QString idStr = friendId.toString(); + QString inviteStr = Core::tr("/me offers friendship, \"%1\"").arg(msg); + QString pkStr = selfPk.toString(); + QDateTime datetime = QDateTime::currentDateTime(); + profile->getHistory()->addNewMessage(idStr, inviteStr, pkStr, datetime, true, QString()); } void Core::requestFriendship(const ToxId& friendId, const QString& message) @@ -643,27 +617,24 @@ void Core::requestFriendship(const ToxId& friendId, const QString& message) QString errorMessage = getFriendRequestErrorMessage(friendId, message); if (!errorMessage.isNull()) { emit failedToAddFriend(friendPk, errorMessage); + profile.saveToxSave(); + } + + ToxString cMessage(message); + uint32_t friendNumber = + tox_friend_add(tox, friendId.getBytes(), cMessage.data(), cMessage.size(), nullptr); + if (friendNumber == std::numeric_limits::max()) { + qDebug() << "Failed to request friendship"; + emit failedToAddFriend(friendPk); } else { - ToxString cMessage(message); - uint32_t friendNumber = tox_friend_add(tox, - friendId.getBytes(), - cMessage.data(), - cMessage.size(), - nullptr); - if (friendNumber == std::numeric_limits::max()) { - qDebug() << "Failed to request friendship"; - emit failedToAddFriend(friendPk); - } else { - qDebug() << "Requested friendship of " << friendNumber; - Settings::getInstance().updateFriendAddress(friendId.toString()); + qDebug() << "Requested friendship of " << friendNumber; + Settings::getInstance().updateFriendAddress(friendId.toString()); - // TODO: start: this really shouldn't be in Core - tryAddFriendRequestToHistory(friendId, getSelfPublicKey(), message); - // TODO: end + // TODO: this really shouldn't be in Core + tryAddFriendRequestToHistory(friendId, getSelfPublicKey(), message); - emit friendAdded(friendNumber, friendPk); - emit friendshipChanged(friendNumber); - } + emit friendAdded(friendNumber, friendPk); + emit friendshipChanged(friendNumber); } profile.saveToxSave(); @@ -673,12 +644,8 @@ int Core::sendMessage(uint32_t friendId, const QString& message) { QMutexLocker ml(&messageSendMutex); ToxString cMessage(message); - int receipt = tox_friend_send_message(tox, - friendId, - TOX_MESSAGE_TYPE_NORMAL, - cMessage.data(), - cMessage.size(), - nullptr); + int receipt = tox_friend_send_message(tox, friendId, TOX_MESSAGE_TYPE_NORMAL, cMessage.data(), + cMessage.size(), nullptr); emit messageSentResult(friendId, message, receipt); return receipt; } @@ -687,12 +654,8 @@ int Core::sendAction(uint32_t friendId, const QString& action) { QMutexLocker ml(&messageSendMutex); ToxString cMessage(action); - int receipt = tox_friend_send_message(tox, - friendId, - TOX_MESSAGE_TYPE_ACTION, - cMessage.data(), - cMessage.size(), - nullptr); + int receipt = tox_friend_send_message(tox, friendId, TOX_MESSAGE_TYPE_ACTION, cMessage.data(), + cMessage.size(), nullptr); emit messageSentResult(friendId, action, receipt); return receipt; } @@ -1025,7 +988,7 @@ void Core::setStatus(Status status) QString Core::sanitize(QString name) { // these are pretty much Windows banned filename characters - QList banned {'/', '\\', ':', '<', '>', '"', '|', '?', '*'}; + QList banned{'/', '\\', ':', '<', '>', '"', '|', '?', '*'}; for (QChar c : banned) { name.replace(c, '_'); } @@ -1054,6 +1017,19 @@ QByteArray Core::getToxSaveData() return data; } +// Declared to avoid code duplication +#define GET_FRIEND_PROPERTY(property, function, checkSize)\ + const size_t property##Size = function##_size(tox, ids[i], nullptr);\ + if ((!checkSize || property##Size) && property##Size != SIZE_MAX) {\ + uint8_t* prop = new uint8_t[property##Size];\ + if (function(tox, ids[i], prop, nullptr)) {\ + QString propStr = ToxString(prop, property##Size).getQString();\ + emit friend##property##Changed(ids[i], propStr);\ + }\ + \ + delete[] prop;\ + }\ + void Core::loadFriends() { const uint32_t friendCount = tox_self_get_friend_list_size(tox); @@ -1071,27 +1047,8 @@ void Core::loadFriends() } emit friendAdded(ids[i], ToxPk(friendPk)); - - const size_t nameSize = tox_friend_get_name_size(tox, ids[i], nullptr); - if (nameSize && nameSize != SIZE_MAX) { - uint8_t* name = new uint8_t[nameSize]; - if (tox_friend_get_name(tox, ids[i], name, nullptr)) { - QString username = ToxString(name, nameSize).getQString(); - emit friendUsernameChanged(ids[i], username); - } - delete[] name; - } - - const size_t statusMessageSize = tox_friend_get_status_message_size(tox, ids[i], nullptr); - if (statusMessageSize != SIZE_MAX) { - uint8_t* statusMessage = new uint8_t[statusMessageSize]; - if (tox_friend_get_status_message(tox, ids[i], statusMessage, nullptr)) { - QString statusMsg = ToxString(statusMessage, statusMessageSize).getQString(); - emit friendStatusMessageChanged(ids[i], statusMsg); - } - delete[] statusMessage; - } - + GET_FRIEND_PROPERTY(Username, tox_friend_get_name, true); + GET_FRIEND_PROPERTY(StatusMessage, tox_friend_get_status_message, false); checkLastOnline(ids[i]); } delete[] ids; @@ -1291,28 +1248,28 @@ bool Core::parseConferenceJoinError(TOX_ERR_CONFERENCE_JOIN error) const * * @return Conference number on success, UINT32_MAX on failure. */ -uint32_t Core::joinGroupchat(int32_t friendId, - uint8_t type, - const uint8_t* friendGroupPK, +uint32_t Core::joinGroupchat(int32_t friendId, uint8_t type, const uint8_t* friendGroupPK, uint16_t length) const { - if (type == TOX_CONFERENCE_TYPE_TEXT) { + switch (type) { + case TOX_CONFERENCE_TYPE_TEXT: { qDebug() << QString("Trying to join text groupchat invite sent by friend %1").arg(friendId); TOX_ERR_CONFERENCE_JOIN error; uint32_t groupId = tox_conference_join(tox, friendId, friendGroupPK, length, &error); return parseConferenceJoinError(error) ? groupId : std::numeric_limits::max(); - } else if (type == TOX_CONFERENCE_TYPE_AV) { - qDebug() << QString("Trying to join AV groupchat invite sent by friend %1").arg(friendId); - return toxav_join_av_groupchat(tox, - friendId, - friendGroupPK, - length, - CoreAV::groupCallCallback, - const_cast(this)); - } else { - qWarning() << "joinGroupchat: Unknown groupchat type " << type; - return std::numeric_limits::max(); } + + case TOX_CONFERENCE_TYPE_AV: { + qDebug() << QString("Trying to join AV groupchat invite sent by friend %1").arg(friendId); + return toxav_join_av_groupchat(tox, friendId, friendGroupPK, length, + CoreAV::groupCallCallback, const_cast(this)); + } + + default: + qWarning() << "joinGroupchat: Unknown groupchat type " << type; + } + + return std::numeric_limits::max(); } /** @@ -1452,7 +1409,7 @@ QStringList Core::splitMessage(const QString& message, int maxLen) splitPos = maxLen; if (ba_message[splitPos] & 0x80) { do { - splitPos--; + --splitPos; } while (!(ba_message[splitPos] & 0x40)); } --splitPos; diff --git a/src/widget/form/chatform.cpp b/src/widget/form/chatform.cpp index 659d12e1e..588290852 100644 --- a/src/widget/form/chatform.cpp +++ b/src/widget/form/chatform.cpp @@ -68,13 +68,17 @@ QString statusToString(const Status status) { QString result; switch (status) { - case Status::Online: result = ChatForm::tr("online", "contact status"); + case Status::Online: + result = ChatForm::tr("online", "contact status"); break; - case Status::Away: result = ChatForm::tr("away", "contact status"); + case Status::Away: + result = ChatForm::tr("away", "contact status"); break; - case Status::Busy: result = ChatForm::tr("busy", "contact status"); + case Status::Busy: + result = ChatForm::tr("busy", "contact status"); break; - case Status::Offline: result = ChatForm::tr("offline", "contact status"); + case Status::Offline: + result = ChatForm::tr("offline", "contact status"); break; } return result; @@ -171,12 +175,12 @@ ChatForm::ChatForm(Friend* chatFriend) connect(msgEdit, &ChatTextEdit::enterPressed, this, &ChatForm::onSendTriggered); connect(msgEdit, &ChatTextEdit::textChanged, this, &ChatForm::onTextEditChanged); connect(statusMessageLabel, &CroppingLabel::customContextMenuRequested, this, - [&](const QPoint& pos) { - if (!statusMessageLabel->text().isEmpty()) { - QWidget* sender = static_cast(this->sender()); - statusMessageMenu.exec(sender->mapToGlobal(pos)); - } - }); + [&](const QPoint& pos) { + if (!statusMessageLabel->text().isEmpty()) { + QWidget* sender = static_cast(this->sender()); + statusMessageMenu.exec(sender->mapToGlobal(pos)); + } + }); connect(&typingTimer, &QTimer::timeout, this, [=] { Core::getInstance()->sendTyping(f->getFriendId(), false); @@ -237,12 +241,8 @@ void ChatForm::onTextEditChanged() void ChatForm::onAttachClicked() { - QStringList paths = QFileDialog::getOpenFileNames(this, - tr("Send a file"), - QDir::homePath(), - 0, - 0, - QFileDialog::DontUseNativeDialog); + QStringList paths = QFileDialog::getOpenFileNames(this, tr("Send a file"), QDir::homePath(), 0, + 0, QFileDialog::DontUseNativeDialog); if (paths.isEmpty()) { return; } @@ -252,16 +252,14 @@ void ChatForm::onAttachClicked() QFile file(path); QString fileName = QFileInfo(path).fileName(); if (!file.exists() || !file.open(QIODevice::ReadOnly)) { - QMessageBox::warning(this, - tr("Unable to open"), + QMessageBox::warning(this, tr("Unable to open"), tr("qTox wasn't able to open %1").arg(fileName)); continue; } file.close(); if (file.isSequential()) { - QMessageBox::critical(this, - tr("Bad idea"), + QMessageBox::critical(this, tr("Bad idea"), tr("You're trying to send a sequential file, " "which is not going to work!")); continue; @@ -286,10 +284,8 @@ void ChatForm::startFileSend(ToxFile file) previousId = self; } - insertChatMessage(ChatMessage::createFileTransferMessage(name, - file, - true, - QDateTime::currentDateTime())); + insertChatMessage( + ChatMessage::createFileTransferMessage(name, file, true, QDateTime::currentDateTime())); Widget::getInstance()->updateFriendActivity(f); } @@ -307,10 +303,8 @@ void ChatForm::onFileRecvRequest(ToxFile file) previousId = friendId; } - ChatMessage::Ptr msg = ChatMessage::createFileTransferMessage(name, - file, - false, - QDateTime::currentDateTime()); + ChatMessage::Ptr msg = + ChatMessage::createFileTransferMessage(name, file, false, QDateTime::currentDateTime()); insertChatMessage(msg); ChatLineContentProxy* proxy = static_cast(msg->getContent(1)); @@ -322,7 +316,7 @@ void ChatForm::onFileRecvRequest(ToxFile file) // there is auto-accept for that contact if (!autoAcceptDir.isEmpty()) { tfWidget->autoAcceptTransfer(autoAcceptDir); - // global autosave to global directory + // global autosave to global directory } else if (settings.getAutoSaveEnabled()) { tfWidget->autoAcceptTransfer(settings.getGlobalAutoAcceptDir()); } @@ -348,9 +342,7 @@ void ChatForm::onAvInvite(uint32_t friendId, bool video) uint32_t friendId = f->getFriendId(); qDebug() << "automatic call answer"; CoreAV* coreav = Core::getInstance()->getAv(); - QMetaObject::invokeMethod(coreav, - "answerCall", - Qt::QueuedConnection, + QMetaObject::invokeMethod(coreav, "answerCall", Qt::QueuedConnection, Q_ARG(uint32_t, friendId)); onAvStart(friendId, video); } else { @@ -359,8 +351,7 @@ void ChatForm::onAvInvite(uint32_t friendId, bool video) connect(confirmData, &CallConfirmWidget::accepted, this, &ChatForm::onAnswerCallTriggered); connect(confirmData, &CallConfirmWidget::rejected, this, &ChatForm::onRejectCallTriggered); auto msg = ChatMessage::createChatInfoMessage(tr("%1 calling").arg(displayedName), - ChatMessage::INFO, - QDateTime::currentDateTime()); + ChatMessage::INFO, QDateTime::currentDateTime()); insertChatMessage(msg); Widget::getInstance()->newFriendMessageAlert(friendId, false); Audio& audio = Audio::getInstance(); @@ -410,8 +401,7 @@ void ChatForm::showOutgoingCall(bool video) btn->setObjectName("yellow"); btn->setStyleSheet(Style::getStylesheet(video ? VIDEO_BTN_STYLESHEET : CALL_BTN_STYLESHEET)); btn->setToolTip(video ? tr("Cancel video call") : tr("Cancel audio call")); - addSystemInfoMessage(tr("Calling %1").arg(f->getDisplayedName()), - ChatMessage::INFO, + addSystemInfoMessage(tr("Calling %1").arg(f->getDisplayedName()), ChatMessage::INFO, QDateTime::currentDateTime()); Widget::getInstance()->updateFriendActivity(f); } @@ -519,8 +509,7 @@ void ChatForm::onFileSendFailed(uint32_t friendId, const QString& fname) return; } - addSystemInfoMessage(tr("Failed to send file \"%1\"").arg(fname), - ChatMessage::ERROR, + addSystemInfoMessage(tr("Failed to send file \"%1\"").arg(fname), ChatMessage::ERROR, QDateTime::currentDateTime()); } @@ -545,8 +534,7 @@ void ChatForm::onFriendStatusChanged(uint32_t friendId, Status status) addSystemInfoMessage(tr("%1 is now %2", "e.g. \"Dubslow is now online\"") .arg(f->getDisplayedName()) .arg(fStatus), - ChatMessage::INFO, - QDateTime::currentDateTime()); + ChatMessage::INFO, QDateTime::currentDateTime()); } } @@ -637,8 +625,7 @@ void ChatForm::dropEvent(QDropEvent* ev) info.setFile(url.toLocalFile()); file.setFileName(info.absoluteFilePath()); if (!file.exists() || !file.open(QIODevice::ReadOnly)) { - QMessageBox::warning(this, - tr("Unable to open"), + QMessageBox::warning(this, tr("Unable to open"), tr("qTox wasn't able to open %1").arg(fileName)); continue; } @@ -646,10 +633,8 @@ void ChatForm::dropEvent(QDropEvent* ev) file.close(); if (file.isSequential()) { - QMessageBox::critical(0, - tr("Bad idea"), - tr("You're trying to send a sequential file, " - "which is not going to work!")); + QMessageBox::critical(0, tr("Bad idea"), tr("You're trying to send a sequential file, " + "which is not going to work!")); continue; } @@ -905,8 +890,7 @@ void ChatForm::stopCounter() } QString dhms = secondsToDHMS(timeElapsed.elapsed() / 1000); QString name = f->getDisplayedName(); - addSystemInfoMessage(tr("Call with %1 ended. %2").arg(name, dhms), - ChatMessage::INFO, + addSystemInfoMessage(tr("Call with %1 ended. %2").arg(name, dhms), ChatMessage::INFO, QDateTime::currentDateTime()); callDurationTimer->stop(); callDuration->setText("");