diff --git a/audio/src/backend/alsink.cpp b/audio/src/backend/alsink.cpp index dbf4974370..a3531da16d 100644 --- a/audio/src/backend/alsink.cpp +++ b/audio/src/backend/alsink.cpp @@ -16,7 +16,7 @@ AlSink::~AlSink() { - QMutexLocker locker{&killLock}; + const QMutexLocker locker{&killLock}; // unsubscribe only if not already killed if (!killed) { @@ -27,7 +27,7 @@ AlSink::~AlSink() void AlSink::playAudioBuffer(const int16_t* data, int samples, unsigned channels, int sampleRate) const { - QMutexLocker locker{&killLock}; + const QMutexLocker locker{&killLock}; if (killed) { qCritical() << "Trying to play audio on an invalid sink"; @@ -38,7 +38,7 @@ void AlSink::playAudioBuffer(const int16_t* data, int samples, unsigned channels void AlSink::playMono16Sound(const IAudioSink::Sound& sound) { - QMutexLocker locker{&killLock}; + const QMutexLocker locker{&killLock}; if (killed) { qCritical() << "Trying to play sound on an invalid sink"; @@ -49,7 +49,7 @@ void AlSink::playMono16Sound(const IAudioSink::Sound& sound) void AlSink::startLoop() { - QMutexLocker locker{&killLock}; + const QMutexLocker locker{&killLock}; if (killed) { qCritical() << "Trying to start loop on an invalid sink"; @@ -60,7 +60,7 @@ void AlSink::startLoop() void AlSink::stopLoop() { - QMutexLocker locker{&killLock}; + const QMutexLocker locker{&killLock}; if (killed) { qCritical() << "Trying to stop loop on an invalid sink"; @@ -71,7 +71,7 @@ void AlSink::stopLoop() uint AlSink::getSourceId() const { - uint tmp = sourceId; + const uint tmp = sourceId; return tmp; } @@ -92,7 +92,7 @@ AlSink::AlSink(OpenAL& al, uint sourceId_) AlSink::operator bool() const { - QMutexLocker locker{&killLock}; + const QMutexLocker locker{&killLock}; return !killed; } diff --git a/audio/src/backend/alsource.cpp b/audio/src/backend/alsource.cpp index ae2d769e23..b8c3d76755 100644 --- a/audio/src/backend/alsource.cpp +++ b/audio/src/backend/alsource.cpp @@ -21,7 +21,7 @@ AlSource::AlSource(OpenAL& al) AlSource::~AlSource() { - QMutexLocker locker{&killLock}; + const QMutexLocker locker{&killLock}; // unsubscribe only if not already killed if (!killed) { @@ -32,7 +32,7 @@ AlSource::~AlSource() AlSource::operator bool() const { - QMutexLocker locker{&killLock}; + const QMutexLocker locker{&killLock}; return !killed; } diff --git a/audio/src/backend/openal.cpp b/audio/src/backend/openal.cpp index 2a543af8da..4792da38d8 100644 --- a/audio/src/backend/openal.cpp +++ b/audio/src/backend/openal.cpp @@ -111,7 +111,7 @@ void OpenAL::checkAlcError(ALCdevice* device) noexcept */ void OpenAL::setOutputVolume(qreal volume) { - QMutexLocker locker(&audioLock); + const QMutexLocker locker(&audioLock); volume = std::max(0.0, std::min(volume, 1.0)); @@ -126,7 +126,7 @@ void OpenAL::setOutputVolume(qreal volume) */ qreal OpenAL::minInputGain() const { - QMutexLocker locker(&audioLock); + const QMutexLocker locker(&audioLock); return minInGain; } @@ -137,7 +137,7 @@ qreal OpenAL::minInputGain() const */ qreal OpenAL::maxInputGain() const { - QMutexLocker locker(&audioLock); + const QMutexLocker locker(&audioLock); return maxInGain; } @@ -148,7 +148,7 @@ qreal OpenAL::maxInputGain() const */ qreal OpenAL::minInputThreshold() const { - QMutexLocker locker(&audioLock); + const QMutexLocker locker(&audioLock); return minInThreshold; } @@ -159,7 +159,7 @@ qreal OpenAL::minInputThreshold() const */ qreal OpenAL::maxInputThreshold() const { - QMutexLocker locker(&audioLock); + const QMutexLocker locker(&audioLock); return maxInThreshold; } @@ -208,7 +208,7 @@ bool OpenAL::reinitOutput(const QString& outDevDesc) */ std::unique_ptr OpenAL::makeSink() { - QMutexLocker locker(&audioLock); + const QMutexLocker locker(&audioLock); if (!autoInitOutput()) { qWarning("Failed to subscribe to audio output device."); @@ -236,7 +236,7 @@ std::unique_ptr OpenAL::makeSink() */ void OpenAL::destroySink(AlSink& sink) { - QMutexLocker locker(&audioLock); + const QMutexLocker locker(&audioLock); const auto sinksErased = sinks.erase(&sink); const auto soundSinksErased = soundSinks.erase(&sink); @@ -269,7 +269,7 @@ void OpenAL::destroySink(AlSink& sink) */ std::unique_ptr OpenAL::makeSource() { - QMutexLocker locker(&audioLock); + const QMutexLocker locker(&audioLock); if (!autoInitInput()) { qWarning("Failed to subscribe to audio input device."); @@ -295,7 +295,7 @@ std::unique_ptr OpenAL::makeSource() */ void OpenAL::destroySource(AlSource& source) { - QMutexLocker locker(&audioLock); + const QMutexLocker locker(&audioLock); const auto s = sources.find(&source); if (s == sources.end()) { @@ -348,7 +348,7 @@ bool OpenAL::initInput(const QString& deviceName, uint32_t channels) // TODO: Try to actually detect if our audio source is stereo inputChannels = channels; - int stereoFlag = inputChannels == 1 ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16; + const int stereoFlag = inputChannels == 1 ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16; const int bytesPerSample = 2; const int safetyFactor = 2; // internal OpenAL ring buffer. must be larger than our inputBuffer // to avoid the ring from overwriting itself between captures. @@ -435,7 +435,7 @@ void OpenAL::playMono16Sound(AlSink& sink, const IAudioSink::Sound& sound) return; } - QMutexLocker locker(&audioLock); + const QMutexLocker locker(&audioLock); // interrupt possibly playing sound, we don't buffer here alSourceStop(sourceId); @@ -463,12 +463,12 @@ void OpenAL::playMono16Sound(AlSink& sink, const IAudioSink::Sound& sound) void OpenAL::cleanupSound() { - QMutexLocker locker(&audioLock); + const QMutexLocker locker(&audioLock); auto sinkIt = soundSinks.begin(); while (sinkIt != soundSinks.end()) { auto sink = *sinkIt; - ALuint sourceId = sink->getSourceId(); + const ALuint sourceId = sink->getSourceId(); ALint state = 0; alGetSourcei(sourceId, AL_SOURCE_STATE, &state); @@ -485,7 +485,7 @@ void OpenAL::playAudioBuffer(uint sourceId, const int16_t* data, int samples, un int sampleRate) { assert(channels == 1 || channels == 2); - QMutexLocker locker(&audioLock); + const QMutexLocker locker(&audioLock); if (!(alOutDev && outputInitialized)) return; @@ -643,7 +643,7 @@ void OpenAL::doOutput() */ void OpenAL::doAudio() { - QMutexLocker lock(&audioLock); + const QMutexLocker lock(&audioLock); // Output section does nothing @@ -663,7 +663,7 @@ void OpenAL::captureSamples(ALCdevice* device, int16_t* buffer, ALCsizei samples */ bool OpenAL::isOutputReady() const { - QMutexLocker locker(&audioLock); + const QMutexLocker locker(&audioLock); return alOutDev && outputInitialized; } @@ -721,13 +721,13 @@ void OpenAL::cleanupBuffers(uint sourceId) void OpenAL::startLoop(uint sourceId) { - QMutexLocker locker(&audioLock); + const QMutexLocker locker(&audioLock); alSourcei(sourceId, AL_LOOPING, AL_TRUE); } void OpenAL::stopLoop(uint sourceId) { - QMutexLocker locker(&audioLock); + const QMutexLocker locker(&audioLock); alSourcei(sourceId, AL_LOOPING, AL_FALSE); alSourceStop(sourceId); cleanupBuffers(sourceId); diff --git a/src/appmanager.cpp b/src/appmanager.cpp index 2adc1a7072..dc89f8b36a 100644 --- a/src/appmanager.cpp +++ b/src/appmanager.cpp @@ -57,7 +57,7 @@ void logMessageHandler(QtMsgType type, const QMessageLogContext& ctxt, const QSt return; } - QRegularExpression snoreFilter{QStringLiteral("Snore::Notification.*was already closed")}; + const QRegularExpression snoreFilter{QStringLiteral("Snore::Notification.*was already closed")}; if (type == QtWarningMsg && msg.contains(snoreFilter)) { // snorenotify logs this when we call requestCloseNotification correctly. The behaviour // still works, so we'll just mask the warning for now. The issue has been reported @@ -75,7 +75,7 @@ void logMessageHandler(QtMsgType type, const QMessageLogContext& ctxt, const QSt } // Time should be in UTC to save user privacy on log sharing - QTime time = QDateTime::currentDateTime().toUTC().time(); + const QTime time = QDateTime::currentDateTime().toUTC().time(); QString LogMsg = QString("[%1 UTC] %2:%3 : ").arg(time.toString("HH:mm:ss.zzz")).arg(file).arg(ctxt.line); switch (type) { @@ -99,7 +99,7 @@ void logMessageHandler(QtMsgType type, const QMessageLogContext& ctxt, const QSt } LogMsg += ": " + msg + "\n"; - QByteArray LogMsgBytes = LogMsg.toUtf8(); + const QByteArray LogMsgBytes = LogMsg.toUtf8(); fwrite(LogMsgBytes.constData(), 1, LogMsgBytes.size(), stderr); #ifdef LOG_TO_FILE @@ -178,7 +178,7 @@ int AppManager::run() qWarning() << "Couldn't load font"; } - QString locale = settings->getTranslation(); + const QString locale = settings->getTranslation(); // We need to init the resources in the translations_library explicitely. // See https://doc.qt.io/qt-5/resources.html#using-resources-in-a-library Q_INIT_RESOURCE(translations); @@ -222,10 +222,10 @@ int AppManager::run() } #ifdef LOG_TO_FILE - QString logFileDir = settings->getPaths().getAppCacheDirPath(); + QString const logFileDir = settings->getPaths().getAppCacheDirPath(); QDir(logFileDir).mkpath("."); - QString logfile = logFileDir + "qtox.log"; + const QString logfile = logFileDir + "qtox.log"; FILE* mainLogFilePtr = fopen(logfile.toLocal8Bit().constData(), "a"); // Trim log file if over 1MB @@ -304,7 +304,7 @@ int AppManager::run() } if (doIpc && !ipc->isCurrentOwner()) { - time_t event = ipc->postEvent(eventType, firstParam.toUtf8(), ipcDest); + const time_t event = ipc->postEvent(eventType, firstParam.toUtf8(), ipcDest); // If someone else processed it, we're done here, no need to actually start qTox if (ipc->waitUntilAccepted(event, 2)) { if (eventType == "activate") { @@ -344,7 +344,7 @@ int AppManager::run() nexus->bootstrapWithProfile(profile); } else { nexus->setParser(&parser); - int returnval = nexus->showLogin(profileName); + const int returnval = nexus->showLogin(profileName); if (returnval == QDialog::Rejected) { return -1; } diff --git a/src/chatlog/chatline.cpp b/src/chatlog/chatline.cpp index 736bbd9508..f2b9278800 100644 --- a/src/chatlog/chatline.cpp +++ b/src/chatlog/chatline.cpp @@ -166,7 +166,7 @@ void ChatLine::layout(qreal w, QPointF scenePos) if (varWidth == 0.0) varWidth = 1.0; - qreal leftover = qMax(0.0, width - fixedWidth); + const qreal leftover = qMax(0.0, width - fixedWidth); qreal maxVOffset = 0.0; qreal xOffset = 0.0; @@ -207,7 +207,7 @@ void ChatLine::layout(qreal w, QPointF scenePos) for (int i = 0; i < content.size(); ++i) { // calculate vertical alignment // vertical alignment may depend on width, so we do it in a second pass - qreal yOffset = maxVOffset - content[i]->getAscent(); + const qreal yOffset = maxVOffset - content[i]->getAscent(); // reposition content[i]->setPos(xPos[i], scenePos.y() + yOffset); diff --git a/src/chatlog/chatmessage.cpp b/src/chatlog/chatmessage.cpp index 8bf1faa146..a7d901e213 100644 --- a/src/chatlog/chatmessage.cpp +++ b/src/chatlog/chatmessage.cpp @@ -57,7 +57,7 @@ ChatMessage::Ptr ChatMessage::createChatMessage(const QString& sender, const QSt text = TextFormatter::highlightURI(text); // text styling - Settings::StyleType styleType = settings.getStylePreference(); + const Settings::StyleType styleType = settings.getStylePreference(); if (styleType != Settings::StyleType::NONE) { text = TextFormatter::applyMarkdown(text, styleType == Settings::StyleType::WITH_CHARS); } @@ -79,14 +79,15 @@ ChatMessage::Ptr ChatMessage::createChatMessage(const QString& sender, const QSt } // Note: Eliding cannot be enabled for RichText items. (QTBUG-17207) - QFont baseFont = settings.getChatMessageFont(); + const QFont baseFont = settings.getChatMessageFont(); QFont authorFont = baseFont; if (isMe) authorFont.setBold(true); QColor color = style.getColor(Style::ColorPalette::MainText); if (colorizeName) { - QByteArray hash = QCryptographicHash::hash((sender.toUtf8()), QCryptographicHash::Sha256); + const QByteArray hash = + QCryptographicHash::hash((sender.toUtf8()), QCryptographicHash::Sha256); auto lightness = color.lightnessF(); // Adapt as good as possible to Light/Dark themes lightness = lightness * 0.5f + 0.3f; @@ -133,7 +134,7 @@ ChatMessage::Ptr ChatMessage::createChatInfoMessage(const QString& rawMessage, Settings& settings, Style& style) { ChatMessage::Ptr msg = ChatMessage::Ptr(new ChatMessage(documentCache, settings, style)); - QString text = rawMessage.toHtmlEscaped(); + const QString text = rawMessage.toHtmlEscaped(); QString img; switch (type) { @@ -148,7 +149,7 @@ ChatMessage::Ptr ChatMessage::createChatInfoMessage(const QString& rawMessage, break; } - QFont baseFont = settings.getChatMessageFont(); + const QFont baseFont = settings.getChatMessageFont(); msg->addColumn(new Image(QSize(18, 18), img), ColumnFormat(NAME_COL_WIDTH, ColumnFormat::FixedSize, ColumnFormat::Right)); @@ -169,7 +170,7 @@ ChatMessage::Ptr ChatMessage::createFileTransferMessage(const QString& sender, C { ChatMessage::Ptr msg = ChatMessage::Ptr(new ChatMessage(documentCache, settings, style)); - QFont baseFont = settings.getChatMessageFont(); + const QFont baseFont = settings.getChatMessageFont(); QFont authorFont = baseFont; if (isMe) { authorFont.setBold(true); @@ -193,7 +194,7 @@ ChatMessage::Ptr ChatMessage::createTypingNotification(DocumentCache& documentCa { ChatMessage::Ptr msg = ChatMessage::Ptr(new ChatMessage(documentCache, settings, style)); - QFont baseFont = settings.getChatMessageFont(); + const QFont baseFont = settings.getChatMessageFont(); // Note: "[user]..." is just a placeholder. The actual text is set in // ChatForm::setFriendTyping() @@ -237,7 +238,7 @@ ChatMessage::Ptr ChatMessage::createBusyNotification(DocumentCache& documentCach void ChatMessage::markAsDelivered(const QDateTime& time) { - QFont baseFont = settings.getChatMessageFont(); + const QFont baseFont = settings.getChatMessageFont(); // remove the spinner and replace it by $time replaceContent(2, new Timestamp(time, settings.getTimestampFormat(), baseFont, documentCache, diff --git a/src/chatlog/chatwidget.cpp b/src/chatlog/chatwidget.cpp index 092f824c54..af31f90e76 100644 --- a/src/chatlog/chatwidget.cpp +++ b/src/chatlog/chatwidget.cpp @@ -297,7 +297,7 @@ ChatWidget::~ChatWidget() Translator::unregister(this); // Remove chatlines from scene - for (ChatLine::Ptr l : *chatLineStorage) + for (const ChatLine::Ptr l : *chatLineStorage) l->removeFromScene(); if (busyNotification) @@ -394,7 +394,7 @@ void ChatWidget::mouseMoveEvent(QMouseEvent* ev) { QGraphicsView::mouseMoveEvent(ev); - QPointF scenePos = mapToScene(ev->pos()); + const QPointF scenePos = mapToScene(ev->pos()); if (ev->buttons() & Qt::LeftButton) { // autoscroll @@ -408,8 +408,8 @@ void ChatWidget::mouseMoveEvent(QMouseEvent* ev) // select if (selectionMode == SelectionMode::None && (clickPos - ev->pos()).manhattanLength() > QApplication::startDragDistance()) { - QPointF sceneClickPos = mapToScene(clickPos.toPoint()); - ChatLine::Ptr line = findLineByPosY(scenePos.y()); + const QPointF sceneClickPos = mapToScene(clickPos.toPoint()); + const ChatLine::Ptr line = findLineByPosY(scenePos.y()); ChatLineContent* content = getContentFromPos(sceneClickPos); if (content) { @@ -436,10 +436,10 @@ void ChatWidget::mouseMoveEvent(QMouseEvent* ev) if (selectionMode != SelectionMode::None) { ChatLineContent* content = getContentFromPos(scenePos); - ChatLine::Ptr line = findLineByPosY(scenePos.y()); + const ChatLine::Ptr line = findLineByPosY(scenePos.y()); if (content) { - int col = content->getColumn(); + const int col = content->getColumn(); if (line == selClickedRow && col == selClickedCol) { selectionMode = SelectionMode::Precise; @@ -516,11 +516,11 @@ void ChatWidget::insertChatlines(std::map chatLines) if (chatLines.empty()) return; - bool allLinesAtEnd = !chatLineStorage->hasIndexedMessage() - || chatLines.begin()->first > chatLineStorage->lastIdx(); + const bool allLinesAtEnd = !chatLineStorage->hasIndexedMessage() + || chatLines.begin()->first > chatLineStorage->lastIdx(); auto startLineSize = chatLineStorage->size(); - QGraphicsScene::ItemIndexMethod oldIndexMeth = scene->itemIndexMethod(); + const QGraphicsScene::ItemIndexMethod oldIndexMeth = scene->itemIndexMethod(); scene->setItemIndexMethod(QGraphicsScene::NoIndex); for (auto const& chatLine : chatLines) { @@ -558,7 +558,7 @@ void ChatWidget::insertChatlines(std::map chatLines) // have to rely on the onRenderFinished callback to continue doing any work, // even if all rendering is done synchronously if (allLinesAtEnd) { - bool stickToBtm = stickToBottom(); + const bool stickToBtm = stickToBottom(); // partial refresh layout(startLineSize, chatLineStorage->size(), useableWidth()); @@ -605,7 +605,7 @@ void ChatWidget::startResizeWorker() // switch to busy scene displaying the busy notification if there is a lot // of text to be resized int txt = 0; - for (ChatLine::Ptr line : *chatLineStorage) { + for (const ChatLine::Ptr line : *chatLineStorage) { if (txt > 500000) break; for (ChatLineContent* content : line->content) @@ -622,9 +622,9 @@ void ChatWidget::startResizeWorker() void ChatWidget::mouseDoubleClickEvent(QMouseEvent* ev) { - QPointF scenePos = mapToScene(ev->pos()); + const QPointF scenePos = mapToScene(ev->pos()); ChatLineContent* content = getContentFromPos(scenePos); - ChatLine::Ptr line = findLineByPosY(scenePos.y()); + const ChatLine::Ptr line = findLineByPosY(scenePos.y()); if (content) { content->selectionDoubleClick(scenePos); @@ -662,10 +662,10 @@ QString ChatWidget::getSelectedText() const if (line->content[1]->getText().isEmpty()) return; - QString timestamp = + const QString timestamp = line->content[2]->getText().isEmpty() ? tr("pending") : line->content[2]->getText(); - QString author = line->content[0]->getText(); - QString msg = line->content[1]->getText(); + const QString author = line->content[0]->getText(); + const QString msg = line->content[1]->getText(); out += QString(out.isEmpty() ? QStringLiteral("[%2] %1: %3") : QStringLiteral("\n[%2] %1: %3")) @@ -702,7 +702,7 @@ void ChatWidget::clear() { clearSelection(); - QVector savedLines; + const QVector savedLines; for (auto it = chatLineStorage->begin(); it != chatLineStorage->end();) { if (!isActiveFileTransfer(*it)) { @@ -721,7 +721,7 @@ void ChatWidget::clear() void ChatWidget::copySelectedText(bool toSelectionBuffer) const { - QString text = getSelectedText(); + const QString text = getSelectedText(); QClipboard* clipboard = QApplication::clipboard(); if (clipboard && !text.isNull()) @@ -743,7 +743,7 @@ void ChatWidget::setTypingNotificationName(const QString& displayName) } Text* text = static_cast(typingNotification->getContent(1)); - QString typingDiv = "
%1
"; + const QString typingDiv = "
%1
"; text->setText(typingDiv.arg(tr("%1 is typing").arg(displayName))); updateTypingNotification(); @@ -775,7 +775,7 @@ void ChatWidget::selectAll() void ChatWidget::fontChanged(const QFont& font) { - for (ChatLine::Ptr l : *chatLineStorage) { + for (const ChatLine::Ptr l : *chatLineStorage) { l->fontChanged(font); } } @@ -789,7 +789,7 @@ void ChatWidget::reloadTheme() selGraphItem->setPen(QPen(selectionRectColor.darker(120))); setTypingNotification(); - for (ChatLine::Ptr l : *chatLineStorage) { + for (const ChatLine::Ptr l : *chatLineStorage) { l->reloadTheme(); } } @@ -915,7 +915,7 @@ void ChatWidget::checkVisibility() } // these lines are no longer visible - for (ChatLine::Ptr line : visibleLines) + for (const ChatLine::Ptr line : visibleLines) line->visibilityChanged(false); visibleLines = newVisibleLines; @@ -1110,8 +1110,8 @@ void ChatWidget::renderMessages(ChatLogIdx begin, ChatLogIdx end) auto linesToRender = std::map(); for (auto i = begin; i < end; ++i) { - bool alreadyRendered = chatLineStorage->contains(i); - bool prevIdxRendered = i != begin || chatLineStorage->contains(i - 1); + const bool alreadyRendered = chatLineStorage->contains(i); + const bool prevIdxRendered = i != begin || chatLineStorage->contains(i - 1); auto chatMessage = alreadyRendered ? (*chatLineStorage)[i] : ChatLine::Ptr(); renderItem(chatLog.at(i), needsToHideName(i, prevIdxRendered), colorizeNames, chatMessage); @@ -1266,9 +1266,9 @@ void ChatWidget::handleMultiClickEvent() switch (clickCount) { case 3: - QPointF scenePos = mapToScene(lastClickPos); + const QPointF scenePos = mapToScene(lastClickPos); ChatLineContent* content = getContentFromPos(scenePos); - ChatLine::Ptr line = findLineByPosY(scenePos.y()); + const ChatLine::Ptr line = findLineByPosY(scenePos.y()); if (content) { content->selectionTripleClick(scenePos); @@ -1362,7 +1362,7 @@ void ChatWidget::retranslateUi() bool ChatWidget::isActiveFileTransfer(ChatLine::Ptr l) { - int count = l->getColumnCount(); + const int count = l->getColumnCount(); for (int i = 0; i < count; ++i) { ChatLineContent* content = l->getContent(i); ChatLineContentProxy* proxy = qobject_cast(content); @@ -1393,7 +1393,7 @@ void ChatWidget::renderItem(const ChatLogItem& item, bool hideName, bool coloriz { const auto& sender = item.getSender(); - bool isSelf = sender == core.getSelfPublicKey(); + const bool isSelf = sender == core.getSelfPublicKey(); switch (item.getContentType()) { case ChatLogItem::ContentType::message: { @@ -1470,7 +1470,7 @@ bool ChatWidget::needsToHideName(ChatLogIdx idx, bool prevIdxRendered) const return false; } - qint64 messagesTimeDiff = prevItem.getTimestamp().secsTo(currentItem.getTimestamp()); + const qint64 messagesTimeDiff = prevItem.getTimestamp().secsTo(currentItem.getTimestamp()); return currentItem.getSender() == prevItem.getSender() && messagesTimeDiff < repNameAfter; return false; diff --git a/src/chatlog/content/filetransferwidget.cpp b/src/chatlog/content/filetransferwidget.cpp index 8dd8beff91..706b76b333 100644 --- a/src/chatlog/content/filetransferwidget.cpp +++ b/src/chatlog/content/filetransferwidget.cpp @@ -104,7 +104,7 @@ FileTransferWidget::~FileTransferWidget() bool FileTransferWidget::tryRemoveFile(const QString& filepath) { QFile tmp(filepath); - bool writable = tmp.open(QIODevice::WriteOnly); + const bool writable = tmp.open(QIODevice::WriteOnly); tmp.remove(); return writable; } @@ -178,7 +178,8 @@ void FileTransferWidget::paintEvent(QPaintEvent* event) painter.setRenderHint(QPainter::Antialiasing); painter.setPen(Qt::NoPen); - qreal ratio = static_cast(geometry().height()) / static_cast(geometry().width()); + const qreal ratio = + static_cast(geometry().height()) / static_cast(geometry().width()); const int r = 24; const int buttonFieldWidth = 32; const int lineWidth = 1; @@ -314,8 +315,9 @@ void FileTransferWidget::updateFileProgress(ToxFile const& file) // update UI if (speed > 0) { // ETA - QTime toGo = QTime(0, 0).addSecs(remainingTime); - QString format = toGo.hour() > 0 ? QStringLiteral("hh:mm:ss") : QStringLiteral("mm:ss"); + const QTime toGo = QTime(0, 0).addSecs(remainingTime); + const QString format = + toGo.hour() > 0 ? QStringLiteral("hh:mm:ss") : QStringLiteral("mm:ss"); ui->etaLabel->setText(toGo.toString(format)); } else { ui->etaLabel->setText(""); @@ -459,7 +461,7 @@ void FileTransferWidget::handleButton(QPushButton* btn) } else if (btn->objectName() == "resume") { coreFile.pauseResumeFile(fileInfo.friendId, fileInfo.fileNum); } else if (btn->objectName() == "accept") { - QString path = + const QString path = QFileDialog::getSaveFileName(Q_NULLPTR, tr("Save a file", "Title of the file saving dialog"), settings.getGlobalAutoAcceptDir() + "/" @@ -471,7 +473,7 @@ void FileTransferWidget::handleButton(QPushButton* btn) if (btn->objectName() == "ok" || btn->objectName() == "previewButton") { messageBoxManager.confirmExecutableOpen(QFileInfo(fileInfo.filePath)); } else if (btn->objectName() == "dir") { - QString dirPath = QFileInfo(fileInfo.filePath).dir().path(); + const QString dirPath = QFileInfo(fileInfo.filePath).dir().path(); QDesktopServices::openUrl(QUrl::fromLocalFile(dirPath)); } } @@ -503,7 +505,7 @@ void FileTransferWidget::updateWidget(ToxFile const& file) fileInfo = file; - bool shouldUpdateFileProgress = + const bool shouldUpdateFileProgress = file.status != ToxFile::TRANSMITTING || lastTransmissionUpdate == QTime() || lastTransmissionUpdate.msecsTo(file.progress.lastSampleTime()) > 1000; diff --git a/src/chatlog/content/spinner.cpp b/src/chatlog/content/spinner.cpp index de522677fb..02e6911f8b 100644 --- a/src/chatlog/content/spinner.cpp +++ b/src/chatlog/content/spinner.cpp @@ -46,7 +46,7 @@ void Spinner::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, Q { painter->setClipRect(boundingRect()); - QTransform trans = + const QTransform trans = QTransform().rotate(static_cast(curRot)).translate(-size.width() / 2.0, -size.height() / 2.0); painter->setOpacity(alpha); painter->setTransform(trans, true); @@ -74,7 +74,7 @@ qreal Spinner::getAscent() const void Spinner::timeout() { // Use global time, so the animations are synced - float angle = QTime::currentTime().msecsSinceStartOfDay() / 1000.0f * rotSpeed; + const float angle = QTime::currentTime().msecsSinceStartOfDay() / 1000.0f * rotSpeed; // limit to the range [0.0 - 360.0] curRot = remainderf(angle, 360.0f); diff --git a/src/chatlog/content/text.cpp b/src/chatlog/content/text.cpp index cd76b38999..01bb0fc1cf 100644 --- a/src/chatlog/content/text.cpp +++ b/src/chatlog/content/text.cpp @@ -101,7 +101,7 @@ void Text::selectionMouseMove(QPointF scenePos) if (!doc) return; - int cur = cursorFromPos(scenePos); + const int cur = cursorFromPos(scenePos); if (cur >= 0) { selectionEnd = cur; selectedText = extractSanitizedText(getSelectionStart(), getSelectionEnd()); @@ -112,7 +112,7 @@ void Text::selectionMouseMove(QPointF scenePos) void Text::selectionStarted(QPointF scenePos) { - int cur = cursorFromPos(scenePos); + const int cur = cursorFromPos(scenePos); if (cur >= 0) { selectionEnd = cur; selectionAnchor = cur; @@ -135,7 +135,7 @@ void Text::selectionDoubleClick(QPointF scenePos) if (!doc) return; - int cur = cursorFromPos(scenePos); + const int cur = cursorFromPos(scenePos); if (cur >= 0) { QTextCursor cursor(doc); @@ -156,7 +156,7 @@ void Text::selectionTripleClick(QPointF scenePos) if (!doc) return; - int cur = cursorFromPos(scenePos); + const int cur = cursorFromPos(scenePos); if (cur >= 0) { QTextCursor cursor(doc); @@ -183,7 +183,7 @@ void Text::selectionFocusChanged(bool focusIn) bool Text::isOverSelection(QPointF scenePos) const { - int cur = cursorFromPos(scenePos); + const int cur = cursorFromPos(scenePos); if (getSelectionStart() < cur && getSelectionEnd() >= cur) return true; @@ -269,7 +269,7 @@ void Text::mouseReleaseEvent(QGraphicsSceneMouseEvent* event) if (!doc) return; - QString anchor = doc->documentLayout()->anchorAt(event->pos()); + const QString anchor = doc->documentLayout()->anchorAt(event->pos()); // open anchor in browser if (!anchor.isEmpty()) @@ -281,7 +281,7 @@ void Text::hoverMoveEvent(QGraphicsSceneHoverEvent* event) if (!doc) return; - QString anchor = doc->documentLayout()->anchorAt(event->pos()); + const QString anchor = doc->documentLayout()->anchorAt(event->pos()); if (anchor.isEmpty()) setCursor(Qt::IBeamCursor); @@ -320,8 +320,8 @@ void Text::regenerate() doc->setDefaultFont(defFont); if (elide) { - QFontMetrics metrics = QFontMetrics(defFont); - QString elidedText = metrics.elidedText(text, Qt::ElideRight, qRound(width)); + const QFontMetrics metrics = QFontMetrics(defFont); + const QString elidedText = metrics.elidedText(text, Qt::ElideRight, qRound(width)); doc->setPlainText(elidedText); } else { @@ -402,24 +402,24 @@ QString Text::extractSanitizedText(int from, int to) const QString txt; - QTextBlock begin = doc->findBlock(from); - QTextBlock end = doc->findBlock(to); + const QTextBlock begin = doc->findBlock(from); + const QTextBlock end = doc->findBlock(to); for (QTextBlock block = begin; block != end.next() && block.isValid(); block = block.next()) { for (QTextBlock::Iterator itr = block.begin(); itr != block.end(); ++itr) { int pos = itr.fragment().position(); // fragment position -> position of the first // character in the fragment if (itr.fragment().charFormat().isImageFormat()) { - QTextImageFormat imgFmt = itr.fragment().charFormat().toImageFormat(); - QString key = imgFmt.name(); // img key (eg. key::D for :D) - QString rune = key.mid(4); + const QTextImageFormat imgFmt = itr.fragment().charFormat().toImageFormat(); + const QString key = imgFmt.name(); // img key (eg. key::D for :D) + const QString rune = key.mid(4); if (pos >= from && pos < to) { txt += rune; ++pos; } } else { - for (QChar c : itr.fragment().text()) { + for (const QChar c : itr.fragment().text()) { if (pos >= from && pos < to) txt += c; @@ -440,7 +440,7 @@ QString Text::extractImgTooltip(int pos) const { for (QTextBlock::Iterator itr = doc->firstBlock().begin(); itr != doc->firstBlock().end(); ++itr) { if (itr.fragment().contains(pos) && itr.fragment().charFormat().isImageFormat()) { - QTextImageFormat imgFmt = itr.fragment().charFormat().toImageFormat(); + const QTextImageFormat imgFmt = itr.fragment().charFormat().toImageFormat(); return imgFmt.toolTip(); } } diff --git a/src/chatlog/customtextdocument.cpp b/src/chatlog/customtextdocument.cpp index 1cf1271075..829439bc50 100644 --- a/src/chatlog/customtextdocument.cpp +++ b/src/chatlog/customtextdocument.cpp @@ -24,10 +24,10 @@ CustomTextDocument::CustomTextDocument(SmileyPack& smileyPack_, Settings& settin QVariant CustomTextDocument::loadResource(int type, const QUrl& name) { if (type == QTextDocument::ImageResource && name.scheme() == "key") { - QSize size = QSize(settings.getEmojiFontPointSize(), settings.getEmojiFontPointSize()); - QString fileName = QUrl::fromPercentEncoding(name.toEncoded()).mid(4).toHtmlEscaped(); + const QSize size = QSize(settings.getEmojiFontPointSize(), settings.getEmojiFontPointSize()); + const QString fileName = QUrl::fromPercentEncoding(name.toEncoded()).mid(4).toHtmlEscaped(); - std::shared_ptr icon = smileyPack.getAsIcon(fileName); + const std::shared_ptr icon = smileyPack.getAsIcon(fileName); emoticonIcons.append(icon); return icon->pixmap(size); } diff --git a/src/chatlog/textformatter.cpp b/src/chatlog/textformatter.cpp index 036460a9a7..561b41ee05 100644 --- a/src/chatlog/textformatter.cpp +++ b/src/chatlog/textformatter.cpp @@ -164,9 +164,10 @@ QString highlight(const QString& message, const QVector& pat const QRegularExpressionMatch match = iter.next(); const int uriWithWrapMatch{0}; const int uriWithoutWrapMatch{1}; - MatchingUri matchUri = stripSurroundingChars(match.capturedView(uriWithWrapMatch), - match.capturedStart(uriWithoutWrapMatch) - - match.capturedStart(uriWithWrapMatch)); + const MatchingUri matchUri = + stripSurroundingChars(match.capturedView(uriWithWrapMatch), + match.capturedStart(uriWithoutWrapMatch) + - match.capturedStart(uriWithWrapMatch)); if (!matchUri.valid) { continue; } @@ -227,7 +228,7 @@ QString TextFormatter::applyMarkdown(const QString& message, bool showFormatting int offset = 0; while (iter.hasNext()) { const QRegularExpressionMatch match = iter.next(); - QString captured = match.captured(!showFormattingSymbols); + const QString captured = match.captured(!showFormattingSymbols); if (isTagIntersection(captured)) { continue; } diff --git a/src/core/core.cpp b/src/core/core.cpp index 6688145087..97e6de5a1a 100644 --- a/src/core/core.cpp +++ b/src/core/core.cpp @@ -244,17 +244,17 @@ void Core::onStarted() ASSERT_CORE_THREAD; // One time initialization stuff - QString name = getUsername(); + const QString name = getUsername(); if (!name.isEmpty()) { emit usernameSet(name); } - QString msg = getStatusMessage(); + const QString msg = getStatusMessage(); if (!msg.isEmpty()) { emit statusMessageSet(msg); } - ToxId id = getSelfId(); + const ToxId id = getSelfId(); // Id comes from toxcore, must be valid assert(id.isValid()); emit idSet(id); @@ -318,7 +318,7 @@ CoreExt* Core::getExt() */ void Core::process() { - QMutexLocker ml{&coreLoopLock}; + const QMutexLocker ml{&coreLoopLock}; ASSERT_CORE_THREAD; @@ -338,7 +338,7 @@ void Core::process() tolerance = 3 * CORE_DISCONNECT_TOLERANCE; } - unsigned sleeptime = + const unsigned sleeptime = qMin(tox_iteration_interval(tox.get()), getCoreFile()->corefileIterationInterval()); toxTimer->start(sleeptime); } @@ -407,7 +407,7 @@ void Core::bootstrapDht() continue; } - ToxPk pk{dhtServer.publicKey}; + const ToxPk pk{dhtServer.publicKey}; qDebug() << "Connecting to bootstrap node" << pk.toString(); const uint8_t* pkPtr = pk.getData(); @@ -429,8 +429,8 @@ void Core::onFriendRequest(Tox* tox, const uint8_t* cFriendPk, const uint8_t* cM size_t cMessageSize, void* core) { std::ignore = tox; - ToxPk friendPk(cFriendPk); - QString requestMessage = ToxString(cMessage, cMessageSize).getQString(); + const ToxPk friendPk(cFriendPk); + const QString requestMessage = ToxString(cMessage, cMessageSize).getQString(); emit static_cast(core)->friendRequestReceived(friendPk, requestMessage); } @@ -438,8 +438,8 @@ void Core::onFriendMessage(Tox* tox, uint32_t friendId, Tox_Message_Type type, const uint8_t* cMessage, size_t cMessageSize, void* core) { std::ignore = tox; - bool isAction = (type == TOX_MESSAGE_TYPE_ACTION); - QString msg = ToxString(cMessage, cMessageSize).getQString(); + const bool isAction = (type == TOX_MESSAGE_TYPE_ACTION); + const QString msg = ToxString(cMessage, cMessageSize).getQString(); emit static_cast(core)->friendMessageReceived(friendId, msg, isAction); } @@ -447,7 +447,7 @@ void Core::onFriendNameChange(Tox* tox, uint32_t friendId, const uint8_t* cName, void* core) { std::ignore = tox; - QString newName = ToxString(cName, cNameSize).getQString(); + const QString newName = ToxString(cName, cNameSize).getQString(); // no saveRequest, this callback is called on every connection, not just on name change emit static_cast(core)->friendUsernameChanged(friendId, newName); } @@ -462,7 +462,7 @@ void Core::onStatusMessageChanged(Tox* tox, uint32_t friendId, const uint8_t* cM size_t cMessageSize, void* core) { std::ignore = tox; - QString message = ToxString(cMessage, cMessageSize).getQString(); + const QString message = ToxString(cMessage, cMessageSize).getQString(); // no saveRequest, this callback is called on every connection, not just on name change emit static_cast(core)->friendStatusMessageChanged(friendId, message); } @@ -513,7 +513,7 @@ void Core::onConnectionStatusChanged(Tox* tox, uint32_t friendId, Tox_Connection } // Ignore Online because it will be emited from onUserStatusChanged - bool isOffline = friendStatus == Status::Status::Offline; + const bool isOffline = friendStatus == Status::Status::Offline; if (isOffline) { emit core->friendStatusChanged(friendId, friendStatus); core->checkLastOnline(friendId); @@ -548,8 +548,8 @@ void Core::onGroupMessage(Tox* tox, uint32_t groupId, uint32_t peerId, Tox_Messa { std::ignore = tox; Core* core = static_cast(vCore); - bool isAction = type == TOX_MESSAGE_TYPE_ACTION; - QString message = ToxString(cMessage, length).getQString(); + const bool isAction = type == TOX_MESSAGE_TYPE_ACTION; + const QString message = ToxString(cMessage, length).getQString(); emit core->groupMessageReceived(groupId, peerId, message, isAction); } @@ -605,9 +605,9 @@ void Core::onReadReceiptCallback(Tox* tox, uint32_t friendId, uint32_t receipt, void Core::acceptFriendRequest(const ToxPk& friendPk) { - QMutexLocker ml{&coreLoopLock}; + const QMutexLocker ml{&coreLoopLock}; Tox_Err_Friend_Add error; - uint32_t friendId = tox_friend_add_norequest(tox.get(), friendPk.getData(), &error); + const uint32_t friendId = tox_friend_add_norequest(tox.get(), friendPk.getData(), &error); if (PARSE_ERR(error)) { emit saveRequest(); emit friendAdded(friendId, friendPk); @@ -624,7 +624,7 @@ void Core::acceptFriendRequest(const ToxPk& friendPk) */ QString Core::getFriendRequestErrorMessage(const ToxId& friendId, const QString& message) const { - QMutexLocker ml{&coreLoopLock}; + const QMutexLocker ml{&coreLoopLock}; if (!friendId.isValid()) { return tr("Invalid Tox ID", "Error while sending friend request"); @@ -648,19 +648,19 @@ QString Core::getFriendRequestErrorMessage(const ToxId& friendId, const QString& void Core::requestFriendship(const ToxId& friendId, const QString& message) { - QMutexLocker ml{&coreLoopLock}; + const QMutexLocker ml{&coreLoopLock}; - ToxPk friendPk = friendId.getPublicKey(); - QString errorMessage = getFriendRequestErrorMessage(friendId, message); + const ToxPk friendPk = friendId.getPublicKey(); + const QString errorMessage = getFriendRequestErrorMessage(friendId, message); if (!errorMessage.isNull()) { emit failedToAddFriend(friendPk, errorMessage); emit saveRequest(); return; } - ToxString cMessage(message); + const ToxString cMessage(message); Tox_Err_Friend_Add error; - uint32_t friendNumber = + const uint32_t friendNumber = tox_friend_add(tox.get(), friendId.getBytes(), cMessage.data(), cMessage.size(), &error); if (PARSE_ERR(error)) { qDebug() << "Requested friendship from " << friendNumber; @@ -676,7 +676,7 @@ void Core::requestFriendship(const ToxId& friendId, const QString& message) bool Core::sendMessageWithType(uint32_t friendId, const QString& message, Tox_Message_Type type, ReceiptNum& receipt) { - int size = message.toUtf8().size(); + const int size = message.toUtf8().size(); auto maxSize = static_cast(getMaxMessageSize()); if (size > maxSize) { assert(false); @@ -685,7 +685,7 @@ bool Core::sendMessageWithType(uint32_t friendId, const QString& message, Tox_Me return false; } - ToxString cMessage(message); + const ToxString cMessage(message); Tox_Err_Friend_Send_Message error; receipt = ReceiptNum{tox_friend_send_message(tox.get(), friendId, type, cMessage.data(), cMessage.size(), &error)}; @@ -697,19 +697,19 @@ bool Core::sendMessageWithType(uint32_t friendId, const QString& message, Tox_Me bool Core::sendMessage(uint32_t friendId, const QString& message, ReceiptNum& receipt) { - QMutexLocker ml(&coreLoopLock); + const QMutexLocker ml(&coreLoopLock); return sendMessageWithType(friendId, message, TOX_MESSAGE_TYPE_NORMAL, receipt); } bool Core::sendAction(uint32_t friendId, const QString& action, ReceiptNum& receipt) { - QMutexLocker ml(&coreLoopLock); + const QMutexLocker ml(&coreLoopLock); return sendMessageWithType(friendId, action, TOX_MESSAGE_TYPE_ACTION, receipt); } void Core::sendTyping(uint32_t friendId, bool typing) { - QMutexLocker ml{&coreLoopLock}; + const QMutexLocker ml{&coreLoopLock}; Tox_Err_Set_Typing error; tox_self_set_typing(tox.get(), friendId, typing, &error); @@ -720,9 +720,9 @@ void Core::sendTyping(uint32_t friendId, bool typing) void Core::sendGroupMessageWithType(int groupId, const QString& message, Tox_Message_Type type) { - QMutexLocker ml{&coreLoopLock}; + const QMutexLocker ml{&coreLoopLock}; - int size = message.toUtf8().size(); + const int size = message.toUtf8().size(); auto maxSize = static_cast(getMaxMessageSize()); if (size > maxSize) { qCritical() << "Core::sendMessageWithType called with message of size:" << size @@ -730,7 +730,7 @@ void Core::sendGroupMessageWithType(int groupId, const QString& message, Tox_Mes return; } - ToxString cMsg(message); + const ToxString cMsg(message); Tox_Err_Conference_Send_Message error; tox_conference_send_message(tox.get(), groupId, type, cMsg.data(), cMsg.size(), &error); if (!PARSE_ERR(error)) { @@ -741,23 +741,23 @@ void Core::sendGroupMessageWithType(int groupId, const QString& message, Tox_Mes void Core::sendGroupMessage(int groupId, const QString& message) { - QMutexLocker ml{&coreLoopLock}; + const QMutexLocker ml{&coreLoopLock}; sendGroupMessageWithType(groupId, message, TOX_MESSAGE_TYPE_NORMAL); } void Core::sendGroupAction(int groupId, const QString& message) { - QMutexLocker ml{&coreLoopLock}; + const QMutexLocker ml{&coreLoopLock}; sendGroupMessageWithType(groupId, message, TOX_MESSAGE_TYPE_ACTION); } void Core::changeGroupTitle(int groupId, const QString& title) { - QMutexLocker ml{&coreLoopLock}; + const QMutexLocker ml{&coreLoopLock}; - ToxString cTitle(title); + const ToxString cTitle(title); Tox_Err_Conference_Title error; tox_conference_set_title(tox.get(), groupId, cTitle.data(), cTitle.size(), &error); if (PARSE_ERR(error)) { @@ -768,7 +768,7 @@ void Core::changeGroupTitle(int groupId, const QString& title) void Core::removeFriend(uint32_t friendId) { - QMutexLocker ml{&coreLoopLock}; + const QMutexLocker ml{&coreLoopLock}; Tox_Err_Friend_Delete error; tox_friend_delete(tox.get(), friendId, &error); @@ -783,7 +783,7 @@ void Core::removeFriend(uint32_t friendId) void Core::removeGroup(int groupId) { - QMutexLocker ml{&coreLoopLock}; + const QMutexLocker ml{&coreLoopLock}; Tox_Err_Conference_Delete error; tox_conference_delete(tox.get(), groupId, &error); @@ -806,14 +806,14 @@ void Core::removeGroup(int groupId) */ QString Core::getUsername() const { - QMutexLocker ml{&coreLoopLock}; + const QMutexLocker ml{&coreLoopLock}; QString sname; if (!tox) { return sname; } - int size = tox_self_get_name_size(tox.get()); + const int size = tox_self_get_name_size(tox.get()); if (!size) { return {}; } @@ -824,13 +824,13 @@ QString Core::getUsername() const void Core::setUsername(const QString& username) { - QMutexLocker ml{&coreLoopLock}; + const QMutexLocker ml{&coreLoopLock}; if (username == getUsername()) { return; } - ToxString cUsername(username); + const ToxString cUsername(username); Tox_Err_Set_Info error; tox_self_set_name(tox.get(), cUsername.data(), cUsername.size(), &error); if (!PARSE_ERR(error)) { @@ -847,7 +847,7 @@ void Core::setUsername(const QString& username) */ ToxId Core::getSelfId() const { - QMutexLocker ml{&coreLoopLock}; + const QMutexLocker ml{&coreLoopLock}; uint8_t friendId[TOX_ADDRESS_SIZE] = {0x00}; tox_self_get_address(tox.get(), friendId); @@ -860,7 +860,7 @@ ToxId Core::getSelfId() const */ ToxPk Core::getSelfPublicKey() const { - QMutexLocker ml{&coreLoopLock}; + const QMutexLocker ml{&coreLoopLock}; uint8_t selfPk[TOX_PUBLIC_KEY_SIZE] = {0x00}; tox_self_get_public_key(tox.get(), selfPk); @@ -869,7 +869,7 @@ ToxPk Core::getSelfPublicKey() const QByteArray Core::getSelfDhtId() const { - QMutexLocker ml{&coreLoopLock}; + const QMutexLocker ml{&coreLoopLock}; QByteArray dhtKey(TOX_PUBLIC_KEY_SIZE, 0x00); tox_self_get_dht_id(tox.get(), reinterpret_cast(dhtKey.data())); return dhtKey; @@ -877,7 +877,7 @@ QByteArray Core::getSelfDhtId() const int Core::getSelfUdpPort() const { - QMutexLocker ml{&coreLoopLock}; + const QMutexLocker ml{&coreLoopLock}; Tox_Err_Get_Port error; auto port = tox_self_get_udp_port(tox.get(), &error); if (!PARSE_ERR(error)) { @@ -891,11 +891,11 @@ int Core::getSelfUdpPort() const */ QString Core::getStatusMessage() const { - QMutexLocker ml{&coreLoopLock}; + const QMutexLocker ml{&coreLoopLock}; assert(tox != nullptr); - size_t size = tox_self_get_status_message_size(tox.get()); + const size_t size = tox_self_get_status_message_size(tox.get()); if (!size) { return {}; } @@ -909,20 +909,20 @@ QString Core::getStatusMessage() const */ Status::Status Core::getStatus() const { - QMutexLocker ml{&coreLoopLock}; + const QMutexLocker ml{&coreLoopLock}; return static_cast(tox_self_get_status(tox.get())); } void Core::setStatusMessage(const QString& message) { - QMutexLocker ml{&coreLoopLock}; + const QMutexLocker ml{&coreLoopLock}; if (message == getStatusMessage()) { return; } - ToxString cMessage(message); + const ToxString cMessage(message); Tox_Err_Set_Info error; tox_self_set_status_message(tox.get(), cMessage.data(), cMessage.size(), &error); if (!PARSE_ERR(error)) { @@ -936,7 +936,7 @@ void Core::setStatusMessage(const QString& message) void Core::setStatus(Status::Status status) { - QMutexLocker ml{&coreLoopLock}; + const QMutexLocker ml{&coreLoopLock}; Tox_User_Status userstatus; switch (status) { @@ -967,9 +967,9 @@ void Core::setStatus(Status::Status status) */ QByteArray Core::getToxSaveData() { - QMutexLocker ml{&coreLoopLock}; + const QMutexLocker ml{&coreLoopLock}; - uint32_t fileSize = tox_get_savedata_size(tox.get()); + const uint32_t fileSize = tox_get_savedata_size(tox.get()); QByteArray data; data.resize(fileSize); tox_get_savedata(tox.get(), reinterpret_cast(data.data())); @@ -978,7 +978,7 @@ QByteArray Core::getToxSaveData() void Core::loadFriends() { - QMutexLocker ml{&coreLoopLock}; + const QMutexLocker ml{&coreLoopLock}; const size_t friendCount = tox_self_get_friend_list_size(tox.get()); if (friendCount == 0) { @@ -997,11 +997,12 @@ void Core::loadFriends() emit friendAdded(ids[i], ToxPk(friendPk)); emit friendUsernameChanged(ids[i], getFriendUsername(ids[i])); Tox_Err_Friend_Query queryError; - size_t statusMessageSize = tox_friend_get_status_message_size(tox.get(), ids[i], &queryError); + const size_t statusMessageSize = + tox_friend_get_status_message_size(tox.get(), ids[i], &queryError); if (PARSE_ERR(queryError) && statusMessageSize) { std::vector messageData(statusMessageSize); tox_friend_get_status_message(tox.get(), ids[i], messageData.data(), &queryError); - QString friendStatusMessage = + const QString friendStatusMessage = ToxString(messageData.data(), statusMessageSize).getQString(); emit friendStatusMessageChanged(ids[i], friendStatusMessage); } @@ -1011,7 +1012,7 @@ void Core::loadFriends() void Core::loadGroups() { - QMutexLocker ml{&coreLoopLock}; + const QMutexLocker ml{&coreLoopLock}; const size_t groupCount = tox_conference_get_chatlist_size(tox.get()); if (groupCount == 0) { @@ -1025,7 +1026,7 @@ void Core::loadGroups() Tox_Err_Conference_Title error; QString name; const auto groupNumber = groupNumbers[i]; - size_t titleSize = tox_conference_get_title_size(tox.get(), groupNumber, &error); + const size_t titleSize = tox_conference_get_title_size(tox.get(), groupNumber, &error); const GroupId persistentId = getGroupPersistentId(groupNumber); const QString defaultName = tr("Groupchat %1").arg(persistentId.toString().left(8)); if (PARSE_ERR(error) || !titleSize) { @@ -1050,7 +1051,7 @@ void Core::loadGroups() void Core::checkLastOnline(uint32_t friendId) { - QMutexLocker ml{&coreLoopLock}; + const QMutexLocker ml{&coreLoopLock}; Tox_Err_Friend_Get_Last_Online error; const uint64_t lastOnline = tox_friend_get_last_online(tox.get(), friendId, &error); @@ -1064,7 +1065,7 @@ void Core::checkLastOnline(uint32_t friendId) */ QVector Core::getFriendList() const { - QMutexLocker ml{&coreLoopLock}; + const QMutexLocker ml{&coreLoopLock}; QVector friends; friends.resize(tox_self_get_friend_list_size(tox.get())); @@ -1074,7 +1075,7 @@ QVector Core::getFriendList() const GroupId Core::getGroupPersistentId(uint32_t groupNumber) const { - QMutexLocker ml{&coreLoopLock}; + const QMutexLocker ml{&coreLoopLock}; std::vector idBuff(TOX_CONFERENCE_UID_SIZE); if (tox_conference_get_id(tox.get(), groupNumber, idBuff.data())) { @@ -1091,10 +1092,10 @@ GroupId Core::getGroupPersistentId(uint32_t groupNumber) const */ uint32_t Core::getGroupNumberPeers(int groupId) const { - QMutexLocker ml{&coreLoopLock}; + const QMutexLocker ml{&coreLoopLock}; Tox_Err_Conference_Peer_Query error; - uint32_t count = tox_conference_peer_count(tox.get(), groupId, &error); + const uint32_t count = tox_conference_peer_count(tox.get(), groupId, &error); if (!PARSE_ERR(error)) { return std::numeric_limits::max(); } @@ -1107,10 +1108,10 @@ uint32_t Core::getGroupNumberPeers(int groupId) const */ QString Core::getGroupPeerName(int groupId, int peerId) const { - QMutexLocker ml{&coreLoopLock}; + const QMutexLocker ml{&coreLoopLock}; Tox_Err_Conference_Peer_Query error; - size_t length = tox_conference_peer_get_name_size(tox.get(), groupId, peerId, &error); + const size_t length = tox_conference_peer_get_name_size(tox.get(), groupId, peerId, &error); if (!PARSE_ERR(error) || !length) { return QString{}; } @@ -1129,7 +1130,7 @@ QString Core::getGroupPeerName(int groupId, int peerId) const */ ToxPk Core::getGroupPeerPk(int groupId, int peerId) const { - QMutexLocker ml{&coreLoopLock}; + const QMutexLocker ml{&coreLoopLock}; uint8_t friendPk[TOX_PUBLIC_KEY_SIZE] = {0x00}; Tox_Err_Conference_Peer_Query error; @@ -1146,11 +1147,11 @@ ToxPk Core::getGroupPeerPk(int groupId, int peerId) const */ QStringList Core::getGroupPeerNames(int groupId) const { - QMutexLocker ml{&coreLoopLock}; + const QMutexLocker ml{&coreLoopLock}; assert(tox != nullptr); - uint32_t nPeers = getGroupNumberPeers(groupId); + const uint32_t nPeers = getGroupNumberPeers(groupId); if (nPeers == std::numeric_limits::max()) { qWarning() << "getGroupPeerNames: Unable to get number of peers"; return {}; @@ -1159,7 +1160,7 @@ QStringList Core::getGroupPeerNames(int groupId) const QStringList names; for (int i = 0; i < static_cast(nPeers); ++i) { Tox_Err_Conference_Peer_Query error; - size_t length = tox_conference_peer_get_name_size(tox.get(), groupId, i, &error); + const size_t length = tox_conference_peer_get_name_size(tox.get(), groupId, i, &error); if (!PARSE_ERR(error) || !length) { names.append(QString()); @@ -1187,9 +1188,9 @@ QStringList Core::getGroupPeerNames(int groupId) const */ bool Core::getGroupAvEnabled(int groupId) const { - QMutexLocker ml{&coreLoopLock}; + const QMutexLocker ml{&coreLoopLock}; Tox_Err_Conference_Get_Type error; - Tox_Conference_Type type = tox_conference_get_type(tox.get(), groupId, &error); + const Tox_Conference_Type type = tox_conference_get_type(tox.get(), groupId, &error); PARSE_ERR(error); // would be nice to indicate to caller that we don't actually know.. return type == TOX_CONFERENCE_TYPE_AV; @@ -1203,7 +1204,7 @@ bool Core::getGroupAvEnabled(int groupId) const */ uint32_t Core::joinGroupchat(const GroupInvite& inviteInfo) { - QMutexLocker ml{&coreLoopLock}; + const QMutexLocker ml{&coreLoopLock}; const uint32_t friendId = inviteInfo.getFriendId(); const uint8_t confType = inviteInfo.getType(); @@ -1239,7 +1240,7 @@ uint32_t Core::joinGroupchat(const GroupInvite& inviteInfo) void Core::groupInviteFriend(uint32_t friendId, int groupId) { - QMutexLocker ml{&coreLoopLock}; + const QMutexLocker ml{&coreLoopLock}; Tox_Err_Conference_Invite error; tox_conference_invite(tox.get(), friendId, groupId, &error); @@ -1248,11 +1249,11 @@ void Core::groupInviteFriend(uint32_t friendId, int groupId) int Core::createGroup(uint8_t type) { - QMutexLocker ml{&coreLoopLock}; + const QMutexLocker ml{&coreLoopLock}; if (type == TOX_CONFERENCE_TYPE_TEXT) { Tox_Err_Conference_New error; - uint32_t groupId = tox_conference_new(tox.get(), &error); + const uint32_t groupId = tox_conference_new(tox.get(), &error); if (PARSE_ERR(error)) { emit saveRequest(); emit emptyGroupCreated(groupId, getGroupPersistentId(groupId)); @@ -1263,7 +1264,7 @@ int Core::createGroup(uint8_t type) } else if (type == TOX_CONFERENCE_TYPE_AV) { // unlike tox_conference_new, toxav_add_av_groupchat does not have an error enum, so -1 // group number is our only indication of an error - int groupId = toxav_add_av_groupchat(tox.get(), CoreAV::groupCallCallback, this); + const int groupId = toxav_add_av_groupchat(tox.get(), CoreAV::groupCallCallback, this); if (groupId != -1) { emit saveRequest(); emit emptyGroupCreated(groupId, getGroupPersistentId(groupId)); @@ -1282,10 +1283,10 @@ int Core::createGroup(uint8_t type) */ bool Core::isFriendOnline(uint32_t friendId) const { - QMutexLocker ml{&coreLoopLock}; + const QMutexLocker ml{&coreLoopLock}; Tox_Err_Friend_Query error; - Tox_Connection connection = tox_friend_get_connection_status(tox.get(), friendId, &error); + const Tox_Connection connection = tox_friend_get_connection_status(tox.get(), friendId, &error); PARSE_ERR(error); return connection != TOX_CONNECTION_NONE; } @@ -1295,7 +1296,7 @@ bool Core::isFriendOnline(uint32_t friendId) const */ bool Core::hasFriendWithPublicKey(const ToxPk& publicKey) const { - QMutexLocker ml{&coreLoopLock}; + const QMutexLocker ml{&coreLoopLock}; if (publicKey.isEmpty()) { return false; @@ -1311,7 +1312,7 @@ bool Core::hasFriendWithPublicKey(const ToxPk& publicKey) const */ ToxPk Core::getFriendPublicKey(uint32_t friendNumber) const { - QMutexLocker ml{&coreLoopLock}; + const QMutexLocker ml{&coreLoopLock}; uint8_t rawid[TOX_PUBLIC_KEY_SIZE]; Tox_Err_Friend_Get_Public_Key error; @@ -1329,10 +1330,10 @@ ToxPk Core::getFriendPublicKey(uint32_t friendNumber) const */ QString Core::getFriendUsername(uint32_t friendnumber) const { - QMutexLocker ml{&coreLoopLock}; + const QMutexLocker ml{&coreLoopLock}; Tox_Err_Friend_Query error; - size_t nameSize = tox_friend_get_name_size(tox.get(), friendnumber, &error); + const size_t nameSize = tox_friend_get_name_size(tox.get(), friendnumber, &error); if (!PARSE_ERR(error) || !nameSize) { return QString(); } @@ -1362,10 +1363,10 @@ uint64_t Core::getMaxMessageSize() const QString Core::getPeerName(const ToxPk& id) const { - QMutexLocker ml{&coreLoopLock}; + const QMutexLocker ml{&coreLoopLock}; Tox_Err_Friend_By_Public_Key keyError; - uint32_t friendId = tox_friend_by_public_key(tox.get(), id.getData(), &keyError); + const uint32_t friendId = tox_friend_by_public_key(tox.get(), id.getData(), &keyError); if (!PARSE_ERR(keyError)) { qWarning() << "getPeerName: No such peer"; return {}; @@ -1393,7 +1394,7 @@ QString Core::getPeerName(const ToxPk& id) const */ void Core::setNospam(uint32_t nospam) { - QMutexLocker ml{&coreLoopLock}; + const QMutexLocker ml{&coreLoopLock}; tox_self_set_nospam(tox.get(), nospam); emit idSet(getSelfId()); diff --git a/src/core/coreav.cpp b/src/core/coreav.cpp index c8e27c7bdf..e757633205 100644 --- a/src/core/coreav.cpp +++ b/src/core/coreav.cpp @@ -188,7 +188,7 @@ void CoreAV::process() */ bool CoreAV::isCallStarted(const Friend* f) const { - QReadLocker locker{&callsLock}; + const QReadLocker locker{&callsLock}; return f && (calls.find(f->getId()) != calls.end()); } @@ -199,7 +199,7 @@ bool CoreAV::isCallStarted(const Friend* f) const */ bool CoreAV::isCallStarted(const Group* g) const { - QReadLocker locker{&callsLock}; + const QReadLocker locker{&callsLock}; return g && (groupCalls.find(g->getId()) != groupCalls.end()); } @@ -210,7 +210,7 @@ bool CoreAV::isCallStarted(const Group* g) const */ bool CoreAV::isCallActive(const Friend* f) const { - QReadLocker locker{&callsLock}; + const QReadLocker locker{&callsLock}; auto it = calls.find(f->getId()); if (it == calls.end()) { return false; @@ -225,7 +225,7 @@ bool CoreAV::isCallActive(const Friend* f) const */ bool CoreAV::isCallActive(const Group* g) const { - QReadLocker locker{&callsLock}; + const QReadLocker locker{&callsLock}; auto it = groupCalls.find(g->getId()); if (it == groupCalls.end()) { return false; @@ -235,15 +235,15 @@ bool CoreAV::isCallActive(const Group* g) const bool CoreAV::isCallVideoEnabled(const Friend* f) const { - QReadLocker locker{&callsLock}; + const QReadLocker locker{&callsLock}; auto it = calls.find(f->getId()); return isCallStarted(f) && it->second->getVideoEnabled(); } bool CoreAV::answerCall(uint32_t friendNum, bool video) { - QWriteLocker locker{&callsLock}; - QMutexLocker coreLocker{&coreLock}; + const QWriteLocker locker{&callsLock}; + const QMutexLocker coreLocker{&coreLock}; qDebug() << QString("Answering call %1").arg(friendNum); auto it = calls.find(friendNum); @@ -266,8 +266,8 @@ bool CoreAV::answerCall(uint32_t friendNum, bool video) bool CoreAV::startCall(uint32_t friendNum, bool video) { - QWriteLocker locker{&callsLock}; - QMutexLocker coreLocker{&coreLock}; + const QWriteLocker locker{&callsLock}; + const QMutexLocker coreLocker{&coreLock}; qDebug() << QString("Starting call with %1").arg(friendNum); auto it = calls.find(friendNum); @@ -276,7 +276,7 @@ bool CoreAV::startCall(uint32_t friendNum, bool video) return false; } - uint32_t videoBitrate = video ? VIDEO_DEFAULT_BITRATE : 0; + const uint32_t videoBitrate = video ? VIDEO_DEFAULT_BITRATE : 0; Toxav_Err_Call err; toxav_call(toxav.get(), friendNum, audioSettings.getAudioBitrate(), videoBitrate, &err); if (!PARSE_ERR(err)) { @@ -297,7 +297,7 @@ bool CoreAV::startCall(uint32_t friendNum, bool video) bool CoreAV::cancelCall(uint32_t friendNum) { QWriteLocker locker{&callsLock}; - QMutexLocker coreLocker{&coreLock}; + const QMutexLocker coreLocker{&coreLock}; qDebug() << QString("Cancelling call with %1").arg(friendNum); Toxav_Err_Call_Control err; @@ -315,7 +315,7 @@ bool CoreAV::cancelCall(uint32_t friendNum) void CoreAV::timeoutCall(uint32_t friendNum) { - QWriteLocker locker{&callsLock}; + const QWriteLocker locker{&callsLock}; if (!cancelCall(friendNum)) { qWarning() << QString("Failed to timeout call with %1").arg(friendNum); @@ -336,7 +336,7 @@ void CoreAV::timeoutCall(uint32_t friendNum) bool CoreAV::sendCallAudio(uint32_t callId, const int16_t* pcm, size_t samples, uint8_t chans, uint32_t rate) const { - QReadLocker locker{&callsLock}; + const QReadLocker locker{&callsLock}; auto it = calls.find(callId); if (it == calls.end()) { @@ -372,7 +372,7 @@ bool CoreAV::sendCallAudio(uint32_t callId, const int16_t* pcm, size_t samples, void CoreAV::sendCallVideo(uint32_t callId, std::shared_ptr vframe) { - QWriteLocker locker{&callsLock}; + const QWriteLocker locker{&callsLock}; // We might be running in the FFmpeg thread and holding the CameraSource lock // So be careful not to deadlock with anything while toxav locks in toxav_video_send_frame @@ -390,7 +390,7 @@ void CoreAV::sendCallVideo(uint32_t callId, std::shared_ptr vframe) if (call.getNullVideoBitrate()) { qDebug() << "Restarting video stream to friend" << callId; - QMutexLocker coreLocker{&coreLock}; + const QMutexLocker coreLocker{&coreLock}; Toxav_Err_Bit_Rate_Set err; toxav_video_set_bit_rate(toxav.get(), callId, VIDEO_DEFAULT_BITRATE, &err); if (!PARSE_ERR(err)) { @@ -399,7 +399,7 @@ void CoreAV::sendCallVideo(uint32_t callId, std::shared_ptr vframe) call.setNullVideoBitrate(false); } - ToxYUVFrame frame = vframe->toToxYUVFrame(); + const ToxYUVFrame frame = vframe->toToxYUVFrame(); if (!frame) { return; @@ -431,7 +431,7 @@ void CoreAV::sendCallVideo(uint32_t callId, std::shared_ptr vframe) */ void CoreAV::toggleMuteCallInput(const Friend* f) { - QWriteLocker locker{&callsLock}; + const QWriteLocker locker{&callsLock}; auto it = calls.find(f->getId()); if (f && (it != calls.end())) { @@ -446,7 +446,7 @@ void CoreAV::toggleMuteCallInput(const Friend* f) */ void CoreAV::toggleMuteCallOutput(const Friend* f) { - QWriteLocker locker{&callsLock}; + const QWriteLocker locker{&callsLock}; auto it = calls.find(f->getId()); if (f && (it != calls.end())) { @@ -482,7 +482,7 @@ void CoreAV::groupCallCallback(void* tox, uint32_t group, uint32_t peer, const i Core* c = static_cast(core); CoreAV* cav = c->getAv(); - QReadLocker locker{&cav->callsLock}; + const QReadLocker locker{&cav->callsLock}; const ToxPk peerPk = c->getGroupPeerPk(group, peer); // don't play the audio if it comes from a muted peer @@ -513,7 +513,7 @@ void CoreAV::groupCallCallback(void* tox, uint32_t group, uint32_t peer, const i */ void CoreAV::invalidateGroupCallPeerSource(const Group& group, ToxPk peerPk) { - QWriteLocker locker{&callsLock}; + const QWriteLocker locker{&callsLock}; auto it = groupCalls.find(group.getId()); if (it == groupCalls.end()) { @@ -529,7 +529,7 @@ void CoreAV::invalidateGroupCallPeerSource(const Group& group, ToxPk peerPk) */ VideoSource* CoreAV::getVideoSourceFromCall(int friendNum) const { - QReadLocker locker{&callsLock}; + const QReadLocker locker{&callsLock}; auto it = calls.find(friendNum); if (it == calls.end()) { @@ -547,7 +547,7 @@ VideoSource* CoreAV::getVideoSourceFromCall(int friendNum) const */ void CoreAV::joinGroupCall(const Group& group) { - QWriteLocker locker{&callsLock}; + const QWriteLocker locker{&callsLock}; qDebug() << QString("Joining group call %1").arg(group.getId()); @@ -573,7 +573,7 @@ void CoreAV::joinGroupCall(const Group& group) */ void CoreAV::leaveGroupCall(int groupNum) { - QWriteLocker locker{&callsLock}; + const QWriteLocker locker{&callsLock}; qDebug() << QString("Leaving group call %1").arg(groupNum); @@ -583,9 +583,9 @@ void CoreAV::leaveGroupCall(int groupNum) bool CoreAV::sendGroupCallAudio(int groupNum, const int16_t* pcm, size_t samples, uint8_t chans, uint32_t rate) const { - QReadLocker locker{&callsLock}; + const QReadLocker locker{&callsLock}; - std::map::const_iterator it = groupCalls.find(groupNum); + const std::map::const_iterator it = groupCalls.find(groupNum); if (it == groupCalls.end()) { return false; } @@ -607,7 +607,7 @@ bool CoreAV::sendGroupCallAudio(int groupNum, const int16_t* pcm, size_t samples */ void CoreAV::muteCallInput(const Group* g, bool mute) { - QWriteLocker locker{&callsLock}; + const QWriteLocker locker{&callsLock}; auto it = groupCalls.find(g->getId()); if (g && (it != groupCalls.end())) { @@ -622,7 +622,7 @@ void CoreAV::muteCallInput(const Group* g, bool mute) */ void CoreAV::muteCallOutput(const Group* g, bool mute) { - QWriteLocker locker{&callsLock}; + const QWriteLocker locker{&callsLock}; auto it = groupCalls.find(g->getId()); if (g && (it != groupCalls.end())) { @@ -637,7 +637,7 @@ void CoreAV::muteCallOutput(const Group* g, bool mute) */ bool CoreAV::isGroupCallInputMuted(const Group* g) const { - QReadLocker locker{&callsLock}; + const QReadLocker locker{&callsLock}; if (!g) { return false; @@ -655,7 +655,7 @@ bool CoreAV::isGroupCallInputMuted(const Group* g) const */ bool CoreAV::isGroupCallOutputMuted(const Group* g) const { - QReadLocker locker{&callsLock}; + const QReadLocker locker{&callsLock}; if (!g) { return false; @@ -673,7 +673,7 @@ bool CoreAV::isGroupCallOutputMuted(const Group* g) const */ bool CoreAV::isCallInputMuted(const Friend* f) const { - QReadLocker locker{&callsLock}; + const QReadLocker locker{&callsLock}; if (!f) { return false; @@ -690,7 +690,7 @@ bool CoreAV::isCallInputMuted(const Friend* f) const */ bool CoreAV::isCallOutputMuted(const Friend* f) const { - QReadLocker locker{&callsLock}; + const QReadLocker locker{&callsLock}; if (!f) { return false; @@ -706,7 +706,7 @@ bool CoreAV::isCallOutputMuted(const Friend* f) const */ void CoreAV::sendNoVideo() { - QWriteLocker locker{&callsLock}; + const QWriteLocker locker{&callsLock}; // We don't change the audio bitrate, but we signal that we're not sending video anymore qDebug() << "CoreAV: Signaling end of video sending"; @@ -789,7 +789,7 @@ void CoreAV::stateCallback(ToxAV* toxav, uint32_t friendNum, uint32_t state, voi // If our state was null, we started the call and were still ringing if (!call.getState() && state) { call.setActive(true); - bool videoEnabled = call.getVideoEnabled(); + const bool videoEnabled = call.getVideoEnabled(); call.setState(static_cast(state)); locker.unlock(); emit self->avStart(friendNum, videoEnabled); @@ -857,14 +857,14 @@ void CoreAV::audioFrameCallback(ToxAV* toxAV, uint32_t friendNum, const int16_t* CoreAV* self = static_cast(vSelf); // This callback should come from the CoreAV thread assert(QThread::currentThread() == self->coreavThread.get()); - QReadLocker locker{&self->callsLock}; + const QReadLocker locker{&self->callsLock}; auto it = self->calls.find(friendNum); if (it == self->calls.end()) { return; } - ToxFriendCall& call = *it->second; + const ToxFriendCall& call = *it->second; if (call.getMuteVol()) { return; @@ -881,7 +881,7 @@ void CoreAV::videoFrameCallback(ToxAV* toxAV, uint32_t friendNum, uint16_t w, ui auto self = static_cast(vSelf); // This callback should come from the CoreAV thread assert(QThread::currentThread() == self->coreavThread.get()); - QReadLocker locker{&self->callsLock}; + const QReadLocker locker{&self->callsLock}; auto it = self->calls.find(friendNum); if (it == self->calls.end()) { diff --git a/src/core/coreext.cpp b/src/core/coreext.cpp index 4ec35689ee..520dfaaf8a 100644 --- a/src/core/coreext.cpp +++ b/src/core/coreext.cpp @@ -44,14 +44,14 @@ CoreExt::CoreExt(ExtensionPtr toxExt_) void CoreExt::process() { - std::lock_guard lock(toxext_mutex); + const std::lock_guard lock(toxext_mutex); toxext_iterate(toxExt.get()); } void CoreExt::onLosslessPacket(uint32_t friendId, const uint8_t* data, size_t length) { if (is_toxext_packet(data, length)) { - std::lock_guard lock(toxext_mutex); + const std::lock_guard lock(toxext_mutex); toxext_handle_lossless_custom_packet(toxExt.get(), friendId, data, length); } } @@ -84,7 +84,7 @@ uint64_t CoreExt::Packet::addExtendedMessage(QString message) return UINT64_MAX; } - int size = message.toUtf8().size(); + const int size = message.toUtf8().size(); enum Tox_Extension_Messages_Error err; auto maxSize = static_cast(tox_extension_messages_get_max_sending_size(toxExtMessages, friendId, &err)); @@ -96,7 +96,7 @@ uint64_t CoreExt::Packet::addExtendedMessage(QString message) return false; } - ToxString toxString(message); + const ToxString toxString(message); const auto receipt = tox_extension_messages_append(toxExtMessages, packetList, toxString.data(), toxString.size(), friendId, &err); @@ -109,7 +109,7 @@ uint64_t CoreExt::Packet::addExtendedMessage(QString message) bool CoreExt::Packet::send() { - std::lock_guard lock(*toxext_mutex); + const std::lock_guard lock(*toxext_mutex); auto ret = toxext_send(packetList); if (ret != TOXEXT_SUCCESS) { @@ -147,7 +147,7 @@ void CoreExt::onFriendStatusChanged(uint32_t friendId, Status::Status status) void CoreExt::onExtendedMessageReceived(uint32_t friendId, const uint8_t* data, size_t size, void* userData) { - QString msg = ToxString(data, size).getQString(); + const QString msg = ToxString(data, size).getQString(); emit static_cast(userData)->extendedMessageReceived(friendId, msg); } diff --git a/src/core/corefile.cpp b/src/core/corefile.cpp index 00583a8db6..704b3aa83b 100644 --- a/src/core/corefile.cpp +++ b/src/core/corefile.cpp @@ -62,7 +62,7 @@ unsigned CoreFile::corefileIterationInterval() */ constexpr unsigned fileInterval = 10, idleInterval = 1000; - for (ToxFile& file : fileMap) { + for (const ToxFile& file : fileMap) { if (file.status == ToxFile::TRANSMITTING) { return fileInterval; } @@ -81,7 +81,7 @@ void CoreFile::connectCallbacks(Tox& tox) void CoreFile::sendAvatarFile(uint32_t friendId, const QByteArray& data) { - QMutexLocker locker{coreLoopLock}; + const QMutexLocker locker{coreLoopLock}; uint64_t filesize = 0; uint8_t* file_id = nullptr; @@ -119,12 +119,12 @@ void CoreFile::sendAvatarFile(uint32_t friendId, const QByteArray& data) void CoreFile::sendFile(uint32_t friendId, QString filename, QString filePath, long long filesize) { - QMutexLocker locker{coreLoopLock}; + const QMutexLocker locker{coreLoopLock}; - ToxString fileName(filename); + const ToxString fileName(filename); Tox_Err_File_Send sendErr; - uint32_t fileNum = tox_file_send(tox, friendId, TOX_FILE_KIND_DATA, filesize, nullptr, - fileName.data(), fileName.size(), &sendErr); + const uint32_t fileNum = tox_file_send(tox, friendId, TOX_FILE_KIND_DATA, filesize, nullptr, + fileName.data(), fileName.size(), &sendErr); if (!PARSE_ERR(sendErr)) { emit fileSendFailed(friendId, fileName.getQString()); @@ -156,7 +156,7 @@ void CoreFile::sendFile(uint32_t friendId, QString filename, QString filePath, l void CoreFile::pauseResumeFile(uint32_t friendId, uint32_t fileId) { - QMutexLocker locker{coreLoopLock}; + const QMutexLocker locker{coreLoopLock}; ToxFile* file = findFile(friendId, fileId); if (!file) { @@ -191,7 +191,7 @@ void CoreFile::pauseResumeFile(uint32_t friendId, uint32_t fileId) void CoreFile::cancelFileSend(uint32_t friendId, uint32_t fileId) { - QMutexLocker locker{coreLoopLock}; + const QMutexLocker locker{coreLoopLock}; ToxFile* file = findFile(friendId, fileId); if (!file) { @@ -211,7 +211,7 @@ void CoreFile::cancelFileSend(uint32_t friendId, uint32_t fileId) void CoreFile::cancelFileRecv(uint32_t friendId, uint32_t fileId) { - QMutexLocker locker{coreLoopLock}; + const QMutexLocker locker{coreLoopLock}; ToxFile* file = findFile(friendId, fileId); if (!file) { @@ -230,7 +230,7 @@ void CoreFile::cancelFileRecv(uint32_t friendId, uint32_t fileId) void CoreFile::rejectFileRecvRequest(uint32_t friendId, uint32_t fileId) { - QMutexLocker locker{coreLoopLock}; + const QMutexLocker locker{coreLoopLock}; ToxFile* file = findFile(friendId, fileId); if (!file) { @@ -249,7 +249,7 @@ void CoreFile::rejectFileRecvRequest(uint32_t friendId, uint32_t fileId) void CoreFile::acceptFileRecvRequest(uint32_t friendId, uint32_t fileId, QString path) { - QMutexLocker locker{coreLoopLock}; + const QMutexLocker locker{coreLoopLock}; ToxFile* file = findFile(friendId, fileId); if (!file) { @@ -272,9 +272,9 @@ void CoreFile::acceptFileRecvRequest(uint32_t friendId, uint32_t fileId, QString ToxFile* CoreFile::findFile(uint32_t friendId, uint32_t fileId) { - QMutexLocker locker{coreLoopLock}; + const QMutexLocker locker{coreLoopLock}; - uint64_t key = getFriendKey(friendId, fileId); + const uint64_t key = getFriendKey(friendId, fileId); if (fileMap.contains(key)) { return &fileMap[key]; } @@ -285,7 +285,7 @@ ToxFile* CoreFile::findFile(uint32_t friendId, uint32_t fileId) void CoreFile::addFile(uint32_t friendId, uint32_t fileId, const ToxFile& file) { - uint64_t key = getFriendKey(friendId, fileId); + const uint64_t key = getFriendKey(friendId, fileId); if (fileMap.contains(key)) { qWarning() << "addFile: Overwriting existing file transfer with same ID" << friendId << ':' @@ -297,7 +297,7 @@ void CoreFile::addFile(uint32_t friendId, uint32_t fileId, const ToxFile& file) void CoreFile::removeFile(uint32_t friendId, uint32_t fileId) { - uint64_t key = getFriendKey(friendId, fileId); + const uint64_t key = getFriendKey(friendId, fileId); if (!fileMap.contains(key)) { qWarning() << "removeFile: No such file in queue"; return; @@ -308,7 +308,7 @@ void CoreFile::removeFile(uint32_t friendId, uint32_t fileId) QString CoreFile::getCleanFileName(QString filename) { - QRegularExpression regex{QStringLiteral(R"([<>:"/\\|?])")}; + const QRegularExpression regex{QStringLiteral(R"([<>:"/\\|?])")}; filename.replace(regex, "_"); return filename; @@ -351,8 +351,8 @@ void CoreFile::onFileReceiveCallback(Tox* tox, uint32_t friendId, uint32_t fileI if (!PARSE_ERR(fileGetErr)) { return; } - QByteArray avatarBytes{static_cast(static_cast(avatarHash)), - TOX_HASH_LENGTH}; + const QByteArray avatarBytes{static_cast(static_cast(avatarHash)), + TOX_HASH_LENGTH}; emit core->fileAvatarOfferReceived(friendId, fileId, avatarBytes, filesize); return; } @@ -475,7 +475,7 @@ void CoreFile::onFileDataCallback(Tox* tox, uint32_t friendId, uint32_t fileId, return; } - std::unique_ptr data(new uint8_t[length]); + const std::unique_ptr data(new uint8_t[length]); int64_t nread; if (file->fileKind == TOX_FILE_KIND_AVATAR) { @@ -577,7 +577,7 @@ void CoreFile::onFileRecvChunkCallback(Tox* tox, uint32_t friendId, uint32_t fil void CoreFile::onConnectionStatusChanged(uint32_t friendId, Status::Status state) { - bool isOffline = state == Status::Status::Offline; + const bool isOffline = state == Status::Status::Offline; // TODO: Actually resume broken file transfers // We need to: // - Start a new file transfer with the same 32byte file ID with toxcore @@ -585,8 +585,8 @@ void CoreFile::onConnectionStatusChanged(uint32_t friendId, Status::Status state // - Update the fileNum in our ToxFile // - Update the users of our signals to check the 32byte tox file ID, not the uint32_t file_num // (fileId) - ToxFile::FileStatus status = !isOffline ? ToxFile::TRANSMITTING : ToxFile::BROKEN; - for (uint64_t key : fileMap.keys()) { + const ToxFile::FileStatus status = !isOffline ? ToxFile::TRANSMITTING : ToxFile::BROKEN; + for (const uint64_t key : fileMap.keys()) { if (key >> 32 != friendId) continue; fileMap[key].status = status; diff --git a/src/core/toxencrypt.cpp b/src/core/toxencrypt.cpp index a966113a28..e7bf82aa43 100644 --- a/src/core/toxencrypt.cpp +++ b/src/core/toxencrypt.cpp @@ -167,7 +167,7 @@ QByteArray ToxEncrypt::encryptPass(const QString& password, const QByteArray& pl qWarning() << "Empty password supplied, probably not what you intended."; } - QByteArray pass = password.toUtf8(); + const QByteArray pass = password.toUtf8(); QByteArray ciphertext(plaintext.length() + TOX_PASS_ENCRYPTION_EXTRA_LENGTH, 0x00); Tox_Err_Encryption error; tox_pass_encrypt(reinterpret_cast(plaintext.constData()), @@ -202,7 +202,7 @@ QByteArray ToxEncrypt::decryptPass(const QString& password, const QByteArray& ci qDebug() << "Empty password supplied, probably not what you intended."; } - QByteArray pass = password.toUtf8(); + const QByteArray pass = password.toUtf8(); QByteArray plaintext(ciphertext.length() - TOX_PASS_ENCRYPTION_EXTRA_LENGTH, 0x00); Tox_Err_Decryption error; tox_pass_decrypt(reinterpret_cast(ciphertext.constData()), @@ -269,7 +269,7 @@ std::unique_ptr ToxEncrypt::makeToxEncrypt(const QString& password, return std::unique_ptr{}; } - QByteArray pass = password.toUtf8(); + const QByteArray pass = password.toUtf8(); Tox_Err_Key_Derivation keyError; Tox_Pass_Key* const passKey = tox_pass_key_derive_with_salt(reinterpret_cast(pass.constData()), diff --git a/src/core/toxid.cpp b/src/core/toxid.cpp index ddbc636f40..2e1af5b874 100644 --- a/src/core/toxid.cpp +++ b/src/core/toxid.cpp @@ -96,7 +96,7 @@ ToxId::ToxId(const QByteArray& rawId) */ ToxId::ToxId(const uint8_t* rawId, int len) { - QByteArray tmpId(reinterpret_cast(rawId), len); + const QByteArray tmpId(reinterpret_cast(rawId), len); constructToxId(tmpId); } @@ -224,7 +224,7 @@ bool ToxId::isValid() const const int pkAndChecksum = ToxPk::size + ToxId::nospamSize; QByteArray data = toxId.left(pkAndChecksum); - QByteArray checksum = toxId.right(ToxId::checksumSize); + const QByteArray checksum = toxId.right(ToxId::checksumSize); QByteArray calculated(ToxId::checksumSize, 0x00); for (int i = 0; i < pkAndChecksum; i++) { diff --git a/src/core/toxoptions.cpp b/src/core/toxoptions.cpp index 9adb2ed374..9063bd24d7 100644 --- a/src/core/toxoptions.cpp +++ b/src/core/toxoptions.cpp @@ -84,8 +84,8 @@ std::unique_ptr ToxOptions::makeToxOptions(const QByteArray& savedat bool forceTCP = s.getForceTCP(); // LAN requiring UDP is a toxcore limitation, ideally wouldn't be related const bool enableLanDiscovery = s.getEnableLanDiscovery() && !forceTCP; - ICoreSettings::ProxyType proxyType = s.getProxyType(); - quint16 proxyPort = s.getProxyPort(); + const ICoreSettings::ProxyType proxyType = s.getProxyType(); + const quint16 proxyPort = s.getProxyPort(); if (!enableLanDiscovery) { qWarning() << "Core starting without LAN discovery. Peers can only be found through DHT."; diff --git a/src/friendlist.cpp b/src/friendlist.cpp index 6d4d7eaecc..0efd4b750a 100644 --- a/src/friendlist.cpp +++ b/src/friendlist.cpp @@ -19,7 +19,7 @@ Friend* FriendList::addFriend(uint32_t friendId, const ToxPk& friendPk, Settings qWarning() << "addFriend: friendPk already taken"; } - QString alias = settings.getFriendAlias(friendPk); + const QString alias = settings.getFriendAlias(friendPk); Friend* newfriend = new Friend(friendId, friendPk, alias); friendList[friendPk] = newfriend; id2key[friendId] = friendPk; diff --git a/src/ipc.cpp b/src/ipc.cpp index ce30f14318..ed32913054 100644 --- a/src/ipc.cpp +++ b/src/ipc.cpp @@ -129,7 +129,7 @@ IPC::~IPC() */ time_t IPC::postEvent(const QString& name, const QByteArray& data, uint32_t dest) { - QByteArray binName = name.toUtf8(); + const QByteArray binName = name.toUtf8(); if (binName.length() > static_cast(sizeof(IPCEvent::name))) { return 0; } @@ -233,7 +233,7 @@ bool IPC::isEventAccepted(time_t time) bool IPC::waitUntilAccepted(time_t postTime, int32_t timeout /*=-1*/) { bool result = false; - time_t start = time(nullptr); + const time_t start = time(nullptr); forever { result = isEventAccepted(postTime); @@ -334,7 +334,7 @@ void IPC::processEvents() const std::lock_guard lock(eventHandlersMutex); while (IPCEvent* evt = fetchEvent()) { - QString name = QString::fromUtf8(evt->name); + const QString name = QString::fromUtf8(evt->name); auto it = eventHandlers.find(name); if (it != eventHandlers.end()) { evt->accepted = runEventHandler(it.value().handler, evt->data, it.value().userData); diff --git a/src/main.cpp b/src/main.cpp index 48054bd51d..27395e57e7 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -11,7 +11,7 @@ int main(int argc, char* argv[]) { AppManager appManager(argc, argv); - int errorcode = appManager.run(); + const int errorcode = appManager.run(); qDebug() << "Exit with status" << errorcode; return errorcode; diff --git a/src/model/chathistory.cpp b/src/model/chathistory.cpp index dcf540bbdd..d18544956f 100644 --- a/src/model/chathistory.cpp +++ b/src/model/chathistory.cpp @@ -210,8 +210,8 @@ void ChatHistory::onFileUpdated(const ToxPk& sender, const ToxFile& file) switch (file.status) { case ToxFile::INITIALIZING: { auto selfPk = coreIdHandler.getSelfPublicKey(); - QString username(selfPk == sender ? coreIdHandler.getUsername() - : chat.getDisplayedName(sender)); + const QString username(selfPk == sender ? coreIdHandler.getUsername() + : chat.getDisplayedName(sender)); // Note: There is some implcit coupling between history and the current // chat log. Both rely on generating a new id based on the state of diff --git a/src/model/friendlist/friendlistmanager.cpp b/src/model/friendlist/friendlistmanager.cpp index 4b021d24bc..12f0fbaf8d 100644 --- a/src/model/friendlist/friendlistmanager.cpp +++ b/src/model/friendlist/friendlistmanager.cpp @@ -91,13 +91,13 @@ void FriendListManager::setFilter(const QString& searchString, bool hideOnline, void FriendListManager::applyFilter() { - QString searchString = filterParams.searchString; + const QString searchString = filterParams.searchString; - for (IFriendListItemPtr itemTmp : items) { + for (const IFriendListItemPtr itemTmp : items) { if (searchString.isEmpty()) { itemTmp->setWidgetVisible(true); } else { - QString tmp_name = itemTmp->getNameItem(); + const QString tmp_name = itemTmp->getNameItem(); itemTmp->setWidgetVisible(tmp_name.contains(searchString, Qt::CaseInsensitive)); } @@ -216,8 +216,8 @@ bool FriendListManager::cmpByActivity(const IFriendListItemPtr& a, const IFriend return a->getNameItem().toUpper() < b->getNameItem().toUpper(); } - QDateTime dateA = a->getLastActivity(); - QDateTime dateB = b->getLastActivity(); + const QDateTime dateA = a->getLastActivity(); + const QDateTime dateB = b->getLastActivity(); if (dateA.date() == dateB.date()) { if (a->isOnline() && !b->isOnline()) { return true; diff --git a/src/model/friendmessagedispatcher.cpp b/src/model/friendmessagedispatcher.cpp index c89416b69d..58cb44724d 100644 --- a/src/model/friendmessagedispatcher.cpp +++ b/src/model/friendmessagedispatcher.cpp @@ -164,7 +164,7 @@ void FriendMessageDispatcher::sendCoreProcessedMessage(Message const& message, { auto receipt = ReceiptNum(); - uint32_t friendId = f.getId(); + const uint32_t friendId = f.getId(); auto sendFn = message.isAction ? std::mem_fn(&ICoreFriendMessageSender::sendAction) : std::mem_fn(&ICoreFriendMessageSender::sendMessage); diff --git a/src/model/groupmessagedispatcher.cpp b/src/model/groupmessagedispatcher.cpp index cb305dd3c4..9ef5999595 100644 --- a/src/model/groupmessagedispatcher.cpp +++ b/src/model/groupmessagedispatcher.cpp @@ -71,7 +71,7 @@ GroupMessageDispatcher::sendExtendedMessage(const QString& content, ExtensionSet */ void GroupMessageDispatcher::onMessageReceived(const ToxPk& sender, bool isAction, QString const& content) { - bool isSelf = sender == idHandler.getSelfPublicKey(); + const bool isSelf = sender == idHandler.getSelfPublicKey(); if (isSelf) { return; diff --git a/src/model/message.cpp b/src/model/message.cpp index 3875b437be..8aefb36552 100644 --- a/src/model/message.cpp +++ b/src/model/message.cpp @@ -104,7 +104,7 @@ std::vector MessageProcessor::processOutgoingMessage(bool isAction, QSt */ Message MessageProcessor::processIncomingCoreMessage(bool isAction, QString const& message) { - QDateTime timestamp = QDateTime::currentDateTime(); + const QDateTime timestamp = QDateTime::currentDateTime(); auto ret = Message{}; ret.isAction = isAction; ret.content = message; diff --git a/src/model/profile/profileinfo.cpp b/src/model/profile/profileinfo.cpp index 5fa568881e..5f17e812d5 100644 --- a/src/model/profile/profileinfo.cpp +++ b/src/model/profile/profileinfo.cpp @@ -40,8 +40,8 @@ QString sanitize(const QString& src) { QString name = src; // these are pretty much Windows banned filename characters - QList banned{'/', '\\', ':', '<', '>', '"', '|', '?', '*'}; - for (QChar c : banned) { + const QList banned{'/', '\\', ':', '<', '>', '"', '|', '?', '*'}; + for (const QChar c : banned) { name.replace(c, '_'); } @@ -66,7 +66,7 @@ QString sanitize(const QString& src) bool tryRemoveFile(const QString& filepath) { QFile tmp(filepath); - bool writable = tmp.open(QIODevice::WriteOnly); + const bool writable = tmp.open(QIODevice::WriteOnly); tmp.remove(); return writable; } @@ -103,7 +103,7 @@ ProfileInfo::ProfileInfo(Core* core_, Profile* profile_, Settings& settings_, Ne */ bool ProfileInfo::setPassword(const QString& password) { - QString errorMsg = profile->setPassword(password); + const QString errorMsg = profile->setPassword(password); return errorMsg.isEmpty(); } @@ -113,7 +113,7 @@ bool ProfileInfo::setPassword(const QString& password) */ bool ProfileInfo::deletePassword() { - QString errorMsg = profile->setPassword(""); + const QString errorMsg = profile->setPassword(""); return errorMsg.isEmpty(); } @@ -131,8 +131,8 @@ bool ProfileInfo::isEncrypted() const */ void ProfileInfo::copyId() const { - ToxId selfId = core->getSelfId(); - QString txt = selfId.toString(); + const ToxId selfId = core->getSelfId(); + const QString txt = selfId.toString(); QClipboard* clip = QApplication::clipboard(); clip->setText(txt, QClipboard::Clipboard); if (clip->supportsSelection()) { @@ -174,12 +174,12 @@ QString ProfileInfo::getProfileName() const */ IProfileInfo::RenameResult ProfileInfo::renameProfile(const QString& name) { - QString cur = profile->getName(); + const QString cur = profile->getName(); if (name.isEmpty()) { return RenameResult::EmptyName; } - QString newName = sanitize(name); + const QString newName = sanitize(name); if (Profile::exists(newName, settings.getPaths())) { return RenameResult::ProfileAlreadyExists; @@ -199,7 +199,7 @@ IProfileInfo::RenameResult ProfileInfo::renameProfile(const QString& name) */ IProfileInfo::SaveResult ProfileInfo::exportProfile(const QString& path) const { - QString current = profile->getName() + Core::TOX_EXT; + const QString current = profile->getName() + Core::TOX_EXT; if (path.isEmpty()) { return SaveResult::EmptyPath; } @@ -253,7 +253,7 @@ void ProfileInfo::copyQr(const QImage& image) const */ IProfileInfo::SaveResult ProfileInfo::saveQr(const QImage& image, const QString& path) const { - QString current = profile->getName() + ".png"; + const QString current = profile->getName() + ".png"; if (path.isEmpty()) { return SaveResult::EmptyPath; } @@ -303,7 +303,7 @@ IProfileInfo::SetAvatarResult ProfileInfo::setAvatar(const QString& path) */ IProfileInfo::SetAvatarResult ProfileInfo::createAvatarFromFile(QFile& file, QByteArray& avatar) { - QByteArray fileContents{file.readAll()}; + const QByteArray fileContents{file.readAll()}; auto err = byteArrayToPng(fileContents, avatar); if (err != SetAvatarResult::OK) { return err; diff --git a/src/model/sessionchatlog.cpp b/src/model/sessionchatlog.cpp index 4eb3a17c7d..0c25f4b4ef 100644 --- a/src/model/sessionchatlog.cpp +++ b/src/model/sessionchatlog.cpp @@ -133,8 +133,8 @@ SessionChatLog::~SessionChatLog() = default; QString SessionChatLog::resolveSenderNameFromSender(const ToxPk& sender) { - bool isSelf = sender == coreIdHandler.getSelfPublicKey(); - QString myNickName = + const bool isSelf = sender == coreIdHandler.getSelfPublicKey(); + const QString myNickName = coreIdHandler.getUsername().isEmpty() ? sender.toString() : coreIdHandler.getUsername(); return isSelf ? myNickName : resolveToxPk(friendList, groupList, sender); diff --git a/src/net/avatarbroadcaster.cpp b/src/net/avatarbroadcaster.cpp index 1d97772501..2088e1ed9e 100644 --- a/src/net/avatarbroadcaster.cpp +++ b/src/net/avatarbroadcaster.cpp @@ -37,8 +37,8 @@ void AvatarBroadcaster::setAvatar(QByteArray data) avatarData = data; friendsSentTo.clear(); - QVector friends = core.getFriendList(); - for (uint32_t friendId : friends) { + const QVector friends = core.getFriendList(); + for (const uint32_t friendId : friends) { sendAvatarTo(friendId); } } diff --git a/src/net/bootstrapnodeupdater.cpp b/src/net/bootstrapnodeupdater.cpp index 1ec7ec241a..600d946f86 100644 --- a/src/net/bootstrapnodeupdater.cpp +++ b/src/net/bootstrapnodeupdater.cpp @@ -131,8 +131,8 @@ QList jsonToNodeList(const QJsonDocument& nodeList) qWarning() << "Bootstrap JSON is missing nodes array"; return result; } - QJsonArray nodes = rootObj[jsonNodeArrayName].toArray(); - for (const QJsonValueRef node : nodes) { + const QJsonArray nodes = rootObj[jsonNodeArrayName].toArray(); + for (const QJsonValueConstRef node : nodes) { if (node.isObject()) { jsonNodeToDhtServer(node.toObject(), result); } @@ -149,7 +149,7 @@ QList loadNodesFile(QString file) return {}; } - QString nodesJson = QString::fromUtf8(nodesFile.readAll()); + const QString nodesJson = QString::fromUtf8(nodesFile.readAll()); nodesFile.close(); auto jsonDoc = QJsonDocument::fromJson(nodesJson.toUtf8()); @@ -184,7 +184,7 @@ QByteArray serialize(QList nodes) QJsonObject rootObj; rootObj.insert("nodes", jsonNodes); - QJsonDocument doc{rootObj}; + const QJsonDocument doc{rootObj}; return doc.toJson(QJsonDocument::Indented); } @@ -253,13 +253,13 @@ void BootstrapNodeUpdater::onRequestComplete(QNetworkReply* reply) } // parse the reply JSON - QJsonDocument jsonDocument = QJsonDocument::fromJson(reply->readAll()); + const QJsonDocument jsonDocument = QJsonDocument::fromJson(reply->readAll()); if (jsonDocument.isNull()) { emit availableBootstrapNodes({}); return; } - QList result = jsonToNodeList(jsonDocument); + const QList result = jsonToNodeList(jsonDocument); emit availableBootstrapNodes(result); } diff --git a/src/net/toxuri.cpp b/src/net/toxuri.cpp index 3ad97b80af..349b1c1427 100644 --- a/src/net/toxuri.cpp +++ b/src/net/toxuri.cpp @@ -26,9 +26,9 @@ */ bool ToxURIDialog::handleToxURI(const QString& toxURI) { - QString toxaddr = toxURI.mid(4); + const QString toxaddr = toxURI.mid(4); - ToxId toxId(toxaddr); + const ToxId toxId(toxaddr); QString error = QString(); if (!toxId.isValid()) { error = QMessageBox::tr("%1 is not a valid Tox address.").arg(toxaddr); @@ -44,7 +44,7 @@ bool ToxURIDialog::handleToxURI(const QString& toxURI) setUserId(toxURI); - int result = exec(); + const int result = exec(); if (result == QDialog::Accepted) { core.requestFriendship(toxId, getRequestMessage()); } diff --git a/src/net/updatecheck.cpp b/src/net/updatecheck.cpp index a7a97cef70..cf479c097d 100644 --- a/src/net/updatecheck.cpp +++ b/src/net/updatecheck.cpp @@ -32,7 +32,7 @@ struct Version Version tagToVersion(QString tagName) { // capture tag name to avoid showing update available on dev builds which include hash as part of describe - QRegularExpression versionFormat(versionRegexString); + const QRegularExpression versionFormat(versionRegexString); auto matches = versionFormat.match(tagName); assert(matches.lastCapturedIndex() == 3); @@ -78,7 +78,7 @@ bool isUpdateAvailable(Version current, Version available) bool isCurrentVersionStable() { - QRegularExpression versionRegex(versionRegexString); + const QRegularExpression versionRegex(versionRegexString); auto currentVer = versionRegex.match(GIT_DESCRIBE_EXACT); if (currentVer.hasMatch()) { return true; @@ -112,7 +112,7 @@ void UpdateCheck::checkForUpdate() } manager.setProxy(settings.getProxy()); - QNetworkRequest request{versionUrl}; + const QNetworkRequest request{versionUrl}; manager.get(request); } @@ -130,11 +130,11 @@ void UpdateCheck::handleResponse(QNetworkReply* reply) reply->deleteLater(); return; } - QByteArray result = reply->readAll(); - QJsonDocument doc = QJsonDocument::fromJson(result); - QJsonObject jObject = doc.object(); + const QByteArray result = reply->readAll(); + const QJsonDocument doc = QJsonDocument::fromJson(result); + const QJsonObject jObject = doc.object(); QVariantMap mainMap = jObject.toVariantMap(); - QString latestVersion = mainMap["tag_name"].toString(); + const QString latestVersion = mainMap["tag_name"].toString(); if (latestVersion.isEmpty()) { qWarning() << "No tag name found in response:"; emit updateCheckFailed(); @@ -147,7 +147,7 @@ void UpdateCheck::handleResponse(QNetworkReply* reply) if (isUpdateAvailable(currentVer, availableVer)) { qInfo() << "Update available to version" << latestVersion; - QUrl link{mainMap["html_url"].toString()}; + const QUrl link{mainMap["html_url"].toString()}; emit updateAvailable(latestVersion, link); } else { qInfo() << "qTox is up to date"; diff --git a/src/nexus.cpp b/src/nexus.cpp index e2e957a90d..9bff2f06ac 100644 --- a/src/nexus.cpp +++ b/src/nexus.cpp @@ -163,7 +163,7 @@ int Nexus::showLogin(const QString& profileName) // This is awkward because the core is in the profile // The connection order ensures profile will be ready for bootstrap for now connect(this, &Nexus::currentProfileChanged, this, &Nexus::bootstrapWithProfile); - int returnval = loginScreen.exec(); + const int returnval = loginScreen.exec(); if (returnval == QDialog::Rejected) { // Kriby: This will terminate the main application loop, necessary until we refactor // away the split startup/return to login behavior. diff --git a/src/persistence/db/rawdatabase.cpp b/src/persistence/db/rawdatabase.cpp index 9c821c43e9..93beee24ac 100644 --- a/src/persistence/db/rawdatabase.cpp +++ b/src/persistence/db/rawdatabase.cpp @@ -424,7 +424,7 @@ bool RawDatabase::execNow(const QVector& statements) trans.done = &done; trans.success = &success; { - QMutexLocker locker{&transactionsMutex}; + const QMutexLocker locker{&transactionsMutex}; pendingTransactions.enqueue(trans); } @@ -461,7 +461,7 @@ void RawDatabase::execLater(const QVector& statements) Transaction trans; trans.queries = statements; { - QMutexLocker locker{&transactionsMutex}; + const QMutexLocker locker{&transactionsMutex}; pendingTransactions.enqueue(trans); } @@ -506,7 +506,7 @@ bool RawDatabase::setPassword(const QString& password) } if (!password.isEmpty()) { - QString newHexKey = deriveKey(password, currentSalt); + const QString newHexKey = deriveKey(password, currentSalt); if (!currentHexKey.isEmpty()) { if (!execNow("PRAGMA rekey = \"x'" + newHexKey + "'\"")) { qWarning() << "Failed to change encryption key"; @@ -738,7 +738,7 @@ void RawDatabase::process() // Fetch the next transaction Transaction trans; { - QMutexLocker locker{&transactionsMutex}; + const QMutexLocker locker{&transactionsMutex}; if (pendingTransactions.isEmpty()) return; trans = pendingTransactions.dequeue(); @@ -779,7 +779,7 @@ void RawDatabase::process() query.statements += stmt; // Now we can bind our params to this statement - int nParams = sqlite3_bind_parameter_count(stmt); + const int nParams = sqlite3_bind_parameter_count(stmt); if (query.blobs.size() < curParam + nParams) { qWarning() << "Not enough parameters to bind to query " << anonymizeQuery(query.query); @@ -807,7 +807,7 @@ void RawDatabase::process() // Execute each statement of each query of our transaction for (sqlite3_stmt* stmt : query.statements) { - int column_count = sqlite3_column_count(stmt); + const int column_count = sqlite3_column_count(stmt); int result; do { result = sqlite3_step(stmt); @@ -825,7 +825,7 @@ void RawDatabase::process() if (result == SQLITE_DONE) continue; - QString anonQuery = anonymizeQuery(query.query); + const QString anonQuery = anonymizeQuery(query.query); switch (result) { case SQLITE_ERROR: qWarning() << "Error executing query" << anonQuery; @@ -887,18 +887,18 @@ QString RawDatabase::anonymizeQuery(const QByteArray& query) */ QVariant RawDatabase::extractData(sqlite3_stmt* stmt, int col) { - int type = sqlite3_column_type(stmt, col); + const int type = sqlite3_column_type(stmt, col); if (type == SQLITE_INTEGER) { return sqlite3_column_int64(stmt, col); } else if (type == SQLITE_TEXT) { const char* str = reinterpret_cast(sqlite3_column_text(stmt, col)); - int len = sqlite3_column_bytes(stmt, col); + const int len = sqlite3_column_bytes(stmt, col); return QString::fromUtf8(str, len); } else if (type == SQLITE_NULL) { return QVariant{}; } else { const char* data = reinterpret_cast(sqlite3_column_blob(stmt, col)); - int len = sqlite3_column_bytes(stmt, col); + const int len = sqlite3_column_bytes(stmt, col); return QByteArray(data, len); } } diff --git a/src/persistence/db/upgrades/dbto11.cpp b/src/persistence/db/upgrades/dbto11.cpp index 597678fc3e..ce6f52387c 100644 --- a/src/persistence/db/upgrades/dbto11.cpp +++ b/src/persistence/db/upgrades/dbto11.cpp @@ -25,7 +25,7 @@ bool DbTo11::dbSchema10to11(RawDatabase& db) return false; } upgradeQueries += RawDatabase::Query(QStringLiteral("PRAGMA user_version = 11;")); - bool transactionPass = db.execNow(upgradeQueries); + const bool transactionPass = db.execNow(upgradeQueries); if (transactionPass) { return db.execNow("VACUUM"); } diff --git a/src/persistence/db/upgrades/dbupgrader.cpp b/src/persistence/db/upgrades/dbupgrader.cpp index 3b06f557a3..d2b5b0ab1c 100644 --- a/src/persistence/db/upgrades/dbupgrader.cpp +++ b/src/persistence/db/upgrades/dbupgrader.cpp @@ -48,7 +48,7 @@ RowId getValidPeerRow(RawDatabase& db, const ChatId& chatId) db.execNow(RawDatabase::Query(("SELECT id FROM peers ORDER BY id DESC LIMIT 1;"), [&](const QVector& row) { - int64_t maxPeerId = row[0].toInt(); + const int64_t maxPeerId = row[0].toInt(); validPeerRow = RowId{maxPeerId + 1}; })); db.execNow( @@ -369,7 +369,7 @@ bool DbUpgrader::dbSchema1to2(RawDatabase& db) // faux_offline_pending to broken_messages // the last non-pending message in each chat - QString lastDeliveredQuery = + const QString lastDeliveredQuery = QString("SELECT chat_id, MAX(history.id) FROM " "history JOIN peers chat ON chat_id = chat.id " "LEFT JOIN faux_offline_pending ON history.id = faux_offline_pending.id " @@ -598,7 +598,7 @@ bool DbUpgrader::dbSchema9to10(RawDatabase& db) // entries. The resume file ID isn't actually used for loaded files at this time, so we can heal // it to an arbitrary value of full length. constexpr int resumeFileIdLengthNow = 32; - QByteArray dummyResumeId(resumeFileIdLengthNow, 0); + const QByteArray dummyResumeId(resumeFileIdLengthNow, 0); QVector upgradeQueries; upgradeQueries += RawDatabase::Query( QStringLiteral( diff --git a/src/persistence/history.cpp b/src/persistence/history.cpp index 677e1678d9..5bbc0fbf05 100644 --- a/src/persistence/history.cpp +++ b/src/persistence/history.cpp @@ -161,7 +161,7 @@ QVector generateNewSystemMessageQueries(const ChatId& chatId FileDbInsertionData::FileDbInsertionData() { - static int id = qRegisterMetaType(); + static const int id = qRegisterMetaType(); (void)id; } @@ -360,7 +360,7 @@ History::generateNewFileTransferQueries(const ChatId& chatId, const ToxPk& sende queries += generateUpdateAlias(sender, dispName); queries += generateHistoryTableInsertion('F', time, chatId); - std::weak_ptr weakThis = shared_from_this(); + const std::weak_ptr weakThis = shared_from_this(); auto fileId = insertionData.fileId; QString queryString; @@ -444,7 +444,7 @@ void History::addNewFileMessage(const ChatId& chatId, const QByteArray& fileId, direction = ToxFile::SENDING; } - std::weak_ptr weakThis = shared_from_this(); + const std::weak_ptr weakThis = shared_from_this(); FileDbInsertionData insertionData; insertionData.fileId = fileId; insertionData.fileName = fileName; @@ -675,7 +675,7 @@ QList History::getUndeliveredMessagesForChat(const ChatId& auto senderKey = ToxPk{(*it++).toByteArray()}; auto displayName = QString::fromUtf8((*it++).toByteArray().replace('\0', "")); - MessageState messageState = getMessageState(isPending, isBroken); + const MessageState messageState = getMessageState(isPending, isBroken); ret += {id, messageState, extensionSet, timestamp, chatId.clone(), displayName, senderKey, messageContent}; diff --git a/src/persistence/offlinemsgengine.cpp b/src/persistence/offlinemsgengine.cpp index 2f672a8176..c36612e72c 100644 --- a/src/persistence/offlinemsgengine.cpp +++ b/src/persistence/offlinemsgengine.cpp @@ -22,13 +22,13 @@ */ void OfflineMsgEngine::onReceiptReceived(ReceiptNum receipt) { - QMutexLocker ml(&mutex); + const QMutexLocker ml(&mutex); receiptResolver.notifyReceiptReceived(receipt); } void OfflineMsgEngine::onExtendedReceiptReceived(ExtendedReceiptNum receipt) { - QMutexLocker ml(&mutex); + const QMutexLocker ml(&mutex); extendedReceiptResolver.notifyReceiptReceived(receipt); } @@ -43,7 +43,7 @@ void OfflineMsgEngine::onExtendedReceiptReceived(ExtendedReceiptNum receipt) */ void OfflineMsgEngine::addUnsentMessage(Message const& message, CompletionFn completionCallback) { - QMutexLocker ml(&mutex); + const QMutexLocker ml(&mutex); unsentMessages.push_back( OfflineMessage{message, std::chrono::steady_clock::now(), completionCallback}); } @@ -61,7 +61,7 @@ void OfflineMsgEngine::addUnsentMessage(Message const& message, CompletionFn com void OfflineMsgEngine::addSentCoreMessage(ReceiptNum receipt, Message const& message, CompletionFn completionCallback) { - QMutexLocker ml(&mutex); + const QMutexLocker ml(&mutex); receiptResolver.notifyMessageSent(receipt, {message, std::chrono::steady_clock::now(), completionCallback}); } @@ -69,7 +69,7 @@ void OfflineMsgEngine::addSentCoreMessage(ReceiptNum receipt, Message const& mes void OfflineMsgEngine::addSentExtendedMessage(ExtendedReceiptNum receipt, Message const& message, CompletionFn completionCallback) { - QMutexLocker ml(&mutex); + const QMutexLocker ml(&mutex); extendedReceiptResolver.notifyMessageSent(receipt, {message, std::chrono::steady_clock::now(), completionCallback}); } @@ -79,7 +79,7 @@ void OfflineMsgEngine::addSentExtendedMessage(ExtendedReceiptNum receipt, Messag */ std::vector OfflineMsgEngine::removeAllMessages() { - QMutexLocker ml(&mutex); + const QMutexLocker ml(&mutex); auto messages = receiptResolver.clear(); auto extendedMessages = extendedReceiptResolver.clear(); diff --git a/src/persistence/paths.cpp b/src/persistence/paths.cpp index 602ecd0d55..1ec37c6463 100644 --- a/src/persistence/paths.cpp +++ b/src/persistence/paths.cpp @@ -350,21 +350,21 @@ QString Paths::getAppCacheDirPath() const QString Paths::getExampleNodesFilePath() const { - QDir dir(getSettingsDirPath()); + const QDir dir(getSettingsDirPath()); constexpr static char nodesFileName[] = "bootstrapNodes.example.json"; return dir.filePath(nodesFileName); } QString Paths::getUserNodesFilePath() const { - QDir dir(getSettingsDirPath()); + const QDir dir(getSettingsDirPath()); constexpr static char nodesFileName[] = "bootstrapNodes.json"; return dir.filePath(nodesFileName); } QString Paths::getBackupUserNodesFilePath() const { - QDir dir(getSettingsDirPath()); + const QDir dir(getSettingsDirPath()); constexpr static char nodesFileName[] = "bootstrapNodes.backup.json"; return dir.filePath(nodesFileName); } diff --git a/src/persistence/personalsettingsupgrader.cpp b/src/persistence/personalsettingsupgrader.cpp index 392640b4dd..979464ad2a 100644 --- a/src/persistence/personalsettingsupgrader.cpp +++ b/src/persistence/personalsettingsupgrader.cpp @@ -16,7 +16,7 @@ bool version0to1(SettingsSerializer& ps) { ps.beginGroup("Friends"); { - int size = ps.beginReadArray("Friend"); + const int size = ps.beginReadArray("Friend"); for (int i = 0; i < size; i++) { ps.setArrayIndex(i); const auto oldFriendAddr = ps.value("addr").toString(); diff --git a/src/persistence/profile.cpp b/src/persistence/profile.cpp index 7101d391d4..0b60356935 100644 --- a/src/persistence/profile.cpp +++ b/src/persistence/profile.cpp @@ -317,7 +317,7 @@ Profile* Profile::loadProfile(const QString& name, const QString& password, Sett LoadToxDataError error; QByteArray toxsave = QByteArray(); - QString path = paths.getSettingsDirPath() + name + ".tox"; + const QString path = paths.getSettingsDirPath() + name + ".tox"; std::unique_ptr tmpKey = loadToxData(password, path, toxsave, error); if (logLoadToxDataError(error, path)) { ProfileLocker::unlock(); @@ -350,7 +350,7 @@ Profile* Profile::createProfile(const QString& name, const QString& password, Se { CreateToxDataError error; Paths& paths = settings.getPaths(); - QString path = paths.getSettingsDirPath() + name + ".tox"; + const QString path = paths.getSettingsDirPath() + name + ".tox"; std::unique_ptr tmpKey = createToxData(name, password, path, error, paths); if (logCreateToxDataError(error, name)) { @@ -393,9 +393,9 @@ QStringList Profile::getFilesByExt(QString extension, Settings& settings) QStringList out; dir.setFilter(QDir::Files | QDir::NoDotAndDotDot); dir.setNameFilters(QStringList("*." + extension)); - QFileInfoList list = dir.entryInfoList(); + const QFileInfoList list = dir.entryInfoList(); out.reserve(list.size()); - for (QFileInfo file : list) { + for (const QFileInfo file : list) { out += file.completeBaseName(); } @@ -460,7 +460,7 @@ void Profile::startCore() */ void Profile::onSaveToxSave() { - QByteArray data = core->getToxSaveData(); + const QByteArray data = core->getToxSaveData(); assert(data.size()); saveToxSave(data); } @@ -486,7 +486,7 @@ bool Profile::saveToxSave(QByteArray data) ProfileLocker::assertLock(paths); assert(ProfileLocker::getCurLockName() == name); - QString path = paths.getSettingsDirPath() + name + ".tox"; + const QString path = paths.getSettingsDirPath() + name + ".tox"; qDebug() << "Saving tox save to " << path; QSaveFile saveFile(path); if (!saveFile.open(QIODevice::WriteOnly)) { @@ -619,7 +619,7 @@ void Profile::loadDatabase(QString password, IMessageBoxManager& messageBoxManag return; } - QByteArray salt = core->getSelfPublicKey().getByteArray(); + const QByteArray salt = core->getSelfPublicKey().getByteArray(); if (salt.size() != TOX_PASS_SALT_LENGTH) { qWarning() << "Couldn't compute salt from public key" << name; messageBoxManager @@ -723,7 +723,7 @@ void Profile::saveAvatar(const ToxPk& owner, const QByteArray& avatar) const bool needEncrypt = encrypted && !avatar.isEmpty(); const QByteArray& pic = needEncrypt ? passkey->encrypt(avatar) : avatar; - QString path = avatarPath(owner); + const QString path = avatarPath(owner); QDir(paths.getSettingsDirPath()).mkdir("avatars"); if (pic.isEmpty()) { QFile::remove(path); @@ -803,7 +803,7 @@ void Profile::removeAvatar(const ToxPk& owner) bool Profile::exists(QString name, Paths& paths) { - QString path = paths.getSettingsDirPath() + name; + const QString path = paths.getSettingsDirPath() + name; return QFile::exists(path + ".tox"); } @@ -825,7 +825,7 @@ bool Profile::isEncrypted() const bool Profile::isEncrypted(QString name, Paths& paths) { uint8_t data[TOX_PASS_ENCRYPTION_EXTRA_LENGTH] = {0}; - QString path = paths.getSettingsDirPath() + name + ".tox"; + const QString path = paths.getSettingsDirPath() + name + ".tox"; QFile saveFile(path); if (!saveFile.open(QIODevice::ReadOnly)) { qWarning() << "Couldn't open tox save " << path; @@ -859,7 +859,7 @@ QStringList Profile::remove() i--; } } - QString path = paths.getSettingsDirPath() + name; + const QString path = paths.getSettingsDirPath() + name; ProfileLocker::unlock(); QFile profileMain{path + ".tox"}; @@ -876,7 +876,7 @@ QStringList Profile::remove() qWarning() << "Could not remove file " << profileConfig.fileName(); } - QString dbPath = getDbPath(name, settings.getPaths()); + const QString dbPath = getDbPath(name, settings.getPaths()); if (database && database->isOpen() && !database->remove() && QFile::exists(dbPath)) { ret.push_back(dbPath); qWarning() << "Could not remove file " << dbPath; @@ -907,7 +907,7 @@ bool Profile::rename(QString newName) database->rename(newName); } - bool resetAutorun = settings.getAutorun(); + const bool resetAutorun = settings.getAutorun(); settings.setAutorun(false); settings.setCurrentProfile(newName); if (resetAutorun) { @@ -964,10 +964,10 @@ QString Profile::setPassword(const QString& newPassword) "password."); } - QByteArray avatar = loadAvatarData(core->getSelfPublicKey()); + const QByteArray avatar = loadAvatarData(core->getSelfPublicKey()); saveAvatar(core->getSelfPublicKey(), avatar); - QVector friendList = core->getFriendList(); + const QVector friendList = core->getFriendList(); QVectorIterator i(friendList); while (i.hasNext()) { const ToxPk friendPublicKey = core->getFriendPublicKey(i.next()); diff --git a/src/persistence/profilelocker.cpp b/src/persistence/profilelocker.cpp index f224dcdcce..ce166bc7a4 100644 --- a/src/persistence/profilelocker.cpp +++ b/src/persistence/profilelocker.cpp @@ -96,7 +96,7 @@ void ProfileLocker::assertLock(Paths& paths) } if (!QFile(lockPathFromName(curLockName, paths)).exists()) { - QString tmp = curLockName; + const QString tmp = curLockName; unlock(); if (lock(tmp, paths)) { qCritical() << "assertLock: Lock file was lost, but could be restored"; diff --git a/src/persistence/settings.cpp b/src/persistence/settings.cpp index 4415861567..1329c8f105 100644 --- a/src/persistence/settings.cpp +++ b/src/persistence/settings.cpp @@ -74,14 +74,14 @@ Settings::~Settings() void Settings::loadGlobal() { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; if (loaded) return; createSettingsDir(); - QDir dir(paths.getSettingsDirPath()); + const QDir dir(paths.getSettingsDirPath()); QString filePath = dir.filePath(globalSettingsFile); // If no settings file exist -- use the default one @@ -161,7 +161,7 @@ void Settings::loadGlobal() s.beginGroup("Widgets"); { - QList objectNames = s.childKeys(); + const QList objectNames = s.childKeys(); for (const QString& name : objectNames) widgetSettings[name] = s.value(name).toByteArray(); } @@ -255,7 +255,7 @@ void Settings::loadGlobal() void Settings::updateProfileData(Profile* profile, const QCommandLineParser* parser, bool newProfile) { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; if (profile == nullptr) { qWarning() << QString("Could not load new settings (profile change to nullptr)"); @@ -277,10 +277,10 @@ void Settings::updateProfileData(Profile* profile, const QCommandLineParser* par */ bool Settings::verifyProxySettings(const QCommandLineParser& parser) { - QString IPv6SettingString = parser.value("I").toLower(); - QString LANSettingString = parser.value("L").toLower(); - QString UDPSettingString = parser.value("U").toLower(); - QString proxySettingString = parser.value("proxy").toLower(); + const QString IPv6SettingString = parser.value("I").toLower(); + const QString LANSettingString = parser.value("L").toLower(); + const QString UDPSettingString = parser.value("U").toLower(); + const QString proxySettingString = parser.value("proxy").toLower(); QStringList proxySettingStrings = proxySettingString.split(":"); const QString SOCKS5 = QStringLiteral("socks5"); @@ -350,7 +350,7 @@ bool Settings::verifyProxySettings(const QCommandLineParser& parser) // TODO(Kriby): Sanity check IPv4/IPv6 addresses/hostnames? - int portNumber = proxySettingStrings[2].toInt(); + const int portNumber = proxySettingStrings[2].toInt(); if (!(portNumber > 0 && portNumber < 65536)) { qCritical() << "Invalid port number range."; } @@ -370,10 +370,10 @@ bool Settings::applyCommandLineOptions(const QCommandLineParser& parser) return false; } - QString IPv6Setting = parser.value("I").toUpper(); - QString LANSetting = parser.value("L").toUpper(); - QString UDPSetting = parser.value("U").toUpper(); - QString proxySettingString = parser.value("proxy").toUpper(); + const QString IPv6Setting = parser.value("I").toUpper(); + const QString LANSetting = parser.value("L").toUpper(); + const QString UDPSetting = parser.value("U").toUpper(); + const QString proxySettingString = parser.value("proxy").toUpper(); QStringList proxySettings = proxySettingString.split(":"); const QString SOCKS5 = QStringLiteral("SOCKS5"); @@ -421,7 +421,7 @@ bool Settings::applyCommandLineOptions(const QCommandLineParser& parser) } if (parser.isSet("U")) { - bool shouldForceTCP = UDPSetting == OFF; + const bool shouldForceTCP = UDPSetting == OFF; if (!shouldForceTCP && proxyType != ICoreSettings::ProxyType::ptNone) { qDebug() << "Cannot use UDP with proxy; disable proxy explicitly with '-P none'."; } else { @@ -437,7 +437,7 @@ bool Settings::applyCommandLineOptions(const QCommandLineParser& parser) } if (parser.isSet("L")) { - bool shouldEnableLAN = LANSetting == ON; + const bool shouldEnableLAN = LANSetting == ON; if (shouldEnableLAN && proxyType != ICoreSettings::ProxyType::ptNone) { qDebug() @@ -454,14 +454,14 @@ bool Settings::applyCommandLineOptions(const QCommandLineParser& parser) void Settings::loadPersonal(const Profile& profile, bool newProfile) { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; loadedProfile = &profile; - QDir dir(paths.getSettingsDirPath()); + const QDir dir(paths.getSettingsDirPath()); QString filePath = dir.filePath(globalSettingsFile); // load from a profile specific friend data list if possible - QString tmp = dir.filePath(profile.getName() + ".ini"); + const QString tmp = dir.filePath(profile.getName() + ".ini"); if (QFile(tmp).exists()) { // otherwise, filePath remains the global file filePath = tmp; } @@ -502,7 +502,7 @@ void Settings::loadPersonal(const Profile& profile, bool newProfile) ps.beginGroup("Friends"); { - int size = ps.beginReadArray("Friend"); + const int size = ps.beginReadArray("Friend"); friendLst.reserve(size); for (int i = 0; i < size; i++) { ps.setArrayIndex(i); @@ -529,7 +529,7 @@ void Settings::loadPersonal(const Profile& profile, bool newProfile) ps.beginGroup("Requests"); { - int size = ps.beginReadArray("Request"); + const int size = ps.beginReadArray("Request"); friendRequests.clear(); friendRequests.reserve(size); for (int i = 0; i < size; i++) { @@ -563,7 +563,7 @@ void Settings::loadPersonal(const Profile& profile, bool newProfile) ps.beginGroup("Circles"); { - int size = ps.beginReadArray("Circle"); + const int size = ps.beginReadArray("Circle"); circleLst.clear(); circleLst.reserve(size); for (int i = 0; i < size; i++) { @@ -584,8 +584,8 @@ void Settings::resetToDefault() loaded = false; // Remove file with profile settings - QDir dir(paths.getSettingsDirPath()); - QString localPath = dir.filePath(loadedProfile->getName() + ".ini"); + const QDir dir(paths.getSettingsDirPath()); + const QString localPath = dir.filePath(loadedProfile->getName() + ".ini"); QFile local(localPath); if (local.exists()) local.remove(); @@ -599,11 +599,11 @@ void Settings::saveGlobal() if (QThread::currentThread() != settingsThread) return (void)QMetaObject::invokeMethod(this, "saveGlobal"); - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; if (!loaded) return; - QString path = paths.getSettingsDirPath() + globalSettingsFile; + const QString path = paths.getSettingsDirPath() + globalSettingsFile; qDebug() << "Saving global settings at " + path; QSettings s(path, QSettings::IniFormat); @@ -746,11 +746,11 @@ void Settings::savePersonal() void Settings::savePersonal(QString profileName, const ToxEncrypt* passkey) { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; if (!loaded) return; - QString path = paths.getSettingsDirPath() + profileName + ".ini"; + const QString path = paths.getSettingsDirPath() + profileName + ".ini"; qDebug() << "Saving personal settings at " << path; @@ -841,7 +841,7 @@ void Settings::savePersonal(QString profileName, const ToxEncrypt* passkey) uint32_t Settings::makeProfileId(const QString& profile) { - QByteArray data = QCryptographicHash::hash(profile.toUtf8(), QCryptographicHash::Md5); + const QByteArray data = QCryptographicHash::hash(profile.toUtf8(), QCryptographicHash::Md5); const uint32_t* dwords = reinterpret_cast(data.constData()); return dwords[0] ^ dwords[1] ^ dwords[2] ^ dwords[3]; } @@ -853,7 +853,7 @@ Paths& Settings::getPaths() bool Settings::getEnableTestSound() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return enableTestSound; } @@ -866,7 +866,7 @@ void Settings::setEnableTestSound(bool newValue) bool Settings::getEnableIPv6() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return enableIPv6; } @@ -879,7 +879,7 @@ void Settings::setEnableIPv6(bool enabled) bool Settings::getMakeToxPortable() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return paths.isPortable(); } @@ -900,7 +900,7 @@ void Settings::setMakeToxPortable(bool newValue) bool Settings::getAutorun() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; #ifdef QTOX_PLATFORM_EXT return Platform::getAutorun(*this); @@ -912,7 +912,7 @@ bool Settings::getAutorun() const void Settings::setAutorun(bool newValue) { #ifdef QTOX_PLATFORM_EXT - bool autorun = Platform::getAutorun(*this); + bool const autorun = Platform::getAutorun(*this); if (newValue != autorun) { Platform::setAutorun(*this, newValue); @@ -925,13 +925,13 @@ void Settings::setAutorun(bool newValue) bool Settings::getAutostartInTray() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return autostartInTray; } QString Settings::getStyle() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return style; } @@ -944,7 +944,7 @@ void Settings::setStyle(const QString& newStyle) bool Settings::getShowSystemTray() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return showSystemTray; } @@ -964,7 +964,7 @@ void Settings::setUseEmoticons(bool newValue) bool Settings::getUseEmoticons() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return useEmoticons; } @@ -977,7 +977,7 @@ void Settings::setAutoSaveEnabled(bool newValue) bool Settings::getAutoSaveEnabled() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return autoSaveEnabled; } @@ -990,7 +990,7 @@ void Settings::setAutostartInTray(bool newValue) bool Settings::getCloseToTray() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return closeToTray; } @@ -1003,7 +1003,7 @@ void Settings::setCloseToTray(bool newValue) bool Settings::getMinimizeToTray() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return minimizeToTray; } @@ -1016,7 +1016,7 @@ void Settings::setMinimizeToTray(bool newValue) bool Settings::getLightTrayIcon() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return lightTrayIcon; } @@ -1029,7 +1029,7 @@ void Settings::setLightTrayIcon(bool newValue) bool Settings::getStatusChangeNotificationEnabled() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return statusChangeNotificationEnabled; } @@ -1042,7 +1042,7 @@ void Settings::setStatusChangeNotificationEnabled(bool newValue) bool Settings::getShowGroupJoinLeaveMessages() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return showGroupJoinLeaveMessages; } @@ -1068,7 +1068,7 @@ void Settings::setSpellCheckingEnabled(bool newValue) bool Settings::getNotifySound() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return notifySound; } @@ -1081,7 +1081,7 @@ void Settings::setNotifySound(bool newValue) bool Settings::getNotifyHide() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return notifyHide; } @@ -1094,7 +1094,7 @@ void Settings::setNotifyHide(bool newValue) bool Settings::getBusySound() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return busySound; } @@ -1107,7 +1107,7 @@ void Settings::setBusySound(bool newValue) bool Settings::getGroupAlwaysNotify() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return groupAlwaysNotify; } @@ -1120,7 +1120,7 @@ void Settings::setGroupAlwaysNotify(bool newValue) QString Settings::getTranslation() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return translation; } @@ -1133,7 +1133,7 @@ void Settings::setTranslation(const QString& newValue) bool Settings::getForceTCP() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return forceTCP; } @@ -1146,7 +1146,7 @@ void Settings::setForceTCP(bool enabled) bool Settings::getEnableLanDiscovery() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return enableLanDiscovery; } @@ -1159,7 +1159,7 @@ void Settings::setEnableLanDiscovery(bool enabled) QNetworkProxy Settings::getProxy() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; QNetworkProxy proxy; switch (Settings::getProxyType()) { @@ -1185,7 +1185,7 @@ QNetworkProxy Settings::getProxy() const Settings::ProxyType Settings::getProxyType() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return proxyType; } @@ -1198,7 +1198,7 @@ void Settings::setProxyType(ProxyType newValue) QString Settings::getProxyAddr() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return proxyAddr; } @@ -1211,7 +1211,7 @@ void Settings::setProxyAddr(const QString& address) quint16 Settings::getProxyPort() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return proxyPort; } @@ -1224,13 +1224,13 @@ void Settings::setProxyPort(quint16 port) QString Settings::getCurrentProfile() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return currentProfile; } uint32_t Settings::getCurrentProfileId() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return currentProfileId; } @@ -1239,7 +1239,7 @@ void Settings::setCurrentProfile(const QString& profile) bool updated = false; uint32_t newProfileId = 0; { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; if (profile != currentProfile) { currentProfile = profile; @@ -1255,7 +1255,7 @@ void Settings::setCurrentProfile(const QString& profile) bool Settings::getEnableLogging() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return enableLogging; } @@ -1268,7 +1268,7 @@ void Settings::setEnableLogging(bool newValue) int Settings::getAutoAwayTime() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return autoAwayTime; } @@ -1290,7 +1290,7 @@ void Settings::setAutoAwayTime(int newValue) QString Settings::getAutoAcceptDir(const ToxPk& id) const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; auto it = friendLst.find(id.getByteArray()); if (it != friendLst.end()) @@ -1303,7 +1303,7 @@ void Settings::setAutoAcceptDir(const ToxPk& id, const QString& dir) { bool updated = false; { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; auto& frnd = getOrInsertFriendPropRef(id); @@ -1319,7 +1319,7 @@ void Settings::setAutoAcceptDir(const ToxPk& id, const QString& dir) Settings::AutoAcceptCallFlags Settings::getAutoAcceptCall(const ToxPk& id) const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; auto it = friendLst.find(id.getByteArray()); if (it != friendLst.end()) @@ -1332,7 +1332,7 @@ void Settings::setAutoAcceptCall(const ToxPk& id, AutoAcceptCallFlags accept) { bool updated = false; { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; auto& frnd = getOrInsertFriendPropRef(id); @@ -1348,7 +1348,7 @@ void Settings::setAutoAcceptCall(const ToxPk& id, AutoAcceptCallFlags accept) bool Settings::getAutoGroupInvite(const ToxPk& id) const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; auto it = friendLst.find(id.getByteArray()); if (it != friendLst.end()) { @@ -1362,7 +1362,7 @@ void Settings::setAutoGroupInvite(const ToxPk& id, bool accept) { bool updated = false; { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; auto& frnd = getOrInsertFriendPropRef(id); @@ -1379,7 +1379,7 @@ void Settings::setAutoGroupInvite(const ToxPk& id, bool accept) QString Settings::getContactNote(const ToxPk& id) const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; auto it = friendLst.find(id.getByteArray()); if (it != friendLst.end()) @@ -1392,7 +1392,7 @@ void Settings::setContactNote(const ToxPk& id, const QString& note) { bool updated = false; { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; auto& frnd = getOrInsertFriendPropRef(id); @@ -1408,7 +1408,7 @@ void Settings::setContactNote(const ToxPk& id, const QString& note) QString Settings::getGlobalAutoAcceptDir() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return globalAutoAcceptDir; } @@ -1421,7 +1421,7 @@ void Settings::setGlobalAutoAcceptDir(const QString& newValue) size_t Settings::getMaxAutoAcceptSize() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return autoAcceptMaxSize; } @@ -1434,7 +1434,7 @@ void Settings::setMaxAutoAcceptSize(size_t size) const QFont& Settings::getChatMessageFont() const { - QMutexLocker locker(&bigLock); + const QMutexLocker locker(&bigLock); return chatMessageFont; } @@ -1449,7 +1449,7 @@ void Settings::setWidgetData(const QString& uniqueName, const QByteArray& data) { bool updated = false; { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; if (!widgetSettings.contains(uniqueName) || widgetSettings[uniqueName] != data) { widgetSettings[uniqueName] = data; @@ -1463,13 +1463,13 @@ void Settings::setWidgetData(const QString& uniqueName, const QByteArray& data) QByteArray Settings::getWidgetData(const QString& uniqueName) const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return widgetSettings.value(uniqueName); } QString Settings::getSmileyPack() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return smileyPack; } @@ -1482,7 +1482,7 @@ void Settings::setSmileyPack(const QString& value) int Settings::getEmojiFontPointSize() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return emojiFontPointSize; } @@ -1495,7 +1495,7 @@ void Settings::setEmojiFontPointSize(int value) const QString& Settings::getTimestampFormat() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return timestampFormat; } @@ -1508,7 +1508,7 @@ void Settings::setTimestampFormat(const QString& format) const QString& Settings::getDateFormat() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return dateFormat; } @@ -1521,7 +1521,7 @@ void Settings::setDateFormat(const QString& format) Settings::StyleType Settings::getStylePreference() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return stylePreference; } @@ -1534,7 +1534,7 @@ void Settings::setStylePreference(StyleType newValue) QByteArray Settings::getWindowGeometry() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return windowGeometry; } @@ -1547,7 +1547,7 @@ void Settings::setWindowGeometry(const QByteArray& value) QByteArray Settings::getWindowState() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return windowState; } @@ -1560,7 +1560,7 @@ void Settings::setWindowState(const QByteArray& value) bool Settings::getCheckUpdates() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return checkUpdates; } @@ -1573,7 +1573,7 @@ void Settings::setCheckUpdates(bool newValue) bool Settings::getNotify() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return notify; } @@ -1586,7 +1586,7 @@ void Settings::setNotify(bool newValue) bool Settings::getShowWindow() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return showWindow; } @@ -1599,7 +1599,7 @@ void Settings::setShowWindow(bool newValue) bool Settings::getDesktopNotify() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return desktopNotify; } @@ -1612,7 +1612,7 @@ void Settings::setDesktopNotify(bool enabled) QByteArray Settings::getSplitterState() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return splitterState; } @@ -1625,7 +1625,7 @@ void Settings::setSplitterState(const QByteArray& value) QByteArray Settings::getDialogGeometry() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return dialogGeometry; } @@ -1638,7 +1638,7 @@ void Settings::setDialogGeometry(const QByteArray& value) QByteArray Settings::getDialogSplitterState() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return dialogSplitterState; } @@ -1651,7 +1651,7 @@ void Settings::setDialogSplitterState(const QByteArray& value) QByteArray Settings::getDialogSettingsGeometry() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return dialogSettingsGeometry; } @@ -1664,7 +1664,7 @@ void Settings::setDialogSettingsGeometry(const QByteArray& value) bool Settings::getMinimizeOnClose() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return minimizeOnClose; } @@ -1677,7 +1677,7 @@ void Settings::setMinimizeOnClose(bool newValue) bool Settings::getTypingNotification() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return typingNotification; } @@ -1690,7 +1690,7 @@ void Settings::setTypingNotification(bool enabled) QStringList Settings::getBlackList() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return blackList; } @@ -1703,7 +1703,7 @@ void Settings::setBlackList(const QStringList& blist) QString Settings::getInDev() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return inDev; } @@ -1716,7 +1716,7 @@ void Settings::setInDev(const QString& deviceSpecifier) bool Settings::getAudioInDevEnabled() const { - QMutexLocker locker(&bigLock); + const QMutexLocker locker(&bigLock); return audioInDevEnabled; } @@ -1729,7 +1729,7 @@ void Settings::setAudioInDevEnabled(bool enabled) qreal Settings::getAudioInGainDecibel() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return audioInGainDecibel; } @@ -1742,7 +1742,7 @@ void Settings::setAudioInGainDecibel(qreal dB) qreal Settings::getAudioThreshold() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return audioThreshold; } @@ -1755,7 +1755,7 @@ void Settings::setAudioThreshold(qreal percent) QString Settings::getVideoDev() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return videoDev; } @@ -1768,7 +1768,7 @@ void Settings::setVideoDev(const QString& deviceSpecifier) QString Settings::getOutDev() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return outDev; } @@ -1781,7 +1781,7 @@ void Settings::setOutDev(const QString& deviceSpecifier) bool Settings::getAudioOutDevEnabled() const { - QMutexLocker locker(&bigLock); + const QMutexLocker locker(&bigLock); return audioOutDevEnabled; } @@ -1794,7 +1794,7 @@ void Settings::setAudioOutDevEnabled(bool enabled) int Settings::getOutVolume() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return outVolume; } @@ -1820,7 +1820,7 @@ void Settings::setAudioBitrate(int bitrate) QRect Settings::getScreenRegion() const { - QMutexLocker locker(&bigLock); + const QMutexLocker locker(&bigLock); return screenRegion; } @@ -1833,7 +1833,7 @@ void Settings::setScreenRegion(const QRect& value) bool Settings::getScreenGrabbed() const { - QMutexLocker locker(&bigLock); + const QMutexLocker locker(&bigLock); return screenGrabbed; } @@ -1846,7 +1846,7 @@ void Settings::setScreenGrabbed(bool value) QRect Settings::getCamVideoRes() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return camVideoRes; } @@ -1859,7 +1859,7 @@ void Settings::setCamVideoRes(QRect newValue) float Settings::getCamVideoFPS() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return camVideoFPS; } @@ -1872,7 +1872,7 @@ void Settings::setCamVideoFPS(float newValue) void Settings::updateFriendAddress(const QString& newAddr) { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; auto key = ToxPk(newAddr); auto& frnd = getOrInsertFriendPropRef(key); frnd.addr = newAddr; @@ -1880,7 +1880,7 @@ void Settings::updateFriendAddress(const QString& newAddr) QString Settings::getFriendAlias(const ToxPk& id) const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; auto it = friendLst.find(id.getByteArray()); if (it != friendLst.end()) return it->alias; @@ -1890,14 +1890,14 @@ QString Settings::getFriendAlias(const ToxPk& id) const void Settings::setFriendAlias(const ToxPk& id, const QString& alias) { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; auto& frnd = getOrInsertFriendPropRef(id); frnd.alias = alias; } int Settings::getFriendCircleID(const ToxPk& id) const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; auto it = friendLst.find(id.getByteArray()); if (it != friendLst.end()) return it->circleID; @@ -1907,14 +1907,14 @@ int Settings::getFriendCircleID(const ToxPk& id) const void Settings::setFriendCircleID(const ToxPk& id, int circleID) { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; auto& frnd = getOrInsertFriendPropRef(id); frnd.circleID = circleID; } QDateTime Settings::getFriendActivity(const ToxPk& id) const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; auto it = friendLst.find(id.getByteArray()); if (it != friendLst.end()) return it->activity; @@ -1924,7 +1924,7 @@ QDateTime Settings::getFriendActivity(const ToxPk& id) const void Settings::setFriendActivity(const ToxPk& id, const QDateTime& activity) { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; auto& frnd = getOrInsertFriendPropRef(id); frnd.activity = activity; } @@ -1937,13 +1937,13 @@ void Settings::saveFriendSettings(const ToxPk& id) void Settings::removeFriendSettings(const ToxPk& id) { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; friendLst.remove(id.getByteArray()); } bool Settings::getCompactLayout() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return compactLayout; } @@ -1956,7 +1956,7 @@ void Settings::setCompactLayout(bool value) Settings::FriendListSortingMode Settings::getFriendSortingMode() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return sortingMode; } @@ -1969,7 +1969,7 @@ void Settings::setFriendSortingMode(FriendListSortingMode mode) bool Settings::getSeparateWindow() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return separateWindow; } @@ -1982,7 +1982,7 @@ void Settings::setSeparateWindow(bool value) bool Settings::getDontGroupWindows() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return dontGroupWindows; } @@ -1995,7 +1995,7 @@ void Settings::setDontGroupWindows(bool value) bool Settings::getGroupchatPosition() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return groupchatPosition; } @@ -2021,26 +2021,26 @@ void Settings::setShowIdenticons(bool value) int Settings::getCircleCount() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return circleLst.size(); } QString Settings::getCircleName(int id) const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return circleLst[id].name; } void Settings::setCircleName(int id, const QString& name) { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; circleLst[id].name = name; savePersonal(); } int Settings::addCircle(const QString& name) { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; circleProp cp; cp.expanded = false; @@ -2057,19 +2057,19 @@ int Settings::addCircle(const QString& name) bool Settings::getCircleExpanded(int id) const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return circleLst[id].expanded; } void Settings::setCircleExpanded(int id, bool expanded) { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; circleLst[id].expanded = expanded; } bool Settings::addFriendRequest(const QString& friendAddress, const QString& message) { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; for (auto queued : friendRequests) { if (queued.address == friendAddress) { @@ -2090,7 +2090,7 @@ bool Settings::addFriendRequest(const QString& friendAddress, const QString& mes unsigned int Settings::getUnreadFriendRequests() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; unsigned int unreadFriendRequests = 0; for (auto request : friendRequests) if (!request.read) @@ -2101,19 +2101,19 @@ unsigned int Settings::getUnreadFriendRequests() const Settings::Request Settings::getFriendRequest(int index) const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return friendRequests.at(index); } int Settings::getFriendRequestSize() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return friendRequests.size(); } void Settings::clearUnreadFriendRequests() { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; for (auto& request : friendRequests) request.read = true; @@ -2121,13 +2121,13 @@ void Settings::clearUnreadFriendRequests() void Settings::removeFriendRequest(int index) { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; friendRequests.removeAt(index); } void Settings::readFriendRequest(int index) { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; friendRequests[index].read = true; } @@ -2143,7 +2143,7 @@ int Settings::removeCircle(int id) int Settings::getThemeColor() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return themeColor; } @@ -2156,7 +2156,7 @@ void Settings::setThemeColor(int value) bool Settings::getAutoLogin() const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; return autoLogin; } @@ -2187,9 +2187,9 @@ bool Settings::getEnableGroupChatsColor() const */ void Settings::createPersonal(const QString& basename) const { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; - QString path = paths.getSettingsDirPath() + QDir::separator() + basename + ".ini"; + const QString path = paths.getSettingsDirPath() + QDir::separator() + basename + ".ini"; qDebug() << "Creating new profile settings in " << path; QSettings ps(path, QSettings::IniFormat); @@ -2207,10 +2207,10 @@ void Settings::createPersonal(const QString& basename) const */ void Settings::createSettingsDir() { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; - QString dir = paths.getSettingsDirPath(); - QDir directory(dir); + const QString dir = paths.getSettingsDirPath(); + const QDir directory(dir); if (!directory.exists() && !directory.mkpath(directory.absolutePath())) qCritical() << "Error while creating directory " << dir; } @@ -2225,7 +2225,7 @@ void Settings::sync() return; } - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; qApp->processEvents(); } @@ -2258,7 +2258,7 @@ ICoreSettings::ProxyType Settings::fixInvalidProxyType(ICoreSettings::ProxyType template bool Settings::setVal(T& savedVal, T newVal) { - QMutexLocker locker{&bigLock}; + const QMutexLocker locker{&bigLock}; if (savedVal != newVal) { savedVal = newVal; return true; diff --git a/src/persistence/settingsserializer.cpp b/src/persistence/settingsserializer.cpp index eb462eee66..b2d768833d 100644 --- a/src/persistence/settingsserializer.cpp +++ b/src/persistence/settingsserializer.cpp @@ -96,7 +96,7 @@ void SettingsSerializer::beginGroup(const QString& prefix) { if (prefix.isEmpty()) endGroup(); - int index = groups.indexOf(prefix); + const int index = groups.indexOf(prefix); if (index >= 0) { group = index; } else { @@ -162,7 +162,7 @@ void SettingsSerializer::setValue(const QString& key, const QVariant& value) if (v) { v->value = value; } else { - Value nv{group, array, arrayIndex, key, value}; + const Value nv{group, array, arrayIndex, key, value}; if (array >= 0) arrays[array].values.append(values.size()); values.append(nv); @@ -185,7 +185,7 @@ const SettingsSerializer::Value* SettingsSerializer::findValue(const QString& ke if (a.group != group) continue; - for (int vi : a.values) { + for (const int vi : a.values) { const Value& v = values[vi]; if (v.arrayIndex == arrayIndex && v.key == key) return &v; @@ -247,7 +247,7 @@ void SettingsSerializer::save() stream.setVersion(QDataStream::Qt_5_0); // prevent signed overflow and the associated warning - int numGroups = std::max(QStringList::size_type(0), groups.size()); + const int numGroups = std::max(QStringList::size_type(0), groups.size()); for (int g = -1; g < numGroups; ++g) { // Save the group name, if any if (g != -1) { @@ -265,7 +265,7 @@ void SettingsSerializer::save() writeStream(stream, a.name.toUtf8()); writeStream(stream, vintToData(a.size)); - for (int vi : a.values) { + for (const int vi : a.values) { const Value& v = values[vi]; writeStream(stream, RecordTag::ArrayValue); writeStream(stream, vintToData(values[vi].arrayIndex)); @@ -360,7 +360,7 @@ void SettingsSerializer::readSerialized() qWarning("The personal save file is corrupted!"); return; } - int size = dataToVInt(sizeData); + const int size = dataToVInt(sizeData); arrays[array].size = qMax(size, arrays[array].size); } else if (tag == RecordTag::ArrayValue) { QByteArray indexData; @@ -394,18 +394,18 @@ void SettingsSerializer::readIni() if (!s.group().isEmpty()) beginGroup(s.group()); - for (QString k : s.childKeys()) { + for (const QString k : s.childKeys()) { setValue(k, s.value(k)); } // Add all groups gstack.push_back(QString()); - for (QString g : s.childGroups()) + for (const QString g : s.childGroups()) gstack.push_back(g); // Visit the next group, if any while (!gstack.isEmpty()) { - QString g = gstack.takeLast(); + const QString g = gstack.takeLast(); if (g.isEmpty()) { if (gstack.isEmpty()) break; @@ -423,7 +423,7 @@ void SettingsSerializer::readIni() // and its elements are all groups matching the pattern "[/]/" // Find groups that only have 1 key - std::unique_ptr groupSizes{new int[groups.size()]}; + const std::unique_ptr groupSizes{new int[groups.size()]}; memset(groupSizes.get(), 0, static_cast(groups.size()) * sizeof(int)); for (const Value& v : values) { if (v.group < 0 || v.group > groups.size()) @@ -446,7 +446,7 @@ void SettingsSerializer::readIni() Array a; a.size = v.value.toInt(); - int slashIndex = groups[static_cast(v.group)].lastIndexOf('/'); + const int slashIndex = groups[static_cast(v.group)].lastIndexOf('/'); if (slashIndex == -1) { a.group = -1; a.name = groups[static_cast(v.group)]; @@ -477,7 +477,7 @@ void SettingsSerializer::readIni() if (!groups[g].startsWith(arrayPrefix)) continue; bool ok; - int groupArrayIndex = groups[g].mid(arrayPrefix.size()).toInt(&ok); + const int groupArrayIndex = groups[g].mid(arrayPrefix.size()).toInt(&ok); if (!ok) continue; groupsToKill.append(g); @@ -502,7 +502,7 @@ void SettingsSerializer::readIni() // Clean up spurious array element groups std::sort(std::begin(groupsToKill), std::end(groupsToKill), std::greater_equal()); - for (int g : groupsToKill) { + for (const int g : groupsToKill) { if (groupSizes[static_cast(g)]) continue; @@ -536,7 +536,7 @@ void SettingsSerializer::removeGroup(int group_) void SettingsSerializer::writePackedVariant(QDataStream& stream, const QVariant& v) { assert(v.canConvert(QMetaType(QMetaType::QString))); - QString str = v.toString(); + const QString str = v.toString(); if (str == "true") writeStream(stream, QString("1")); else if (str == "false") diff --git a/src/persistence/smileypack.cpp b/src/persistence/smileypack.cpp index 09f3152d73..ee77adaeb4 100644 --- a/src/persistence/smileypack.cpp +++ b/src/persistence/smileypack.cpp @@ -119,9 +119,9 @@ QString SmileyPack::getAsRichText(const QString& key) void SmileyPack::cleanupIconsCache() { - QMutexLocker locker(&loadingMutex); + const QMutexLocker locker(&loadingMutex); for (auto it = cachedIcon.begin(); it != cachedIcon.end();) { - std::shared_ptr& icon = it->second; + const std::shared_ptr& icon = it->second; if (icon.use_count() == 1) { it = cachedIcon.erase(it); } else { @@ -160,8 +160,8 @@ QList> SmileyPack::listSmileyPacks(const QStringList& pa for (const QString& subdirectory : dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot)) { dir.cd(subdirectory); if (dir.exists(EMOTICONS_FILE_NAME)) { - QString absPath = dir.absolutePath() + QDir::separator() + EMOTICONS_FILE_NAME; - QPair p{dir.dirName(), absPath}; + const QString absPath = dir.absolutePath() + QDir::separator() + EMOTICONS_FILE_NAME; + const QPair p{dir.dirName(), absPath}; if (!smileyPacks.contains(p)) { smileyPacks.append(p); } @@ -208,7 +208,7 @@ bool SmileyPack::load(const QString& filename) */ path = QFileInfo(filename).absolutePath(); - QDomNodeList emoticonElements = doc.elementsByTagName("emoticon"); + const QDomNodeList emoticonElements = doc.elementsByTagName("emoticon"); const QString itemName = QStringLiteral("file"); const QString childName = QStringLiteral("string"); const int iconsCount = emoticonElements.size(); @@ -217,13 +217,13 @@ bool SmileyPack::load(const QString& filename) cachedIcon.clear(); for (int i = 0; i < iconsCount; ++i) { - QDomNode node = emoticonElements.at(i); - QString iconName = node.attributes().namedItem(itemName).nodeValue(); - QString iconPath = QDir{path}.filePath(iconName); + const QDomNode node = emoticonElements.at(i); + const QString iconName = node.attributes().namedItem(itemName).nodeValue(); + const QString iconPath = QDir{path}.filePath(iconName); QDomElement stringElement = node.firstChildElement(childName); QStringList emoticonList; while (!stringElement.isNull()) { - QString emoticon = stringElement.text().replace("<", "<").replace(">", ">"); + const QString emoticon = stringElement.text().replace("<", "<").replace(">", ">"); emoticonToPath.insert(emoticon, iconPath); emoticonList.append(emoticon); stringElement = stringElement.nextSibling().toElement(); @@ -282,16 +282,16 @@ void SmileyPack::constructRegex() */ QString SmileyPack::smileyfied(const QString& msg) { - QMutexLocker locker(&loadingMutex); + const QMutexLocker locker(&loadingMutex); QString result(msg); int replaceDiff = 0; QRegularExpressionMatchIterator iter = smilify.globalMatch(result); while (iter.hasNext()) { - QRegularExpressionMatch match = iter.next(); - int startPos = match.capturedStart(); - int keyLength = match.capturedLength(); - QString imgRichText = SmileyPack::getAsRichText(match.captured()); + const QRegularExpressionMatch match = iter.next(); + const int startPos = match.capturedStart(); + const int keyLength = match.capturedLength(); + const QString imgRichText = SmileyPack::getAsRichText(match.captured()); result.replace(startPos + replaceDiff, keyLength, imgRichText); replaceDiff += imgRichText.length() - keyLength; } @@ -304,7 +304,7 @@ QString SmileyPack::smileyfied(const QString& msg) */ QList SmileyPack::getEmoticons() const { - QMutexLocker locker(&loadingMutex); + const QMutexLocker locker(&loadingMutex); return emoticons; } @@ -315,7 +315,7 @@ QList SmileyPack::getEmoticons() const */ std::shared_ptr SmileyPack::getAsIcon(const QString& emoticon) const { - QMutexLocker locker(&loadingMutex); + const QMutexLocker locker(&loadingMutex); if (cachedIcon.find(emoticon) != cachedIcon.end()) { return cachedIcon[emoticon]; } diff --git a/src/platform/autorun_xdg.cpp b/src/platform/autorun_xdg.cpp index d58cc05cfb..204b329be3 100644 --- a/src/platform/autorun_xdg.cpp +++ b/src/platform/autorun_xdg.cpp @@ -12,7 +12,7 @@ namespace { QString getAutostartDirPath() { - QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); + const QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); QString config = env.value("XDG_CONFIG_HOME"); if (config.isEmpty()) config = QDir::homePath() + "/" + ".config"; @@ -44,7 +44,7 @@ inline QString profileRunCommand(const Settings& settings) bool Platform::setAutorun(const Settings& settings, bool on) { - QString dirPath = getAutostartDirPath(); + const QString dirPath = getAutostartDirPath(); QFile desktop(getAutostartFilePath(settings, dirPath)); if (on) { if (!QDir().mkpath(dirPath) || !desktop.open(QFile::WriteOnly | QFile::Truncate)) diff --git a/src/platform/camera/v4l2.cpp b/src/platform/camera/v4l2.cpp index 26b7329a99..e48795e2e4 100644 --- a/src/platform/camera/v4l2.cpp +++ b/src/platform/camera/v4l2.cpp @@ -114,7 +114,7 @@ QVector v4l2::getDeviceModes(QString devName) QVector modes; int error = 0; - int fd = deviceOpen(devName, &error); + const int fd = deviceOpen(devName, &error); if (fd < 0 || error != 0) { return modes; } @@ -154,7 +154,7 @@ QVector v4l2::getDeviceModes(QString devName) rates.append(0.0f); } - for (float rate : rates) { + for (const float rate : rates) { mode.FPS = rate; if (!modes.contains(mode)) { modes.append(std::move(mode)); @@ -183,9 +183,9 @@ QVector> v4l2::getDeviceList() deviceFiles += QString("/dev/") + QString::fromUtf8(e->d_name); closedir(dir); - for (QString file : deviceFiles) { + for (const QString& file : deviceFiles) { const std::string filePath = file.toStdString(); - int fd = open(filePath.c_str(), O_RDWR); + const int fd = open(filePath.c_str(), O_RDWR); if (fd < 0) { continue; } diff --git a/src/platform/timer_x11.cpp b/src/platform/timer_x11.cpp index bf09f9ee02..ce9b3bd5c1 100644 --- a/src/platform/timer_x11.cpp +++ b/src/platform/timer_x11.cpp @@ -21,7 +21,7 @@ uint32_t Platform::getIdleTime() } int32_t x11event = 0, x11error = 0; - static int32_t hasExtension = XScreenSaverQueryExtension(display, &x11event, &x11error); + static const int32_t hasExtension = XScreenSaverQueryExtension(display, &x11event, &x11error); if (hasExtension) { XScreenSaverInfo* info = XScreenSaverAllocInfo(); if (info) { diff --git a/src/video/cameradevice.cpp b/src/video/cameradevice.cpp index 07bb52b400..a73b93f620 100644 --- a/src/video/cameradevice.cpp +++ b/src/video/cameradevice.cpp @@ -171,7 +171,7 @@ CameraDevice* CameraDevice::open(QString devName, VideoMode mode) screen.setHeight(mode.height); } else { QScreen* defaultScreen = QApplication::primaryScreen(); - qreal pixRatio = defaultScreen->devicePixelRatio(); + const qreal pixRatio = defaultScreen->devicePixelRatio(); screen = defaultScreen->size(); // Workaround https://trac.ffmpeg.org/ticket/4574 by choping 1 px bottom and right @@ -363,7 +363,7 @@ QVector> CameraDevice::getDeviceList() if (idesktopFormat) { if (QString::fromUtf8(idesktopFormat->name) == QString("x11grab")) { QString dev = "x11grab#"; - QByteArray display = qgetenv("DISPLAY"); + const QByteArray display = qgetenv("DISPLAY"); if (display.isNull()) dev += ":0"; @@ -425,12 +425,12 @@ QVector CameraDevice::getScreenModes() QVector result; std::for_each(screens.begin(), screens.end(), [&result](QScreen* s) { - QRect rect = s->geometry(); - QPoint p = rect.topLeft(); - qreal pixRatio = s->devicePixelRatio(); + const QRect rect = s->geometry(); + const QPoint p = rect.topLeft(); + const qreal pixRatio = s->devicePixelRatio(); - VideoMode mode(rect.width() * pixRatio, rect.height() * pixRatio, p.x() * pixRatio, - p.y() * pixRatio); + const VideoMode mode(rect.width() * pixRatio, rect.height() * pixRatio, p.x() * pixRatio, + p.y() * pixRatio); result.push_back(mode); }); @@ -507,7 +507,7 @@ bool CameraDevice::betterPixelFormat(uint32_t a, uint32_t b) */ bool CameraDevice::getDefaultInputFormat() { - QMutexLocker locker(&iformatLock); + const QMutexLocker locker(&iformatLock); if (iformat) { return true; } diff --git a/src/video/camerasource.cpp b/src/video/camerasource.cpp index 1472a7c351..f3b99ee3b1 100644 --- a/src/video/camerasource.cpp +++ b/src/video/camerasource.cpp @@ -114,8 +114,8 @@ CameraSource::CameraSource(Settings& settings_) */ void CameraSource::setupDefault() { - QString deviceName_ = CameraDevice::getDefaultDeviceName(settings); - bool isScreen = CameraDevice::isScreen(deviceName_); + const QString deviceName_ = CameraDevice::getDefaultDeviceName(settings); + const bool isScreen = CameraDevice::isScreen(deviceName_); VideoMode mode_ = VideoMode(settings.getScreenRegion()); if (!isScreen) { mode_ = VideoMode(settings.getCamVideoRes()); @@ -137,7 +137,7 @@ void CameraSource::setupDevice(const QString& deviceName_, const VideoMode& mode return; } - QWriteLocker locker{&deviceMutex}; + const QWriteLocker locker{&deviceMutex}; if (deviceName_ == deviceName && mode_ == mode) { return; @@ -145,7 +145,7 @@ void CameraSource::setupDevice(const QString& deviceName_, const VideoMode& mode if (subscriptions) { // To force close, ignoring optimization - int subs = subscriptions; + const int subs = subscriptions; subscriptions = 0; closeDevice(); subscriptions = subs; @@ -168,7 +168,7 @@ bool CameraSource::isNone() const CameraSource::~CameraSource() { QWriteLocker locker{&streamMutex}; - QWriteLocker locker2{&deviceMutex}; + const QWriteLocker locker2{&deviceMutex}; // Stop the device thread deviceThread->exit(0); @@ -207,7 +207,7 @@ CameraSource::~CameraSource() void CameraSource::subscribe() { - QWriteLocker locker{&deviceMutex}; + const QWriteLocker locker{&deviceMutex}; ++subscriptions; openDevice(); @@ -215,7 +215,7 @@ void CameraSource::subscribe() void CameraSource::unsubscribe() { - QWriteLocker locker{&deviceMutex}; + const QWriteLocker locker{&deviceMutex}; --subscriptions; if (subscriptions == 0) { @@ -234,7 +234,7 @@ void CameraSource::openDevice() return; } - QWriteLocker locker{&streamMutex}; + const QWriteLocker locker{&streamMutex}; if (subscriptions == 0) { return; } @@ -350,7 +350,7 @@ void CameraSource::closeDevice() return; } - QWriteLocker locker{&streamMutex}; + const QWriteLocker locker{&streamMutex}; if (subscriptions != 0) { return; } @@ -405,8 +405,8 @@ void CameraSource::stream() #else // Forward packets to the decoder and grab the decoded frame - bool isVideo = packet.stream_index == videoStreamIndex; - bool readyToRecive = isVideo && !avcodec_send_packet(cctx, &packet); + const bool isVideo = packet.stream_index == videoStreamIndex; + const bool readyToRecive = isVideo && !avcodec_send_packet(cctx, &packet); if (readyToRecive) { AVFrame* frame = av_frame_alloc(); @@ -424,7 +424,7 @@ void CameraSource::stream() forever { - QReadLocker locker{&streamMutex}; + const QReadLocker locker{&streamMutex}; // Exit if device is no longer valid if (!device) { diff --git a/src/video/corevideosource.cpp b/src/video/corevideosource.cpp index dbed5941df..30d4e80b45 100644 --- a/src/video/corevideosource.cpp +++ b/src/video/corevideosource.cpp @@ -49,11 +49,11 @@ void CoreVideoSource::pushFrame(const vpx_image_t* vpxframe) if (stopped) return; - QMutexLocker locker(&biglock); + const QMutexLocker locker(&biglock); std::shared_ptr vframe; - int width = vpxframe->d_w; - int height = vpxframe->d_h; + const int width = vpxframe->d_w; + const int height = vpxframe->d_h; if (subscribers <= 0) return; @@ -66,7 +66,7 @@ void CoreVideoSource::pushFrame(const vpx_image_t* vpxframe) avframe->height = height; avframe->format = AV_PIX_FMT_YUV420P; - int bufSize = + const int bufSize = av_image_alloc(avframe->data, avframe->linesize, width, height, static_cast(AV_PIX_FMT_YUV420P), VideoFrame::dataAlignment); @@ -76,10 +76,10 @@ void CoreVideoSource::pushFrame(const vpx_image_t* vpxframe) } for (int i = 0; i < 3; ++i) { - int dstStride = avframe->linesize[i]; - int srcStride = vpxframe->stride[i]; - int minStride = std::min(dstStride, srcStride); - int size = (i == 0) ? height : height / 2; + const int dstStride = avframe->linesize[i]; + const int srcStride = vpxframe->stride[i]; + const int minStride = std::min(dstStride, srcStride); + const int size = (i == 0) ? height : height / 2; for (int j = 0; j < size; ++j) { uint8_t* dst = avframe->data[i] + dstStride * j; @@ -94,7 +94,7 @@ void CoreVideoSource::pushFrame(const vpx_image_t* vpxframe) void CoreVideoSource::subscribe() { - QMutexLocker locker(&biglock); + const QMutexLocker locker(&biglock); ++subscribers; } @@ -118,7 +118,7 @@ void CoreVideoSource::unsubscribe() */ void CoreVideoSource::setDeleteOnClose(bool newstate) { - QMutexLocker locker(&biglock); + const QMutexLocker locker(&biglock); deleteOnClose = newstate; } @@ -130,13 +130,13 @@ void CoreVideoSource::setDeleteOnClose(bool newstate) */ void CoreVideoSource::stopSource() { - QMutexLocker locker(&biglock); + const QMutexLocker locker(&biglock); stopped = true; emit sourceStopped(); } void CoreVideoSource::restartSource() { - QMutexLocker locker(&biglock); + const QMutexLocker locker(&biglock); stopped = false; } diff --git a/src/video/netcamview.cpp b/src/video/netcamview.cpp index bd0cadb5c2..9fc68f4df3 100644 --- a/src/video/netcamview.cpp +++ b/src/video/netcamview.cpp @@ -121,14 +121,14 @@ NetCamView::NetCamView(ToxPk friendPk_, CameraSource& cameraSource_, Settings& s connect(selfVideoSurface, &VideoSurface::ratioChanged, this, &NetCamView::updateRatio); connections += connect(videoSurface, &VideoSurface::boundaryChanged, [this]() { - QRect boundingRect = videoSurface->getBoundingRect(); + const QRect boundingRect = videoSurface->getBoundingRect(); updateFrameSize(boundingRect.size()); selfFrame->setBoundary(boundingRect); }); connections += connect(videoSurface, &VideoSurface::ratioChanged, [this]() { selfFrame->setMinimumWidth(selfFrame->minimumHeight() * selfVideoSurface->getRatio()); - QRect boundingRect = videoSurface->getBoundingRect(); + const QRect boundingRect = videoSurface->getBoundingRect(); updateFrameSize(boundingRect.size()); selfFrame->resetBoundary(boundingRect); }); @@ -142,13 +142,13 @@ NetCamView::NetCamView(ToxPk friendPk_, CameraSource& cameraSource_, Settings& s videoSurface->setAvatar(pixmap); }); - QRect videoSize = settings.getCamVideoRes(); + const QRect videoSize = settings.getCamVideoRes(); qDebug() << "SIZER" << videoSize; } NetCamView::~NetCamView() { - for (QMetaObject::Connection conn : connections) + for (const QMetaObject::Connection& conn : connections) disconnect(conn); } @@ -208,9 +208,9 @@ void NetCamView::updateFrameSize(QSize size) QSize NetCamView::getSurfaceMinSize() { - QSize surfaceSize = videoSurface->minimumSize(); - QSize buttonSize = toggleMessagesButton->size(); - QSize panelSize(0, 45); + const QSize surfaceSize = videoSurface->minimumSize(); + const QSize buttonSize = toggleMessagesButton->size(); + const QSize panelSize(0, 45); return surfaceSize + buttonSize + panelSize; } @@ -324,7 +324,7 @@ void NetCamView::updateButtonState(QPushButton* btn, bool active) void NetCamView::keyPressEvent(QKeyEvent* event) { - int key = event->key(); + const int key = event->key(); if (key == Qt::Key_Escape && isFullScreen()) { exitFullScreen(); } diff --git a/src/video/videoframe.cpp b/src/video/videoframe.cpp index c28eb156c4..c23e3e0fa5 100644 --- a/src/video/videoframe.cpp +++ b/src/video/videoframe.cpp @@ -173,7 +173,7 @@ VideoFrame::~VideoFrame() bool VideoFrame::isValid() { frameLock.lockForRead(); - bool retValue = frameBuffer.size() > 0; + const bool retValue = frameBuffer.size() > 0; frameLock.unlock(); return retValue; @@ -240,7 +240,7 @@ void VideoFrame::untrackFrames(const VideoFrame::IDType& sourceID, bool releaseF sourceMutex.lock(); for (auto& frameIterator : refsMap[sourceID]) { - std::shared_ptr frame = frameIterator.second.lock(); + const std::shared_ptr frame = frameIterator.second.lock(); if (frame) { frame->releaseFrame(); @@ -451,8 +451,8 @@ bool VideoFrame::FrameBufferKey::operator!=(const FrameBufferKey& other) const */ size_t VideoFrame::FrameBufferKey::hash(const FrameBufferKey& key) { - std::hash intHasher; - std::hash boolHasher; + const std::hash intHasher; + const std::hash boolHasher; // Use java-style hash function to combine fields // See: https://en.wikipedia.org/wiki/Java_hashCode%28%29#hashCode.28.29_in_general @@ -518,14 +518,14 @@ AVFrame* VideoFrame::retrieveAVFrame(const QSize& dimensions, const int pixelFor * We attempt to obtain a unaligned frame first because an unaligned linesize corresponds * to a data aligned frame. */ - FrameBufferKey frameKey = getFrameKey(dimensions, pixelFormat, false); + const FrameBufferKey frameKey = getFrameKey(dimensions, pixelFormat, false); if (frameBuffer.count(frameKey) > 0) { return frameBuffer[frameKey]; } } - FrameBufferKey frameKey = getFrameKey(dimensions, pixelFormat, true); + const FrameBufferKey frameKey = getFrameKey(dimensions, pixelFormat, true); if (frameBuffer.count(frameKey) > 0) { return frameBuffer[frameKey]; @@ -582,7 +582,7 @@ AVFrame* VideoFrame::generateAVFrame(const QSize& dimensions, const int pixelFor } // Bilinear is better for shrinking, bicubic better for upscaling - int resizeAlgo = sourceDimensions.width() > dimensions.width() ? SWS_BILINEAR : SWS_BICUBIC; + const int resizeAlgo = sourceDimensions.width() > dimensions.width() ? SWS_BILINEAR : SWS_BICUBIC; SwsContext* swsCtx = sws_getContext(sourceDimensions.width(), sourceDimensions.height(), @@ -632,7 +632,7 @@ AVFrame* VideoFrame::generateAVFrame(const QSize& dimensions, const int pixelFor */ AVFrame* VideoFrame::storeAVFrame(AVFrame* frame, const QSize& dimensions, const int pixelFormat) { - FrameBufferKey frameKey = getFrameKey(dimensions, pixelFormat, frame->linesize[0]); + const FrameBufferKey frameKey = getFrameKey(dimensions, pixelFormat, frame->linesize[0]); // We check the prescence of the frame in case of double-computation if (frameBuffer.count(frameKey) > 0) { diff --git a/src/video/videosurface.cpp b/src/video/videosurface.cpp index 1284f70995..f39a8387ea 100644 --- a/src/video/videosurface.cpp +++ b/src/video/videosurface.cpp @@ -135,7 +135,7 @@ void VideoSurface::onNewFrameAvailable(const std::shared_ptr& newFra newSize = lastFrame->getSourceDimensions().size(); unlock(); - float newRatio = getSizeRatio(newSize); + const float newRatio = getSizeRatio(newSize); if (!qFuzzyCompare(newRatio, ratio) && isVisible()) { ratio = newRatio; @@ -162,7 +162,7 @@ void VideoSurface::paintEvent(QPaintEvent* event) QPainter painter(this); painter.fillRect(painter.viewport(), Qt::black); if (lastFrame) { - QImage frame = lastFrame->toQImage(rect().size()); + const QImage frame = lastFrame->toQImage(rect().size()); if (frame.isNull()) lastFrame.reset(); painter.drawImage(boundingRect, frame, frame.rect(), Qt::NoFormatConversion); @@ -200,8 +200,8 @@ void VideoSurface::recalulateBounds() } else { QPoint pos; QSize size; - QSize usableSize = contentsRect().size(); - int possibleWidth = usableSize.height() * ratio; + const QSize usableSize = contentsRect().size(); + const int possibleWidth = usableSize.height() * ratio; if (possibleWidth > usableSize.width()) size = (QSize(usableSize.width(), usableSize.width() / ratio)); diff --git a/src/widget/categorywidget.cpp b/src/widget/categorywidget.cpp index 6278804df7..7f2c4b6f5f 100644 --- a/src/widget/categorywidget.cpp +++ b/src/widget/categorywidget.cpp @@ -131,9 +131,9 @@ void CategoryWidget::removeFriendWidget(FriendWidget* w, Status::Status s) void CategoryWidget::updateStatus() { - QString online = QString::number(listLayout->friendOnlineCount()); - QString offline = QString::number(listLayout->friendTotalCount()); - QString text = online + QStringLiteral(" / ") + offline; + const QString online = QString::number(listLayout->friendOnlineCount()); + const QString offline = QString::number(listLayout->friendTotalCount()); + const QString text = online + QStringLiteral(" / ") + offline; statusLabel->setText(text); } @@ -148,7 +148,7 @@ void CategoryWidget::search(const QString& searchString, bool updateAll, bool hi if (updateAll) { listLayout->searchChatrooms(searchString, hideOnline, hideOffline); } - bool inCategory = searchString.isEmpty() && !(hideOnline && hideOffline); + const bool inCategory = searchString.isEmpty() && !(hideOnline && hideOffline); setVisible(inCategory || listLayout->hasChatrooms()); } diff --git a/src/widget/circlewidget.cpp b/src/widget/circlewidget.cpp index e45b6f549d..2a527bee82 100644 --- a/src/widget/circlewidget.cpp +++ b/src/widget/circlewidget.cpp @@ -98,7 +98,7 @@ void CircleWidget::contextMenuEvent(QContextMenuEvent* event) friendListWidget->removeCircleWidget(this); - int replacedCircle = settings.removeCircle(id); + const int replacedCircle = settings.removeCircle(id); auto circleReplace = circleList.find(replacedCircle); if (circleReplace != circleList.end()) @@ -141,7 +141,7 @@ void CircleWidget::dragEnterEvent(QDragEnterEvent* event) if (!event->mimeData()->hasFormat("toxPk")) { return; } - ToxPk toxPk(event->mimeData()->data("toxPk")); + const ToxPk toxPk(event->mimeData()->data("toxPk")); Friend* f = friendList.findFriend(toxPk); if (f != nullptr) event->acceptProposedAction(); @@ -169,13 +169,13 @@ void CircleWidget::dropEvent(QDropEvent* event) return; } // Check, that the user has a friend with the same ToxId - ToxPk toxPk{event->mimeData()->data("toxPk")}; + const ToxPk toxPk{event->mimeData()->data("toxPk")}; Friend* f = friendList.findFriend(toxPk); if (!f) return; // Save CircleWidget before changing the Id - int circleId = settings.getFriendCircleID(toxPk); + const int circleId = settings.getFriendCircleID(toxPk); CircleWidget* circleWidget = getFromID(circleId); addFriendWidget(widget, f->getStatus()); @@ -202,7 +202,7 @@ void CircleWidget::onExpand() void CircleWidget::onAddFriendWidget(FriendWidget* w) { const Friend* f = w->getFriend(); - ToxPk toxId = f->getPublicKey(); + const ToxPk toxId = f->getPublicKey(); settings.setFriendCircleID(toxId, id); } diff --git a/src/widget/contentdialog.cpp b/src/widget/contentdialog.cpp index 756a63798b..f2aeec34ce 100644 --- a/src/widget/contentdialog.cpp +++ b/src/widget/contentdialog.cpp @@ -101,7 +101,7 @@ ContentDialog::ContentDialog(const Core& core, Settings& settings_, Style& style setAttribute(Qt::WA_DeleteOnClose); setObjectName("detached"); - QByteArray geometry = settings.getDialogGeometry(); + const QByteArray geometry = settings.getDialogGeometry(); if (!geometry.isNull()) { restoreGeometry(geometry); @@ -302,16 +302,16 @@ void ContentDialog::cycleChats(bool forward, bool inverse) } if (!inverse && index == currentLayout->count() - 1) { - bool groupsOnTop = settings.getGroupchatPosition(); - bool offlineEmpty = friendLayout->getLayoutOffline()->isEmpty(); - bool onlineEmpty = friendLayout->getLayoutOnline()->isEmpty(); - bool groupsEmpty = groupLayout.getLayout()->isEmpty(); - bool isCurOffline = currentLayout == friendLayout->getLayoutOffline(); - bool isCurOnline = currentLayout == friendLayout->getLayoutOnline(); - bool isCurGroup = currentLayout == groupLayout.getLayout(); - bool nextIsEmpty = (isCurOnline && offlineEmpty && (groupsEmpty || groupsOnTop)) - || (isCurGroup && offlineEmpty && (onlineEmpty || !groupsOnTop)) - || (isCurOffline); + const bool groupsOnTop = settings.getGroupchatPosition(); + const bool offlineEmpty = friendLayout->getLayoutOffline()->isEmpty(); + const bool onlineEmpty = friendLayout->getLayoutOnline()->isEmpty(); + const bool groupsEmpty = groupLayout.getLayout()->isEmpty(); + const bool isCurOffline = currentLayout == friendLayout->getLayoutOffline(); + const bool isCurOnline = currentLayout == friendLayout->getLayoutOnline(); + const bool isCurGroup = currentLayout == groupLayout.getLayout(); + const bool nextIsEmpty = (isCurOnline && offlineEmpty && (groupsEmpty || groupsOnTop)) + || (isCurGroup && offlineEmpty && (onlineEmpty || !groupsOnTop)) + || (isCurOffline); if (nextIsEmpty) { forward = !forward; @@ -322,13 +322,13 @@ void ContentDialog::cycleChats(bool forward, bool inverse) // If goes out of the layout, then go to the next and skip empty. This loop goes more // then 1 time, because for empty layout index will be out of interval (0 < 0 || 0 >= 0) while (index < 0 || index >= currentLayout->count()) { - int oldCount = currentLayout->count(); + const int oldCount = currentLayout->count(); currentLayout = nextLayout(currentLayout, forward); if (currentLayout == nullptr) { qFatal("Layouts changed during iteration"); break; } - int newCount = currentLayout->count(); + const int newCount = currentLayout->count(); if (index < 0) { index = newCount - 1; } else if (index >= oldCount) { @@ -352,7 +352,7 @@ void ContentDialog::onVideoShow(QSize size) } videoSurfaceSize = size; - QSize minSize_ = minimumSize(); + const QSize minSize_ = minimumSize(); setMinimumSize(minSize_ + videoSurfaceSize); } @@ -363,7 +363,7 @@ void ContentDialog::onVideoHide() return; } - QSize minSize_ = minimumSize(); + const QSize minSize_ = minimumSize(); setMinimumSize(minSize_ - videoSurfaceSize); videoSurfaceSize = QSize(); } @@ -381,13 +381,13 @@ void ContentDialog::updateTitleAndStatusIcon() setWindowTitle(username + QStringLiteral(" - ") + activeChatroomWidget->getTitle()); - bool isGroupchat = activeChatroomWidget->getGroup() != nullptr; + const bool isGroupchat = activeChatroomWidget->getGroup() != nullptr; if (isGroupchat) { setWindowIcon(QIcon(":/img/group.svg")); return; } - Status::Status currentStatus = activeChatroomWidget->getFriend()->getStatus(); + const Status::Status currentStatus = activeChatroomWidget->getFriend()->getStatus(); setWindowIcon(QIcon{Status::getIconPath(currentStatus)}); } @@ -397,7 +397,7 @@ void ContentDialog::updateTitleAndStatusIcon() */ void ContentDialog::reorderLayouts(bool newGroupOnTop) { - bool oldGroupOnTop = layouts.first() == groupLayout.getLayout(); + const bool oldGroupOnTop = layouts.first() == groupLayout.getLayout(); if (newGroupOnTop != oldGroupOnTop) { layouts.swapItemsAt(0, 1); } @@ -467,13 +467,13 @@ void ContentDialog::dragEnterEvent(QDragEnterEvent* event) GroupWidget* group = qobject_cast(o); if (frnd) { assert(event->mimeData()->hasFormat("toxPk")); - ToxPk toxPk{event->mimeData()->data("toxPk")}; + const ToxPk toxPk{event->mimeData()->data("toxPk")}; Friend* contact = friendList.findFriend(toxPk); if (!contact) { return; } - ToxPk friendId = contact->getPublicKey(); + const ToxPk friendId = contact->getPublicKey(); // If friend is already in a dialog then you can't drop friend where it already is. if (!hasChat(friendId)) { @@ -481,7 +481,7 @@ void ContentDialog::dragEnterEvent(QDragEnterEvent* event) } } else if (group) { assert(event->mimeData()->hasFormat("groupId")); - GroupId groupId = GroupId{event->mimeData()->data("groupId")}; + const GroupId groupId = GroupId{event->mimeData()->data("groupId")}; Group* contact = groupList.findGroup(groupId); if (!contact) { return; @@ -638,7 +638,7 @@ void ContentDialog::updateFriendWidget(const ToxPk& friendPk, QString alias) Friend* f = friendList.findFriend(friendPk); FriendWidget* friendWidget = qobject_cast(chatWidgets[friendPk]); - Status::Status status = f->getStatus(); + const Status::Status status = f->getStatus(); friendLayout->addFriendWidget(friendWidget, status); } @@ -691,13 +691,13 @@ bool ContentDialog::hasChat(const ChatId& chatId) const */ QLayout* ContentDialog::nextLayout(QLayout* layout, bool forward) const { - int index = layouts.indexOf(layout); + const int index = layouts.indexOf(layout); if (index == -1) { return nullptr; } int next = forward ? index + 1 : index - 1; - size_t size = layouts.size(); + const size_t size = layouts.size(); next = (next + size) % size; return layouts[next]; diff --git a/src/widget/emoticonswidget.cpp b/src/widget/emoticonswidget.cpp index 5d0f10f650..fc963ca0d9 100644 --- a/src/widget/emoticonswidget.cpp +++ b/src/widget/emoticonswidget.cpp @@ -36,8 +36,8 @@ EmoticonsWidget::EmoticonsWidget(SmileyPack& smileyPack, Settings& settings, Sty const int itemsPerPage = maxRows * maxCols; const QList& emoticons = smileyPack.getEmoticons(); - int itemCount = emoticons.size(); - int pageCount = ceil(float(itemCount) / float(itemsPerPage)); + const int itemCount = emoticons.size(); + const int pageCount = ceil(float(itemCount) / float(itemsPerPage)); int currPage = 0; int currItem = 0; int row = 0; @@ -75,7 +75,7 @@ EmoticonsWidget::EmoticonsWidget(SmileyPack& smileyPack, Settings& settings, Sty for (const QStringList& set : emoticons) { QPushButton* button = new QPushButton; - std::shared_ptr icon = smileyPack.getAsIcon(set[0]); + const std::shared_ptr icon = smileyPack.getAsIcon(set[0]); emoticonsIcons.append(icon); button->setIcon(icon->pixmap(size)); button->setToolTip(set.join(" ")); @@ -115,7 +115,7 @@ void EmoticonsWidget::onSmileyClicked() // emit insert emoticon QWidget* sender = qobject_cast(QObject::sender()); if (sender) { - QString sequence = + const QString sequence = sender->property("sequence").toString().replace("<", "<").replace(">", ">"); emit insertEmoticon(sequence); } @@ -125,7 +125,7 @@ void EmoticonsWidget::onPageButtonClicked() { QWidget* sender = qobject_cast(QObject::sender()); if (sender) { - int page = sender->property("pageIndex").toInt(); + const int page = sender->property("pageIndex").toInt(); stack.setCurrentIndex(page); } } @@ -163,7 +163,7 @@ void EmoticonsWidget::wheelEvent(QWheelEvent* e) void EmoticonsWidget::PageButtonsUpdate() { - QList pageButtons = findChildren(QString()); + const QList pageButtons = findChildren(QString()); foreach (QRadioButton* t_pageButton, pageButtons) { if (t_pageButton->property("pageIndex").toInt() == stack.currentIndex()) t_pageButton->setChecked(true); diff --git a/src/widget/flowlayout.cpp b/src/widget/flowlayout.cpp index c6f2e0877c..e6b8ace6b0 100644 --- a/src/widget/flowlayout.cpp +++ b/src/widget/flowlayout.cpp @@ -5,14 +5,17 @@ #include "flowlayout.h" //! [1] -FlowLayout::FlowLayout(QWidget *parent, int margin, int hSpacing, int vSpacing) - : QLayout(parent), m_hSpace(hSpacing), m_vSpace(vSpacing) +FlowLayout::FlowLayout(QWidget* parent, int margin, int hSpacing, int vSpacing) + : QLayout(parent) + , m_hSpace(hSpacing) + , m_vSpace(vSpacing) { setContentsMargins(margin, margin, margin, margin); } FlowLayout::FlowLayout(int margin, int hSpacing, int vSpacing) - : m_hSpace(hSpacing), m_vSpace(vSpacing) + : m_hSpace(hSpacing) + , m_vSpace(vSpacing) { setContentsMargins(margin, margin, margin, margin); } @@ -21,14 +24,14 @@ FlowLayout::FlowLayout(int margin, int hSpacing, int vSpacing) //! [2] FlowLayout::~FlowLayout() { - QLayoutItem *item; + QLayoutItem* item; while ((item = takeAt(0))) delete item; } //! [2] //! [3] -void FlowLayout::addItem(QLayoutItem *item) +void FlowLayout::addItem(QLayoutItem* item) { itemList.append(item); } @@ -60,12 +63,12 @@ int FlowLayout::count() const return itemList.size(); } -QLayoutItem *FlowLayout::itemAt(int index) const +QLayoutItem* FlowLayout::itemAt(int index) const { return itemList.value(index); } -QLayoutItem *FlowLayout::takeAt(int index) +QLayoutItem* FlowLayout::takeAt(int index) { if (index >= 0 && index < itemList.size()) return itemList.takeAt(index); @@ -76,7 +79,7 @@ QLayoutItem *FlowLayout::takeAt(int index) //! [6] Qt::Orientations FlowLayout::expandingDirections() const { - return { }; + return {}; } //! [6] @@ -88,13 +91,13 @@ bool FlowLayout::hasHeightForWidth() const int FlowLayout::heightForWidth(int width) const { - int height = doLayout(QRect(0, 0, width, 0), true); + const int height = doLayout(QRect(0, 0, width, 0), true); return height; } //! [7] //! [8] -void FlowLayout::setGeometry(const QRect &rect) +void FlowLayout::setGeometry(const QRect& rect) { QLayout::setGeometry(rect); doLayout(rect, false); @@ -108,7 +111,7 @@ QSize FlowLayout::sizeHint() const QSize FlowLayout::minimumSize() const { QSize size; - for (const QLayoutItem *item : std::as_const(itemList)) + for (const QLayoutItem* item : std::as_const(itemList)) size = size.expandedTo(item->minimumSize()); const QMargins margins = contentsMargins(); @@ -118,29 +121,29 @@ QSize FlowLayout::minimumSize() const //! [8] //! [9] -int FlowLayout::doLayout(const QRect &rect, bool testOnly) const +int FlowLayout::doLayout(const QRect& rect, bool testOnly) const { int left, top, right, bottom; getContentsMargins(&left, &top, &right, &bottom); - QRect effectiveRect = rect.adjusted(+left, +top, -right, -bottom); + const QRect effectiveRect = rect.adjusted(+left, +top, -right, -bottom); int x = effectiveRect.x(); int y = effectiveRect.y(); int lineHeight = 0; -//! [9] + //! [9] -//! [10] - for (QLayoutItem *item : std::as_const(itemList)) { - const QWidget *wid = item->widget(); + //! [10] + for (QLayoutItem* item : std::as_const(itemList)) { + const QWidget* wid = item->widget(); int spaceX = horizontalSpacing(); if (spaceX == -1) - spaceX = wid->style()->layoutSpacing( - QSizePolicy::PushButton, QSizePolicy::PushButton, Qt::Horizontal); + 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); -//! [10] -//! [11] + spaceY = wid->style()->layoutSpacing(QSizePolicy::PushButton, QSizePolicy::PushButton, + Qt::Vertical); + //! [10] + //! [11] int nextX = x + item->sizeHint().width() + spaceX; if (nextX - spaceX > effectiveRect.right() && lineHeight > 0) { x = effectiveRect.x(); @@ -161,14 +164,14 @@ int FlowLayout::doLayout(const QRect &rect, bool testOnly) const //! [12] int FlowLayout::smartSpacing(QStyle::PixelMetric pm) const { - QObject *parent = this->parent(); + QObject* parent = this->parent(); if (!parent) { return -1; } else if (parent->isWidgetType()) { - QWidget *pw = static_cast(parent); + QWidget* pw = static_cast(parent); return pw->style()->pixelMetric(pm, nullptr, pw); } else { - return static_cast(parent)->spacing(); + return static_cast(parent)->spacing(); } } //! [12] diff --git a/src/widget/form/addfriendform.cpp b/src/widget/form/addfriendform.cpp index d64ab9fc56..2cc6251e12 100644 --- a/src/widget/form/addfriendform.cpp +++ b/src/widget/form/addfriendform.cpp @@ -113,7 +113,7 @@ AddFriendForm::AddFriendForm(ToxId ownId_, Settings& settings_, Style& style_, const int size = settings.getFriendRequestSize(); for (int i = 0; i < size; ++i) { - Settings::Request request = settings.getFriendRequest(i); + const Settings::Request request = settings.getFriendRequest(i); addFriendRequestWidget(request.address, request.message); } } @@ -188,7 +188,7 @@ void AddFriendForm::onUsernameSet(const QString& username) void AddFriendForm::addFriend(const QString& idText) { - ToxId friendId(idText); + const ToxId friendId(idText); if (!friendId.isValid()) { messageBoxManager.showWarning(tr("Couldn't add friend"), @@ -302,7 +302,7 @@ void AddFriendForm::deleteFriendRequest(const ToxId& toxId_) { const int size = settings.getFriendRequestSize(); for (int i = 0; i < size; ++i) { - Settings::Request request = settings.getFriendRequest(i); + const Settings::Request request = settings.getFriendRequest(i); if (toxId_.getPublicKey() == ToxPk(request.address)) { settings.removeFriendRequest(i); return; @@ -416,7 +416,7 @@ void AddFriendForm::addFriendRequestWidget(const QString& friendAddress_, const void AddFriendForm::removeFriendRequestWidget(QWidget* friendWidget) { - int index = requestsLayout->indexOf(friendWidget); + const int index = requestsLayout->indexOf(friendWidget); requestsLayout->removeWidget(friendWidget); acceptButtons.removeAt(index); rejectButtons.removeAt(index); diff --git a/src/widget/form/chatform.cpp b/src/widget/form/chatform.cpp index 29115bfa1d..e36f4f4c04 100644 --- a/src/widget/form/chatform.cpp +++ b/src/widget/form/chatform.cpp @@ -66,14 +66,14 @@ const QString ChatForm::ACTION_PREFIX = QStringLiteral("/me "); namespace { QString secondsToDHMS(quint32 duration) { - QString res; - QString cD = ChatForm::tr("Call duration: "); - quint32 seconds = duration % 60; + const QString res; + const QString cD = ChatForm::tr("Call duration: "); + const quint32 seconds = duration % 60; duration /= 60; - quint32 minutes = duration % 60; + const quint32 minutes = duration % 60; duration /= 60; - quint32 hours = duration % 24; - quint32 days = duration / 24; + const quint32 hours = duration % 24; + const quint32 days = duration / 24; // I assume no one will ever have call longer than a month if (days) { @@ -259,7 +259,7 @@ void ChatForm::onTextEditChanged() return; } - bool isTypingNow = !msgEdit->toPlainText().isEmpty(); + const bool isTypingNow = !msgEdit->toPlainText().isEmpty(); if (isTyping != isTypingNow) { core.sendTyping(f->getId(), isTypingNow); if (isTypingNow) { @@ -272,16 +272,16 @@ void ChatForm::onTextEditChanged() void ChatForm::onAttachClicked() { - QStringList paths = QFileDialog::getOpenFileNames(Q_NULLPTR, tr("Send a file"), - QDir::homePath(), QString(), nullptr); + const QStringList paths = QFileDialog::getOpenFileNames(Q_NULLPTR, tr("Send a file"), + QDir::homePath(), QString(), nullptr); if (paths.isEmpty()) { return; } - for (QString path : paths) { + for (const QString& path : paths) { QFile file(path); - QString fileName = QFileInfo(path).fileName(); + const QString fileName = QFileInfo(path).fileName(); if (!file.exists() || !file.open(QIODevice::ReadOnly)) { QMessageBox::warning(this, tr("Unable to open"), tr("qTox wasn't able to open %1").arg(fileName)); @@ -296,7 +296,7 @@ void ChatForm::onAttachClicked() continue; } - qint64 filesize = file.size(); + const qint64 filesize = file.size(); core.getCoreFile()->sendFile(f->getId(), fileName, path, filesize); } } @@ -307,7 +307,7 @@ void ChatForm::onAvInvite(uint32_t friendId, bool video) return; } - QString displayedName = f->getDisplayedName(); + const QString displayedName = f->getDisplayedName(); SystemMessage systemMessage; systemMessage.messageType = SystemMessageType::incomingCall; @@ -378,7 +378,7 @@ void ChatForm::showOutgoingCall(bool video) void ChatForm::onAnswerCallTriggered(bool video) { headWidget->removeCallConfirm(); - uint32_t friendId = f->getId(); + const uint32_t friendId = f->getId(); emit stopNotification(); emit acceptCall(friendId); @@ -403,7 +403,7 @@ void ChatForm::onRejectCallTriggered() void ChatForm::onCallTriggered() { CoreAV* av = core.getAv(); - uint32_t friendId = f->getId(); + const uint32_t friendId = f->getId(); if (av->isCallStarted(f)) { av->cancelCall(friendId); } else if (av->startCall(friendId, false)) { @@ -414,7 +414,7 @@ void ChatForm::onCallTriggered() void ChatForm::onVideoCallTriggered() { CoreAV* av = core.getAv(); - uint32_t friendId = f->getId(); + const uint32_t friendId = f->getId(); if (av->isCallStarted(f)) { // TODO: We want to activate video on the active call. if (av->isCallVideoEnabled(f)) { @@ -464,7 +464,7 @@ void ChatForm::onFriendStatusChanged(const ToxPk& friendPk, Status::Status statu updateCallButtons(); if (settings.getStatusChangeNotificationEnabled()) { - QString fStatus = Status::getTitle(status); + const QString fStatus = Status::getTitle(status); addSystemInfoMessage(QDateTime::currentDateTime(), SystemMessageType::peerStateChange, {f->getDisplayedName(), fStatus}); } @@ -503,7 +503,7 @@ void ChatForm::onAvatarChanged(const ToxPk& friendPk, const QPixmap& pic) std::unique_ptr ChatForm::createNetcam() { qDebug() << "creating netcam"; - uint32_t friendId = f->getId(); + const uint32_t friendId = f->getId(); std::unique_ptr view = std::unique_ptr( new NetCamView(f->getPublicKey(), cameraSource, settings, style, profile, this)); CoreAV* av = core.getAv(); @@ -532,7 +532,7 @@ void ChatForm::dropEvent(QDropEvent* ev) QFileInfo info(url.path()); QFile file(info.absoluteFilePath()); - QString urlString = url.toString(); + const QString urlString = url.toString(); if (url.isValid() && !url.isLocalFile() && urlString.length() < static_cast(tox_max_message_length())) { messageDispatcher.sendMessage(false, urlString); @@ -540,7 +540,7 @@ void ChatForm::dropEvent(QDropEvent* ev) continue; } - QString fileName = info.fileName(); + const QString fileName = info.fileName(); if (!file.exists() || !file.open(QIODevice::ReadOnly)) { info.setFile(url.toLocalFile()); file.setFileName(info.absoluteFilePath()); @@ -610,19 +610,20 @@ void ChatForm::sendImageFromPreview() // https://en.wikipedia.org/wiki/ISO_8601 // Windows has to be supported, thus filename can't have `:` in it :/ // Format should be: `qTox_Screenshot_yyyy-MM-dd HH-mm-ss.zzz.png` - QString filepath = QString("%1images%2qTox_Image_%3.png") - .arg(settings.getPaths().getAppDataDirPath()) - .arg(QDir::separator()) - .arg(QDateTime::currentDateTime().toString("yyyy-MM-dd HH-mm-ss.zzz")); + const QString filepath = + QString("%1images%2qTox_Image_%3.png") + .arg(settings.getPaths().getAppDataDirPath()) + .arg(QDir::separator()) + .arg(QDateTime::currentDateTime().toString("yyyy-MM-dd HH-mm-ss.zzz")); QFile file(filepath); if (file.open(QFile::ReadWrite)) { imagePreviewSource.save(&file, "PNG"); - qint64 filesize = file.size(); + const qint64 filesize = file.size(); imagePreview->hide(); imagePreviewSource = QPixmap(); file.close(); - QFileInfo fi(file); + const QFileInfo fi(file); CoreFile* coreFile = core.getCoreFile(); coreFile->sendFile(f->getId(), fi.fileName(), fi.filePath(), filesize); } else { @@ -635,7 +636,7 @@ void ChatForm::sendImageFromPreview() void ChatForm::onCopyStatusMessage() { // make sure to copy not truncated text directly from the friend - QString text = f->getStatusMessage(); + const QString text = f->getStatusMessage(); QClipboard* clipboard = QApplication::clipboard(); if (clipboard) { clipboard->setText(text, QClipboard::Clipboard); @@ -645,8 +646,8 @@ void ChatForm::onCopyStatusMessage() void ChatForm::updateMuteMicButton() { const CoreAV* av = core.getAv(); - bool active = av->isCallActive(f); - bool inputMuted = av->isCallInputMuted(f); + const bool active = av->isCallActive(f); + const bool inputMuted = av->isCallInputMuted(f); headWidget->updateMuteMicButton(active, inputMuted); if (netcam) { netcam->updateMuteMicButton(inputMuted); @@ -656,8 +657,8 @@ void ChatForm::updateMuteMicButton() void ChatForm::updateMuteVolButton() { const CoreAV* av = core.getAv(); - bool active = av->isCallActive(f); - bool outputMuted = av->isCallOutputMuted(f); + const bool active = av->isCallActive(f); + const bool outputMuted = av->isCallOutputMuted(f); headWidget->updateMuteVolButton(active, outputMuted); if (netcam) { netcam->updateMuteVolButton(outputMuted); @@ -681,8 +682,8 @@ void ChatForm::stopCounter(bool error) if (!callDurationTimer) { return; } - QString dhms = secondsToDHMS(timeElapsed.elapsed() / 1000); - QString name = f->getDisplayedName(); + const QString dhms = secondsToDHMS(timeElapsed.elapsed() / 1000); + const QString name = f->getDisplayedName(); auto messageType = error ? SystemMessageType::unexpectedCallEnd : SystemMessageType::callEnd; // TODO: add notification once notifications are implemented @@ -703,7 +704,7 @@ void ChatForm::onUpdateTime() void ChatForm::setFriendTyping(bool isTyping_) { chatWidget->setTypingNotificationVisible(isTyping_); - QString name = f->getDisplayedName(); + const QString name = f->getDisplayedName(); chatWidget->setTypingNotificationName(name); } @@ -750,7 +751,7 @@ void ChatForm::showNetcam() bodySplitter->insertWidget(0, netcam.get()); bodySplitter->setCollapsible(0, false); - QSize minSize = netcam->getSurfaceMinSize(); + const QSize minSize = netcam->getSurfaceMinSize(); ContentDialog* current = contentDialogManager.current(); if (current) { current->onVideoShow(minSize); diff --git a/src/widget/form/filesform.cpp b/src/widget/form/filesform.cpp index acdeadf624..25ab3f24aa 100644 --- a/src/widget/form/filesform.cpp +++ b/src/widget/form/filesform.cpp @@ -27,28 +27,28 @@ namespace { QRect pauseRect(const QStyleOptionViewItem& option) { - float controlSize = option.rect.height() * 0.8f; - float rectWidth = option.rect.width(); - float buttonHorizontalArea = rectWidth / 2; + const float controlSize = option.rect.height() * 0.8f; + const float rectWidth = option.rect.width(); + const float buttonHorizontalArea = rectWidth / 2; // To center the button, we find the horizontal center and subtract half // our width from it - int buttonXPos = std::round(option.rect.x() + buttonHorizontalArea / 2 - controlSize / 2); - int buttonYPos = std::round(option.rect.y() + option.rect.height() * 0.1f); + const int buttonXPos = std::round(option.rect.x() + buttonHorizontalArea / 2 - controlSize / 2); + const int buttonYPos = std::round(option.rect.y() + option.rect.height() * 0.1f); return QRect(buttonXPos, buttonYPos, controlSize, controlSize); } QRect stopRect(const QStyleOptionViewItem& option) { - float controlSize = option.rect.height() * 0.8; - float rectWidth = option.rect.width(); - float buttonHorizontalArea = rectWidth / 2; + const float controlSize = option.rect.height() * 0.8; + const float rectWidth = option.rect.width(); + const float buttonHorizontalArea = rectWidth / 2; // To center the button, we find the horizontal center and subtract half // our width from it - int buttonXPos = std::round(option.rect.x() + buttonHorizontalArea + buttonHorizontalArea / 2 - - controlSize / 2); - int buttonYPos = std::round(option.rect.y() + option.rect.height() * 0.1f); + const int buttonXPos = std::round(option.rect.x() + buttonHorizontalArea + + buttonHorizontalArea / 2 - controlSize / 2); + const int buttonYPos = std::round(option.rect.y() + option.rect.height() * 0.1f); return QRect(buttonXPos, buttonYPos, controlSize, controlSize); } @@ -325,7 +325,7 @@ void Delegate::paint(QPainter* painter, const QStyleOptionViewItem& option, cons const auto column = toFileTransferListColumn(index.column()); switch (column) { case Column::progress: { - int progress = index.data().toInt(); + const int progress = index.data().toInt(); QStyleOptionProgressBar progressBarOption; progressBarOption.rect = option.rect; @@ -345,13 +345,13 @@ void Delegate::paint(QPainter* painter, const QStyleOptionViewItem& option, cons return; } const auto localPaused = data.toBool(); - QPixmap pausePixmap = + const QPixmap pausePixmap = localPaused ? QPixmap(style.getImagePath("fileTransferInstance/arrow_black.svg", settings)) : QPixmap(style.getImagePath("fileTransferInstance/pause_dark.svg", settings)); QApplication::style()->drawItemPixmap(painter, pauseRect(option), Qt::AlignCenter, pausePixmap); - QPixmap stopPixmap(style.getImagePath("fileTransferInstance/no_dark.svg", settings)); + const QPixmap stopPixmap(style.getImagePath("fileTransferInstance/no_dark.svg", settings)); QApplication::style()->drawItemPixmap(painter, stopRect(option), Qt::AlignCenter, stopPixmap); return; } diff --git a/src/widget/form/genericchatform.cpp b/src/widget/form/genericchatform.cpp index e3aa1eb39c..f5a0368118 100644 --- a/src/widget/form/genericchatform.cpp +++ b/src/widget/form/genericchatform.cpp @@ -64,11 +64,11 @@ const QString FONT_STYLE[]{"normal", "italic", "oblique"}; */ QString fontToCss(const QFont& font, const QString& name) { - QString result{"%1{" - "font-family: \"%2\"; " - "font-size: %3px; " - "font-style: \"%4\"; " - "font-weight: normal;}"}; + const QString result{"%1{" + "font-family: \"%2\"; " + "font-size: %3px; " + "font-style: \"%4\"; " + "font-weight: normal;}"}; return result.arg(name).arg(font.family()).arg(font.pixelSize()).arg(FONT_STYLE[font.style()]); } } // namespace @@ -297,8 +297,8 @@ GenericChatForm::~GenericChatForm() void GenericChatForm::adjustFileMenuPosition() { - QPoint pos = fileButton->mapTo(bodySplitter, QPoint()); - QSize size = fileFlyout->size(); + const QPoint pos = fileButton->mapTo(bodySplitter, QPoint()); + const QSize size = fileFlyout->size(); fileFlyout->move(pos.x() - size.width(), pos.y()); } @@ -423,8 +423,8 @@ void GenericChatForm::onChatContextMenuRequested(QPoint pos) bool clickedOnLink = false; Text* clickedText = qobject_cast(chatWidget->getContentFromGlobalPos(pos)); if (clickedText) { - QPointF scenePos = chatWidget->mapToScene(chatWidget->mapFromGlobal(pos)); - QString linkTarget = clickedText->getLinkAt(scenePos); + const QPointF scenePos = chatWidget->mapToScene(chatWidget->mapFromGlobal(pos)); + const QString linkTarget = clickedText->getLinkAt(scenePos); if (!linkTarget.isEmpty()) { clickedOnLink = true; copyLinkAction->setData(linkTarget); @@ -439,7 +439,7 @@ void GenericChatForm::onSendTriggered() { auto msg = msgEdit->toPlainText(); - bool isAction = msg.startsWith(ChatForm::ACTION_PREFIX, Qt::CaseInsensitive); + const bool isAction = msg.startsWith(ChatForm::ACTION_PREFIX, Qt::CaseInsensitive); if (isAction) { msg.remove(0, ChatForm::ACTION_PREFIX.length()); } @@ -467,7 +467,7 @@ void GenericChatForm::onEmoteButtonClicked() QWidget* sender = qobject_cast(QObject::sender()); if (sender) { - QPoint pos = + const QPoint pos = -QPoint(widget.sizeHint().width() / 2, widget.sizeHint().height()) - QPoint(0, 10); widget.exec(sender->mapToGlobal(pos)); } @@ -542,7 +542,7 @@ void GenericChatForm::clearChatArea() void GenericChatForm::clearChatArea(bool confirm, bool inform) { if (confirm) { - QMessageBox::StandardButton mboxResult = + const QMessageBox::StandardButton mboxResult = QMessageBox::question(this, tr("Confirmation"), tr("Are you sure that you want to clear all displayed messages?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No); @@ -597,13 +597,13 @@ bool GenericChatForm::eventFilter(QObject* object, QEvent* event) break; case QEvent::Leave: { - QPoint flyPos = fileFlyout->mapToGlobal(QPoint()); - QSize flySize = fileFlyout->size(); + const QPoint flyPos = fileFlyout->mapToGlobal(QPoint()); + const QSize flySize = fileFlyout->size(); - QPoint filePos = fileButton->mapToGlobal(QPoint()); - QSize fileSize = fileButton->size(); + const QPoint filePos = fileButton->mapToGlobal(QPoint()); + const QSize fileSize = fileButton->size(); - QRect region = QRect(flyPos, flySize).united(QRect(filePos, fileSize)); + const QRect region = QRect(flyPos, flySize).united(QRect(filePos, fileSize)); if (!region.contains(QCursor::pos())) hideFileMenu(); @@ -624,7 +624,7 @@ bool GenericChatForm::eventFilter(QObject* object, QEvent* event) void GenericChatForm::quoteSelectedText() { - QString selectedText = chatWidget->getSelectedText(); + const QString selectedText = chatWidget->getSelectedText(); if (selectedText.isEmpty()) return; @@ -647,7 +647,7 @@ void GenericChatForm::quoteSelectedText() */ void GenericChatForm::copyLink() { - QString linkText = copyLinkAction->data().toString(); + const QString linkText = copyLinkAction->data().toString(); QApplication::clipboard()->setText(linkText); } @@ -669,7 +669,7 @@ void GenericChatForm::onLoadHistory() void GenericChatForm::onExportChat() { - QString path = QFileDialog::getSaveFileName(Q_NULLPTR, tr("Save chat log")); + const QString path = QFileDialog::getSaveFileName(Q_NULLPTR, tr("Save chat log")); if (path.isEmpty()) { return; } @@ -686,9 +686,9 @@ void GenericChatForm::onExportChat() continue; } - QString timestamp = item.getTimestamp().time().toString("hh:mm:ss"); - QString datestamp = item.getTimestamp().date().toString("yyyy-MM-dd"); - QString author = item.getDisplayName(); + const QString timestamp = item.getTimestamp().time().toString("hh:mm:ss"); + const QString datestamp = item.getTimestamp().date().toString("yyyy-MM-dd"); + const QString author = item.getDisplayName(); buffer = buffer % QString{datestamp % '\t' % timestamp % '\t' % author % '\t' diff --git a/src/widget/form/groupchatform.cpp b/src/widget/form/groupchatform.cpp index 41992edef8..d165b6c4c4 100644 --- a/src/widget/form/groupchatform.cpp +++ b/src/widget/form/groupchatform.cpp @@ -285,7 +285,7 @@ void GroupChatForm::dragEnterEvent(QDragEnterEvent* ev) if (!ev->mimeData()->hasFormat("toxPk")) { return; } - ToxPk toxPk{ev->mimeData()->data("toxPk")}; + const ToxPk toxPk{ev->mimeData()->data("toxPk")}; Friend* frnd = friendList.findFriend(toxPk); if (frnd) ev->acceptProposedAction(); @@ -296,13 +296,13 @@ void GroupChatForm::dropEvent(QDropEvent* ev) if (!ev->mimeData()->hasFormat("toxPk")) { return; } - ToxPk toxPk{ev->mimeData()->data("toxPk")}; + const ToxPk toxPk{ev->mimeData()->data("toxPk")}; Friend* frnd = friendList.findFriend(toxPk); if (!frnd) return; - int friendId = frnd->getId(); - int groupId = group->getId(); + const int friendId = frnd->getId(); + const int groupId = group->getId(); if (Status::isOnline(frnd->getStatus())) { core.groupInviteFriend(friendId, groupId); } diff --git a/src/widget/form/groupinviteform.cpp b/src/widget/form/groupinviteform.cpp index eb8ccd010e..656dc6350e 100644 --- a/src/widget/form/groupinviteform.cpp +++ b/src/widget/form/groupinviteform.cpp @@ -78,7 +78,7 @@ GroupInviteForm::~GroupInviteForm() */ bool GroupInviteForm::isShown() const { - bool result = isVisible(); + const bool result = isVisible(); if (result) { headWidget->window()->windowHandle()->alert(0); } diff --git a/src/widget/form/groupinvitewidget.cpp b/src/widget/form/groupinvitewidget.cpp index 14967b18ed..e63caa21eb 100644 --- a/src/widget/form/groupinvitewidget.cpp +++ b/src/widget/form/groupinvitewidget.cpp @@ -46,10 +46,10 @@ GroupInviteWidget::GroupInviteWidget(QWidget* parent, const GroupInvite& invite, */ void GroupInviteWidget::retranslateUi() { - QString name = core.getFriendUsername(inviteInfo.getFriendId()); - QDateTime inviteDate = inviteInfo.getInviteDate(); - QString date = inviteDate.toString(settings.getDateFormat()); - QString time = inviteDate.toString(settings.getTimestampFormat()); + const QString name = core.getFriendUsername(inviteInfo.getFriendId()); + const QDateTime inviteDate = inviteInfo.getInviteDate(); + const QString date = inviteDate.toString(settings.getDateFormat()); + const QString time = inviteDate.toString(settings.getTimestampFormat()); inviteMessageLabel->setText( tr("Invited by %1 on %2 at %3.").arg("%1").arg(name.toHtmlEscaped(), date, time)); diff --git a/src/widget/form/loadhistorydialog.cpp b/src/widget/form/loadhistorydialog.cpp index c3c2460cec..1978c3e01a 100644 --- a/src/widget/form/loadhistorydialog.cpp +++ b/src/widget/form/loadhistorydialog.cpp @@ -41,7 +41,7 @@ QDateTime LoadHistoryDialog::getFromDate() QDateTime res(ui->fromDate->selectedDate().startOfDay()); if (res.date().month() != ui->fromDate->monthShown() || res.date().year() != ui->fromDate->yearShown()) { - QDate newDate(ui->fromDate->yearShown(), ui->fromDate->monthShown(), 1); + const QDate newDate(ui->fromDate->yearShown(), ui->fromDate->monthShown(), 1); res.setDate(newDate); } @@ -60,8 +60,8 @@ void LoadHistoryDialog::setInfoLabel(const QString& info) void LoadHistoryDialog::highlightDates(int year, int month) { - QDate monthStart(year, month, 1); - QDate monthEnd(year, month + 1, 1); + const QDate monthStart(year, month, 1); + const QDate monthEnd(year, month + 1, 1); // Max 31 days in a month auto dateIdxs = chatLog->getDateIdxs(monthStart, 31); diff --git a/src/widget/form/profileform.cpp b/src/widget/form/profileform.cpp index a616cd15d6..8e4e630461 100644 --- a/src/widget/form/profileform.cpp +++ b/src/widget/form/profileform.cpp @@ -190,12 +190,12 @@ void ProfileForm::show(ContentLayout* contentLayout) contentLayout->mainContent->layout()->addWidget(this); QWidget::show(); prFileLabelUpdate(); - bool portable = settings.getMakeToxPortable(); - QString defaultPath = QDir(settings.getPaths().getSettingsDirPath()).path().trimmed(); - QString appPath = QApplication::applicationDirPath(); - QString dirPath = portable ? appPath : defaultPath; + const bool portable = settings.getMakeToxPortable(); + const QString defaultPath = QDir(settings.getPaths().getSettingsDirPath()).path().trimmed(); + const QString appPath = QApplication::applicationDirPath(); + const QString dirPath = portable ? appPath : defaultPath; - QString dirPrLink = + const QString dirPrLink = tr("Current profile location: %1").arg(QString("%1").arg(dirPath)); bodyUI->dirPrLink->setText(dirPrLink); @@ -258,7 +258,7 @@ void ProfileForm::onSelfAvatarLoaded(const QPixmap& pic) void ProfileForm::setToxId(const ToxId& id) { - QString idString = id.toString(); + const QString idString = id.toString(); static const QString ToxIdColor = QStringLiteral("%1" "%2" "%3"); @@ -432,7 +432,7 @@ void ProfileForm::onChangePassClicked() return; } - QString newPass = dialog->getPassword(); + const QString newPass = dialog->getPassword(); if (!profileInfo->setPassword(newPass)) { messageBoxManager.showInfo(CAN_NOT_CHANGE_PASSWORD.first, CAN_NOT_CHANGE_PASSWORD.second); } diff --git a/src/widget/form/setpassworddialog.cpp b/src/widget/form/setpassworddialog.cpp index 32aa99e1a7..c30d821d82 100644 --- a/src/widget/form/setpassworddialog.cpp +++ b/src/widget/form/setpassworddialog.cpp @@ -43,7 +43,7 @@ SetPasswordDialog::~SetPasswordDialog() void SetPasswordDialog::onPasswordEdit() { - QString pswd = ui->passwordlineEdit->text(); + const QString pswd = ui->passwordlineEdit->text(); if (pswd.isEmpty()) { ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); @@ -69,7 +69,7 @@ int SetPasswordDialog::getPasswordStrength(QString pass) double fscore = 0; QHash charCounts; - for (QChar c : pass) { + for (const QChar c : pass) { charCounts[c]++; fscore += 5. / charCounts[c]; } diff --git a/src/widget/form/settings/aboutform.cpp b/src/widget/form/settings/aboutform.cpp index 692f8ab762..1895fb9f95 100644 --- a/src/widget/form/settings/aboutform.cpp +++ b/src/widget/form/settings/aboutform.cpp @@ -83,9 +83,9 @@ void AboutForm::replaceVersions() // TODO: When we finally have stable releases: build-in a way to tell // nightly builds from stable releases. - QString TOXCORE_VERSION = QString::number(tox_version_major()) + "." - + QString::number(tox_version_minor()) + "." - + QString::number(tox_version_patch()); + const QString TOXCORE_VERSION = QString::number(tox_version_major()) + "." + + QString::number(tox_version_minor()) + "." + + QString::number(tox_version_patch()); bodyUI->youAreUsing->setText(tr("You are using qTox version %1.").arg(QString(GIT_DESCRIBE))); @@ -101,7 +101,7 @@ void AboutForm::replaceVersions() qDebug() << "AboutForm not showing updates, qTox built without UPDATE_CHECK"; #endif - QString commitLink = "https://github.com/TokTok/qTox/commit/" + QString(GIT_VERSION); + QString const commitLink = "https://github.com/TokTok/qTox/commit/" + QString(GIT_VERSION); bodyUI->gitVersion->setText( tr("Commit hash: %1").arg(createLink(commitLink, QString(GIT_VERSION)))); @@ -155,7 +155,7 @@ void AboutForm::replaceVersions() QString("%1").arg(tr("Click here to report a bug.")))); - QString authorInfo = + const QString authorInfo = QString("

%1

%2

") .arg(tr("Original author: %1").arg(createLink("https://github.com/tux3", "tux3"))) .arg( diff --git a/src/widget/form/settings/advancedform.cpp b/src/widget/form/settings/advancedform.cpp index 3f67ca2552..335587aa62 100644 --- a/src/widget/form/settings/advancedform.cpp +++ b/src/widget/form/settings/advancedform.cpp @@ -41,12 +41,12 @@ AdvancedForm::AdvancedForm(Settings& settings_, Style& style, IMessageBoxManager bodyUI->cbEnableIPv6->setChecked(settings.getEnableIPv6()); bodyUI->cbMakeToxPortable->setChecked(settings.getMakeToxPortable()); bodyUI->proxyAddr->setText(settings.getProxyAddr()); - quint16 port = settings.getProxyPort(); + const quint16 port = settings.getProxyPort(); if (port > 0) { bodyUI->proxyPort->setValue(port); } - int index = static_cast(settings.getProxyType()); + const int index = static_cast(settings.getProxyType()); bodyUI->proxyType->setCurrentIndex(index); on_proxyType_currentIndexChanged(index); const bool udpEnabled = @@ -55,7 +55,7 @@ AdvancedForm::AdvancedForm(Settings& settings_, Style& style, IMessageBoxManager bodyUI->cbEnableLanDiscovery->setChecked(settings.getEnableLanDiscovery() && udpEnabled); bodyUI->cbEnableLanDiscovery->setEnabled(udpEnabled); - QString warningBody = + const QString warningBody = tr("Unless you %1 know what you are doing, " "please do %2 change anything here. Changes " "made here may lead to problems with qTox, and even " @@ -65,10 +65,10 @@ AdvancedForm::AdvancedForm(Settings& settings_, Style& style, IMessageBoxManager .arg(QString("%1").arg(tr("not"))) .arg(QString("

%1

").arg(tr("Changes here are applied only after restarting qTox."))); - QString warning = QString("
" - "

%1

%2

") - .arg(tr("IMPORTANT NOTE")) - .arg(warningBody); + const QString warning = QString("
" + "

%1

%2

") + .arg(tr("IMPORTANT NOTE")) + .arg(warningBody); bodyUI->warningLabel->setText(warning); @@ -88,7 +88,7 @@ void AdvancedForm::on_cbMakeToxPortable_stateChanged() } void AdvancedForm::on_btnExportLog_clicked() { - QString savefile = + const QString savefile = QFileDialog::getSaveFileName(Q_NULLPTR, tr("Save file"), QString{}, tr("Logs (*.log)")); if (savefile.isNull() || savefile.isEmpty()) { @@ -96,10 +96,10 @@ void AdvancedForm::on_btnExportLog_clicked() return; } - QString logFileDir = settings.getPaths().getAppCacheDirPath(); - QString logfile = logFileDir + "qtox.log"; + const QString logFileDir = settings.getPaths().getAppCacheDirPath(); + const QString logfile = logFileDir + "qtox.log"; - QFile file(logfile); + const QFile file(logfile); if (file.exists()) { qDebug() << "Found debug log for copying"; } else { @@ -115,8 +115,8 @@ void AdvancedForm::on_btnExportLog_clicked() void AdvancedForm::on_btnCopyDebug_clicked() { - QString logFileDir = settings.getPaths().getAppCacheDirPath(); - QString logfile = logFileDir + "qtox.log"; + const QString logFileDir = settings.getPaths().getAppCacheDirPath(); + const QString logfile = logFileDir + "qtox.log"; QFile file(logfile); if (!file.exists()) { @@ -146,7 +146,7 @@ void AdvancedForm::on_btnCopyDebug_clicked() void AdvancedForm::on_resetButton_clicked() { const QString titile = tr("Reset settings"); - bool result = + const bool result = messageBoxManager.askQuestion(titile, tr("All settings will be reset to default. Are you sure?"), tr("Yes"), tr("No")); @@ -193,7 +193,7 @@ void AdvancedForm::on_proxyPort_valueChanged(int port) void AdvancedForm::on_proxyType_currentIndexChanged(int index) { - Settings::ProxyType proxytype = static_cast(index); + const Settings::ProxyType proxytype = static_cast(index); const bool proxyEnabled = proxytype != Settings::ProxyType::ptNone; bodyUI->proxyAddr->setEnabled(proxyEnabled); @@ -210,7 +210,7 @@ void AdvancedForm::on_proxyType_currentIndexChanged(int index) */ void AdvancedForm::retranslateUi() { - int proxyType = bodyUI->proxyType->currentIndex(); + const int proxyType = bodyUI->proxyType->currentIndex(); bodyUI->retranslateUi(this); bodyUI->proxyType->setCurrentIndex(proxyType); } diff --git a/src/widget/form/settings/avform.cpp b/src/widget/form/settings/avform.cpp index 34995e090a..2285fd0e49 100644 --- a/src/widget/form/settings/avform.cpp +++ b/src/widget/form/settings/avform.cpp @@ -136,7 +136,7 @@ void AVForm::showEvent(QShowEvent* event) void AVForm::open(const QString& devName, const VideoMode& mode) { - QRect rect = mode.toRect(); + const QRect rect = mode.toRect(); videoSettings->setCamVideoRes(rect); videoSettings->setCamVideoFPS(static_cast(mode.FPS)); camera.setupDevice(devName, mode); @@ -162,15 +162,15 @@ void AVForm::setVolume(qreal value) void AVForm::on_videoModescomboBox_currentIndexChanged(int index) { assert(0 <= index && index < videoModes.size()); - int devIndex = videoDevCombobox->currentIndex(); + const int devIndex = videoDevCombobox->currentIndex(); assert(0 <= devIndex && devIndex < videoDeviceList.size()); - QString devName = videoDeviceList[devIndex].first; - VideoMode newMode = videoModes[index]; + const QString devName = videoDeviceList[devIndex].first; + const VideoMode newMode = videoModes[index]; if (CameraDevice::isScreen(devName) && newMode == VideoMode()) { if (videoSettings->getScreenGrabbed()) { - VideoMode screenMode(videoSettings->getScreenRegion()); + const VideoMode screenMode(videoSettings->getScreenRegion()); open(devName, screenMode); return; } @@ -181,7 +181,7 @@ void AVForm::on_videoModescomboBox_currentIndexChanged(int index) mode.height = mode.height / 2 * 2; // Needed, if the virtual screen origin is the top left corner of the primary screen - QRect screen = QApplication::primaryScreen()->virtualGeometry(); + const QRect screen = QApplication::primaryScreen()->virtualGeometry(); mode.x += screen.x(); mode.y += screen.y(); @@ -224,15 +224,15 @@ void AVForm::selectBestModes(QVector& allVideoModes) std::map bestModeInds; for (int i = 0; i < allVideoModes.size(); ++i) { - VideoMode mode = allVideoModes[i]; + const VideoMode mode = allVideoModes[i]; // PS3-Cam protection, everything above 60fps makes no sense if (mode.FPS > 60) continue; for (auto iter = idealModes.begin(); iter != idealModes.end(); ++iter) { - int res = iter->first; - VideoMode idealMode = iter->second; + const int res = iter->first; + const VideoMode idealMode = iter->second; // don't take approximately correct resolutions unless they really // are close if (mode.norm(idealMode) > idealMode.tolerance()) @@ -243,8 +243,8 @@ void AVForm::selectBestModes(QVector& allVideoModes) continue; } - int index = bestModeInds[res]; - VideoMode best = allVideoModes[index]; + const int index = bestModeInds[res]; + const VideoMode best = allVideoModes[index]; if (mode.norm(idealMode) < best.norm(idealMode)) { bestModeInds[res] = i; continue; @@ -257,7 +257,8 @@ void AVForm::selectBestModes(QVector& allVideoModes) continue; } - bool better = CameraDevice::betterPixelFormat(mode.pixel_format, best.pixel_format); + const bool better = + CameraDevice::betterPixelFormat(mode.pixel_format, best.pixel_format); if (mode.FPS >= best.FPS && better) bestModeInds[res] = i; } @@ -266,12 +267,12 @@ void AVForm::selectBestModes(QVector& allVideoModes) QVector newVideoModes; for (auto it = bestModeInds.rbegin(); it != bestModeInds.rend(); ++it) { - VideoMode mode_ = allVideoModes[it->second]; + const VideoMode mode_ = allVideoModes[it->second]; if (newVideoModes.empty()) { newVideoModes.push_back(mode_); } else { - int size = getModeSize(mode_); + const int size = getModeSize(mode_); auto result = std::find_if(newVideoModes.cbegin(), newVideoModes.cend(), [size](VideoMode mode) { return getModeSize(mode) == size; }); @@ -285,14 +286,15 @@ void AVForm::selectBestModes(QVector& allVideoModes) void AVForm::fillCameraModesComboBox() { qDebug() << "selected Modes:"; - bool previouslyBlocked = videoModescomboBox->blockSignals(true); + const bool previouslyBlocked = videoModescomboBox->blockSignals(true); videoModescomboBox->clear(); for (int i = 0; i < videoModes.size(); ++i) { - VideoMode mode = videoModes[i]; + const VideoMode mode = videoModes[i]; QString str; - std::string pixelFormat = CameraDevice::getPixelFormatString(mode.pixel_format).toStdString(); + const std::string pixelFormat = + CameraDevice::getPixelFormatString(mode.pixel_format).toStdString(); qDebug("width: %d, height: %d, FPS: %f, pixel format: %s", mode.width, mode.height, static_cast(mode.FPS), pixelFormat.c_str()); @@ -313,11 +315,11 @@ void AVForm::fillCameraModesComboBox() int AVForm::searchPreferredIndex() { - QRect prefRes = videoSettings->getCamVideoRes(); - float prefFPS = videoSettings->getCamVideoFPS(); + const QRect prefRes = videoSettings->getCamVideoRes(); + const float prefFPS = videoSettings->getCamVideoFPS(); for (int i = 0; i < videoModes.size(); ++i) { - VideoMode mode = videoModes[i]; + const VideoMode mode = videoModes[i]; if (mode.width == prefRes.width() && mode.height == prefRes.height() && (qAbs(mode.FPS - prefFPS) < 0.0001f)) { return i; @@ -329,12 +331,13 @@ int AVForm::searchPreferredIndex() void AVForm::fillScreenModesComboBox() { - bool previouslyBlocked = videoModescomboBox->blockSignals(true); + const bool previouslyBlocked = videoModescomboBox->blockSignals(true); videoModescomboBox->clear(); for (int i = 0; i < videoModes.size(); ++i) { - VideoMode mode = videoModes[i]; - std::string pixelFormat = CameraDevice::getPixelFormatString(mode.pixel_format).toStdString(); + const VideoMode mode = videoModes[i]; + const std::string pixelFormat = + CameraDevice::getPixelFormatString(mode.pixel_format).toStdString(); qDebug("%dx%d+%d,%d FPS: %f, pixel format: %s\n", mode.width, mode.height, mode.x, mode.y, static_cast(mode.FPS), pixelFormat.c_str()); @@ -372,11 +375,11 @@ void AVForm::updateVideoModes(int curIndex) qWarning() << "Invalid index:" << curIndex; return; } - QString devName = videoDeviceList[curIndex].first; + const QString devName = videoDeviceList[curIndex].first; QVector allVideoModes = CameraDevice::getVideoModes(devName); qDebug("available Modes:"); - bool isScreen = CameraDevice::isScreen(devName); + const bool isScreen = CameraDevice::isScreen(devName); if (isScreen) { // Add extra video mode to region selection allVideoModes.push_back(VideoMode()); @@ -388,7 +391,7 @@ void AVForm::updateVideoModes(int curIndex) fillCameraModesComboBox(); } - int preferedIndex = searchPreferredIndex(); + const int preferedIndex = searchPreferredIndex(); if (preferedIndex != -1) { videoSettings->setScreenGrabbed(false); videoModescomboBox->blockSignals(true); @@ -399,8 +402,8 @@ void AVForm::updateVideoModes(int curIndex) } if (isScreen) { - QRect rect = videoSettings->getScreenRegion(); - VideoMode mode(rect); + const QRect rect = videoSettings->getScreenRegion(); + const VideoMode mode(rect); videoSettings->setScreenGrabbed(true); videoModescomboBox->setCurrentIndex(videoModes.size() - 1); @@ -413,7 +416,7 @@ void AVForm::updateVideoModes(int curIndex) // and the best FPS for that resolution. // If we picked the lowest resolution, the quality would be awful // but if we picked the largest, FPS would be bad and thus quality bad too. - int mid = (videoModes.size() - 1) / 2; + const int mid = (videoModes.size() - 1) / 2; videoModescomboBox->setCurrentIndex(mid); } @@ -422,9 +425,9 @@ void AVForm::on_videoDevCombobox_currentIndexChanged(int index) assert(0 <= index && index < videoDeviceList.size()); videoSettings->setScreenGrabbed(false); - QString dev = videoDeviceList[index].first; + const QString dev = videoDeviceList[index].first; videoSettings->setVideoDev(dev); - bool previouslyBlocked = videoModescomboBox->blockSignals(true); + const bool previouslyBlocked = videoModescomboBox->blockSignals(true); updateVideoModes(index); videoModescomboBox->blockSignals(previouslyBlocked); @@ -432,7 +435,7 @@ void AVForm::on_videoDevCombobox_currentIndexChanged(int index) return; } - int modeIndex = videoModescomboBox->currentIndex(); + const int modeIndex = videoModescomboBox->currentIndex(); VideoMode mode = VideoMode(); if (0 <= modeIndex && modeIndex < videoModes.size()) { mode = videoModes[modeIndex]; @@ -452,13 +455,13 @@ void AVForm::on_audioQualityComboBox_currentIndexChanged(int index) void AVForm::getVideoDevices() { - QString settingsInDev = videoSettings->getVideoDev(); + const QString settingsInDev = videoSettings->getVideoDev(); int videoDevIndex = 0; videoDeviceList = CameraDevice::getDeviceList(); // prevent currentIndexChanged to be fired while adding items videoDevCombobox->blockSignals(true); videoDevCombobox->clear(); - for (QPair device : videoDeviceList) { + for (const QPair& device : videoDeviceList) { videoDevCombobox->addItem(device.second); if (device.first == settingsInDev) videoDevIndex = videoDevCombobox->count() - 1; @@ -484,9 +487,9 @@ void AVForm::getAudioInDevices() inDevCombobox->blockSignals(false); int idx = 0; - bool enabled = audioSettings->getAudioInDevEnabled(); + const bool enabled = audioSettings->getAudioInDevEnabled(); if (enabled && deviceNames.size() > 1) { - QString dev = audioSettings->getInDev(); + const QString dev = audioSettings->getInDev(); idx = qMax(deviceNames.indexOf(dev), 1); } inDevCombobox->setCurrentIndex(idx); @@ -503,9 +506,9 @@ void AVForm::getAudioOutDevices() outDevCombobox->blockSignals(false); int idx = 0; - bool enabled = audioSettings->getAudioOutDevEnabled(); + const bool enabled = audioSettings->getAudioOutDevEnabled(); if (enabled && deviceNames.size() > 1) { - QString dev = audioSettings->getOutDev(); + const QString dev = audioSettings->getOutDev(); idx = qMax(deviceNames.indexOf(dev), 1); } outDevCombobox->setCurrentIndex(idx); diff --git a/src/widget/form/settings/generalform.cpp b/src/widget/form/settings/generalform.cpp index e9986e1975..d692c0e3d1 100644 --- a/src/widget/form/settings/generalform.cpp +++ b/src/widget/form/settings/generalform.cpp @@ -127,7 +127,7 @@ GeneralForm::GeneralForm(SettingsWidget* myParent, Settings& settings_, Style& s bodyUI->cbSpellChecking->setChecked(settings.getSpellCheckingEnabled()); bodyUI->lightTrayIcon->setChecked(settings.getLightTrayIcon()); - bool showSystemTray = settings.getShowSystemTray(); + const bool showSystemTray = settings.getShowSystemTray(); bodyUI->showSystemTray->setChecked(showSystemTray); bodyUI->startInTray->setChecked(settings.getAutostartInTray()); @@ -218,7 +218,7 @@ void GeneralForm::on_groupJoinLeaveMessages_stateChanged() void GeneralForm::on_autoAwaySpinBox_editingFinished() { - int minutes = bodyUI->autoAwaySpinBox->value(); + const int minutes = bodyUI->autoAwaySpinBox->value(); settings.setAutoAwayTime(minutes); } @@ -229,7 +229,7 @@ void GeneralForm::on_autoacceptFiles_stateChanged() void GeneralForm::on_autoSaveFilesDir_clicked() { - QString previousDir = settings.getGlobalAutoAcceptDir(); + const QString previousDir = settings.getGlobalAutoAcceptDir(); QString directory = QFileDialog::getExistingDirectory(Q_NULLPTR, tr("Choose an auto accept directory", "popup title"), diff --git a/src/widget/form/settings/privacyform.cpp b/src/widget/form/settings/privacyform.cpp index 098c322c94..63caf02b35 100644 --- a/src/widget/form/settings/privacyform.cpp +++ b/src/widget/form/settings/privacyform.cpp @@ -69,10 +69,10 @@ void PrivacyForm::on_cbTypingNotification_stateChanged() void PrivacyForm::on_nospamLineEdit_editingFinished() { - QString newNospam = bodyUI->nospamLineEdit->text(); + const QString newNospam = bodyUI->nospamLineEdit->text(); bool ok; - uint32_t nospam = newNospam.toLongLong(&ok, 16); + const uint32_t nospam = newNospam.toLongLong(&ok, 16); if (ok) { core->setNospam(nospam); } @@ -102,7 +102,7 @@ void PrivacyForm::on_randomNosapamButton_clicked() void PrivacyForm::on_nospamLineEdit_textChanged() { QString str = bodyUI->nospamLineEdit->text(); - int curs = bodyUI->nospamLineEdit->cursorPosition(); + const int curs = bodyUI->nospamLineEdit->cursorPosition(); if (str.length() != 8) { str = QString("00000000").replace(0, str.length(), str); bodyUI->nospamLineEdit->setText(str); diff --git a/src/widget/form/settings/userinterfaceform.cpp b/src/widget/form/settings/userinterfaceform.cpp index 65f9b3b269..e1f3ac369b 100644 --- a/src/widget/form/settings/userinterfaceform.cpp +++ b/src/widget/form/settings/userinterfaceform.cpp @@ -58,7 +58,7 @@ UserInterfaceForm::UserInterfaceForm(SmileyPack& smileyPack_, Settings& settings const QFont chatBaseFont = settings.getChatMessageFont(); bodyUI->txtChatFontSize->setValue(QFontInfo(chatBaseFont).pixelSize()); bodyUI->txtChatFont->setCurrentFont(chatBaseFont); - int index = static_cast(settings.getStylePreference()); + const int index = static_cast(settings.getStylePreference()); bodyUI->textStyleComboBox->setCurrentIndex(index); bodyUI->useNameColors->setChecked(settings.getEnableGroupChatsColor()); @@ -93,7 +93,7 @@ UserInterfaceForm::UserInterfaceForm(SmileyPack& smileyPack_, Settings& settings smileLabels = {bodyUI->smile1, bodyUI->smile2, bodyUI->smile3, bodyUI->smile4, bodyUI->smile5}; - int currentPack = bodyUI->smileyPackBrowser->findData(settings.getSmileyPack()); + const int currentPack = bodyUI->smileyPackBrowser->findData(settings.getSmileyPack()); bodyUI->smileyPackBrowser->setCurrentIndex(currentPack); reloadSmileys(); bodyUI->smileyPackBrowser->setEnabled(bodyUI->useEmoticons->isChecked()); @@ -109,13 +109,13 @@ UserInterfaceForm::UserInterfaceForm(SmileyPack& smileyPack_, Settings& settings bodyUI->styleBrowser->setCurrentText(textStyle); - for (QString color : Style::getThemeColorNames()) + for (const QString& color : Style::getThemeColorNames()) bodyUI->themeColorCBox->addItem(color); bodyUI->themeColorCBox->setCurrentIndex(settings.getThemeColor()); bodyUI->emoticonSize->setValue(settings.getEmojiFontPointSize()); - QLocale ql; + const QLocale ql; QStringList timeFormats; timeFormats << ql.timeFormat(QLocale::ShortFormat) << ql.timeFormat(QLocale::LongFormat) << "hh:mm AP" @@ -124,7 +124,7 @@ UserInterfaceForm::UserInterfaceForm(SmileyPack& smileyPack_, Settings& settings timeFormats.removeDuplicates(); bodyUI->timestamp->addItems(timeFormats); - QRegularExpression re(QString("^[^\\n]{0,%0}$").arg(MAX_FORMAT_LENGTH)); + const QRegularExpression re(QString("^[^\\n]{0,%0}$").arg(MAX_FORMAT_LENGTH)); QRegularExpressionValidator* validator = new QRegularExpressionValidator(re, this); QString timeFormat = settings.getTimestampFormat(); @@ -183,21 +183,21 @@ void UserInterfaceForm::on_emoticonSize_editingFinished() void UserInterfaceForm::on_timestamp_editTextChanged(const QString& format) { - QString timeExample = QTime::currentTime().toString(format); + const QString timeExample = QTime::currentTime().toString(format); bodyUI->timeExample->setText(timeExample); settings.setTimestampFormat(format); - QString locale = settings.getTranslation(); + const QString locale = settings.getTranslation(); Translator::translate(locale); } void UserInterfaceForm::on_dateFormats_editTextChanged(const QString& format) { - QString dateExample = QDate::currentDate().toString(format); + const QString dateExample = QDate::currentDate().toString(format); bodyUI->dateExample->setText(dateExample); settings.setDateFormat(format); - QString locale = settings.getTranslation(); + const QString locale = settings.getTranslation(); Translator::translate(locale); } @@ -209,14 +209,14 @@ void UserInterfaceForm::on_useEmoticons_stateChanged() void UserInterfaceForm::on_textStyleComboBox_currentTextChanged() { - Settings::StyleType styleType = + const Settings::StyleType styleType = static_cast(bodyUI->textStyleComboBox->currentIndex()); settings.setStylePreference(styleType); } void UserInterfaceForm::on_smileyPackBrowser_currentIndexChanged(int index) { - QString filename = bodyUI->smileyPackBrowser->itemData(index).toString(); + const QString filename = bodyUI->smileyPackBrowser->itemData(index).toString(); settings.setSmileyPack(filename); reloadSmileys(); } @@ -226,7 +226,7 @@ void UserInterfaceForm::on_smileyPackBrowser_currentIndexChanged(int index) */ void UserInterfaceForm::reloadSmileys() { - QList emoticons = smileyPack.getEmoticons(); + const QList emoticons = smileyPack.getEmoticons(); // sometimes there are no emoticons available, don't crash in this case if (emoticons.isEmpty()) { @@ -241,7 +241,7 @@ void UserInterfaceForm::reloadSmileys() emoticonsIcons.clear(); const QSize size(18, 18); for (int i = 0; i < smileLabels.size(); ++i) { - std::shared_ptr icon = smileyPack.getAsIcon(smileys[i]); + const std::shared_ptr icon = smileyPack.getAsIcon(smileys[i]); emoticonsIcons.append(icon); smileLabels[i]->setPixmap(icon->pixmap(size)); smileLabels[i]->setToolTip(smileys[i]); @@ -251,10 +251,10 @@ void UserInterfaceForm::reloadSmileys() auto geometry = QGuiApplication::primaryScreen()->geometry(); // 8 is the count of row and column in emoji's in widget const int sideSize = 8; - int maxSide = qMin(geometry.height() / sideSize, geometry.width() / sideSize); - QSize maxSize(maxSide, maxSide); + const int maxSide = qMin(geometry.height() / sideSize, geometry.width() / sideSize); + const QSize maxSize(maxSide, maxSide); - QSize actualSize = emoticonsIcons.first()->actualSize(maxSize); + const QSize actualSize = emoticonsIcons.first()->actualSize(maxSize); bodyUI->emoticonSize->setMaximum(actualSize.width()); } @@ -304,7 +304,7 @@ void UserInterfaceForm::on_cbCompactLayout_stateChanged() void UserInterfaceForm::on_cbSeparateWindow_stateChanged() { - bool checked = bodyUI->cbSeparateWindow->isChecked(); + const bool checked = bodyUI->cbSeparateWindow->isChecked(); bodyUI->cbDontGroupWindows->setEnabled(checked); settings.setSeparateWindow(checked); } @@ -337,7 +337,7 @@ void UserInterfaceForm::on_themeColorCBox_currentIndexChanged(int index) void UserInterfaceForm::retranslateUi() { // Block signals during translation to prevent settings change - RecursiveSignalBlocker signalBlocker{this}; + const RecursiveSignalBlocker signalBlocker{this}; bodyUI->retranslateUi(this); diff --git a/src/widget/form/tabcompleter.cpp b/src/widget/form/tabcompleter.cpp index 97b3c48a91..1601e6932e 100644 --- a/src/widget/form/tabcompleter.cpp +++ b/src/widget/form/tabcompleter.cpp @@ -48,12 +48,14 @@ void TabCompleter::buildCompletionList() // split the string on the given RE (not chars, nums or braces/brackets) and take the last // section - QString tabAbbrev = msgEdit->toPlainText() - .left(msgEdit->textCursor().position()) - .section(QRegularExpression("[^\\w\\d\\$:@--_\\[\\]{}|`^.\\\\]"), -1, -1); + const QString tabAbbrev = + msgEdit->toPlainText() + .left(msgEdit->textCursor().position()) + .section(QRegularExpression("[^\\w\\d\\$:@--_\\[\\]{}|`^.\\\\]"), -1, -1); // that section is then used as the completion regex - QRegularExpression regex(QString("^[-_\\[\\]{}|`^.\\\\]*").append(QRegularExpression::escape(tabAbbrev)), - QRegularExpression::CaseInsensitiveOption); + const QRegularExpression regex(QString("^[-_\\[\\]{}|`^.\\\\]*") + .append(QRegularExpression::escape(tabAbbrev)), + QRegularExpression::CaseInsensitiveOption); const QString ownNick = group->getSelfName(); for (const auto& name : group->getPeerList()) { @@ -61,7 +63,7 @@ void TabCompleter::buildCompletionList() continue; // don't auto complete own name } if (regex.match(name).hasMatch()) { - SortableString lower = SortableString(name.toLower()); + const SortableString lower = SortableString(name.toLower()); completionMap[lower] = name; } } diff --git a/src/widget/friendlistwidget.cpp b/src/widget/friendlistwidget.cpp index 08fccf73f3..c2b6155e33 100644 --- a/src/widget/friendlistwidget.cpp +++ b/src/widget/friendlistwidget.cpp @@ -48,7 +48,7 @@ Time getTimeBucket(const QDateTime& date) return Time::Never; } - QDate today = QDate::currentDate(); + const QDate today = QDate::currentDate(); // clang-format off const QMap dates { { Time::Today, today.addDays(0) }, @@ -63,7 +63,7 @@ Time getTimeBucket(const QDateTime& date) }; // clang-format on - for (Time time : dates.keys()) { + for (const Time time : dates.keys()) { if (dates[time] <= date.date()) { return time; } @@ -79,7 +79,7 @@ QDateTime getActiveTimeFriend(const Friend* contact, Settings& settings) qint64 timeUntilTomorrow() { - QDateTime now = QDateTime::currentDateTime(); + const QDateTime now = QDateTime::currentDateTime(); QDateTime tomorrow = now.addDays(1); // Tomorrow. tomorrow.setTime(QTime()); // Midnight. return now.msecsTo(tomorrow); @@ -99,7 +99,7 @@ FriendListWidget::FriendListWidget(const Core& core_, Widget* parent, Settings& , groupList{groupList_} , profile{profile_} { - int countContacts = core.getFriendList().size(); + const int countContacts = core.getFriendList().size(); manager = new FriendListManager(countContacts, this); manager->setGroupsOnTop(groupsOnTop); connect(manager, &FriendListManager::itemsChanged, this, &FriendListWidget::itemsChanged); @@ -194,7 +194,7 @@ void FriendListWidget::sortByMode() for (int i = 0; i < circles.size(); ++i) { - QVector> itemsInCircle = + const QVector> itemsInCircle = getItemsFromCircle(circles.at(i)); for (int j = 0; j < itemsInCircle.size(); ++j) { itemsInCircle.at(j)->setNameSortedPos(posByName++); @@ -211,8 +211,8 @@ void FriendListWidget::sortByMode() } cleanMainLayout(); - QLocale ql(settings.getTranslation()); - QDate today = QDate::currentDate(); + const QLocale ql(settings.getTranslation()); + const QDate today = QDate::currentDate(); #define COMMENT "Category for sorting friends by activity" // clang-format off const QMap names { @@ -238,8 +238,8 @@ void FriendListWidget::sortByMode() } activityLayout = new QVBoxLayout(); - bool compact = settings.getCompactLayout(); - for (Time t : names.keys()) { + const bool compact = settings.getCompactLayout(); + for (const Time t : names.keys()) { CategoryWidget* category = new CategoryWidget(compact, settings, style, this); category->setName(names[t]); activityLayout->addWidget(category); @@ -251,7 +251,7 @@ void FriendListWidget::sortByMode() // Insert widgets to CategoryWidget for (int i = 0; i < itemsTmp.size(); ++i) { if (itemsTmp[i]->isFriend()) { - int timeIndex = static_cast(getTimeBucket(itemsTmp[i]->getLastActivity())); + const int timeIndex = static_cast(getTimeBucket(itemsTmp[i]->getLastActivity())); QWidget* widget = activityLayout->itemAt(timeIndex)->widget(); CategoryWidget* categoryWidget = qobject_cast(widget); FriendWidget* frnd = qobject_cast((itemsTmp[i].get())->getWidget()); @@ -300,7 +300,7 @@ void FriendListWidget::cleanMainLayout() QWidget* FriendListWidget::getNextWidgetForName(IFriendListItem* currentPos, bool forward) const { - int pos = currentPos->getNameSortedPos(); + const int pos = currentPos->getNameSortedPos(); int nextPos = forward ? pos + 1 : pos - 1; if (nextPos >= manager->getItems().size()) { nextPos = 0; @@ -318,10 +318,10 @@ QWidget* FriendListWidget::getNextWidgetForName(IFriendListItem* currentPos, boo QVector> FriendListWidget::getItemsFromCircle(CircleWidget* circle) const { - QVector> itemsTmp = manager->getItems(); + const QVector> itemsTmp = manager->getItems(); QVector> itemsInCircle; for (int i = 0; i < itemsTmp.size(); ++i) { - int circleId = itemsTmp.at(i)->getCircleId(); + const int circleId = itemsTmp.at(i)->getCircleId(); if (CircleWidget::getFromID(circleId) == circle) { itemsInCircle.push_back(itemsTmp.at(i)); } @@ -332,7 +332,7 @@ QVector> FriendListWidget::getItemsFromCircle(C CategoryWidget* FriendListWidget::getTimeCategoryWidget(const Friend* frd) const { const auto activityTime = getActiveTimeFriend(frd, settings); - int timeIndex = static_cast(getTimeBucket(activityTime)); + const int timeIndex = static_cast(getTimeBucket(activityTime)); QWidget* widget = activityLayout->itemAt(timeIndex)->widget(); return qobject_cast(widget); } @@ -366,7 +366,7 @@ void FriendListWidget::removeGroupWidget(GroupWidget* w) void FriendListWidget::removeFriendWidget(FriendWidget* w) { const Friend* contact = w->getFriend(); - int id = settings.getFriendCircleID(contact->getPublicKey()); + const int id = settings.getFriendCircleID(contact->getPublicKey()); CircleWidget* circleWidget = CircleWidget::getFromID(id); if (circleWidget != nullptr) { circleWidget->removeFriendWidget(w, contact->getStatus()); @@ -514,7 +514,7 @@ void FriendListWidget::dragEnterEvent(QDragEnterEvent* event) if (!event->mimeData()->hasFormat("toxPk")) { return; } - ToxPk toxPk(event->mimeData()->data("toxPk")); + const ToxPk toxPk(event->mimeData()->data("toxPk")); Friend* frnd = friendList.findFriend(toxPk); if (frnd) event->acceptProposedAction(); @@ -536,7 +536,7 @@ void FriendListWidget::dropEvent(QDropEvent* event) return; // Save CircleWidget before changing the Id - int circleId = settings.getFriendCircleID(f->getPublicKey()); + const int circleId = settings.getFriendCircleID(f->getPublicKey()); CircleWidget* circleWidget = CircleWidget::getFromID(circleId); moveWidget(widget, f->getStatus(), true); @@ -563,7 +563,7 @@ void FriendListWidget::moveWidget(FriendWidget* widget, Status::Status s, bool a { if (mode == SortingMode::Name) { const Friend* f = widget->getFriend(); - int circleId = settings.getFriendCircleID(f->getPublicKey()); + const int circleId = settings.getFriendCircleID(f->getPublicKey()); CircleWidget* circleWidget = CircleWidget::getFromID(circleId); if (circleWidget == nullptr || add) { @@ -591,7 +591,7 @@ void FriendListWidget::updateActivityTime(const QDateTime& time) if (mode != SortingMode::Activity) return; - int timeIndex = static_cast(getTimeBucket(time)); + const int timeIndex = static_cast(getTimeBucket(time)); QWidget* widget = activityLayout->itemAt(timeIndex)->widget(); CategoryWidget* categoryWidget = static_cast(widget); categoryWidget->updateStatus(); diff --git a/src/widget/genericchatitemlayout.cpp b/src/widget/genericchatitemlayout.cpp index 94bcece1d5..5144c42079 100644 --- a/src/widget/genericchatitemlayout.cpp +++ b/src/widget/genericchatitemlayout.cpp @@ -27,7 +27,7 @@ GenericChatItemLayout::~GenericChatItemLayout() void GenericChatItemLayout::addSortedWidget(GenericChatItemWidget* widget, int stretch, Qt::Alignment alignment) { - int closest = indexOfClosestSortedWidget(widget); + const int closest = indexOfClosestSortedWidget(widget); layout->insertWidget(closest, widget, stretch, alignment); } @@ -36,7 +36,7 @@ int GenericChatItemLayout::indexOfSortedWidget(GenericChatItemWidget* widget) co if (layout->isEmpty()) return -1; - int index = indexOfClosestSortedWidget(widget); + const int index = indexOfClosestSortedWidget(widget); if (index >= layout->count()) return -1; @@ -61,7 +61,7 @@ void GenericChatItemLayout::removeSortedWidget(GenericChatItemWidget* widget) if (layout->isEmpty()) return; - int index = indexOfClosestSortedWidget(widget); + const int index = indexOfClosestSortedWidget(widget); if (layout->itemAt(index) == nullptr) return; @@ -95,7 +95,7 @@ int GenericChatItemLayout::indexOfClosestSortedWidget(GenericChatItemWidget* wid // Binary search: Deferred test of equality. int min = 0, max = layout->count(); while (min < max) { - int mid = (max - min) / 2 + min; + const int mid = (max - min) / 2 + min; GenericChatItemWidget* atMid = qobject_cast(layout->itemAt(mid)->widget()); assert(atMid != nullptr); @@ -105,7 +105,7 @@ int GenericChatItemLayout::indexOfClosestSortedWidget(GenericChatItemWidget* wid QCollator collator; collator.setNumericMode(true); - int compareValue = collator.compare(atMid->getName(), widget->getName()); + const int compareValue = collator.compare(atMid->getName(), widget->getName()); if (compareValue < 0) lessThan = true; diff --git a/src/widget/loginscreen.cpp b/src/widget/loginscreen.cpp index db6578a459..952d130b20 100644 --- a/src/widget/loginscreen.cpp +++ b/src/widget/loginscreen.cpp @@ -76,7 +76,7 @@ void LoginScreen::reset(const QString& initialProfileName) ui->loginPassword->clear(); ui->loginUsernames->clear(); - QStringList allProfileNames = Profile::getAllProfileNames(settings); + const QStringList allProfileNames = Profile::getAllProfileNames(settings); if (allProfileNames.isEmpty()) { ui->stackedWidget->setCurrentIndex(0); @@ -137,8 +137,8 @@ void LoginScreen::onLoginPageClicked() void LoginScreen::onCreateNewProfile() { - QString name = ui->newUsername->text(); - QString pass = ui->newPass->text(); + const QString name = ui->newUsername->text(); + const QString pass = ui->newPass->text(); if (name.isEmpty()) { QMessageBox::critical(this, tr("Couldn't create a new profile"), @@ -192,8 +192,8 @@ void LoginScreen::onLoginUsernameSelected(const QString& name) void LoginScreen::onLogin() { - QString name = ui->loginUsernames->currentText(); - QString pass = ui->loginPassword->text(); + const QString name = ui->loginUsernames->currentText(); + const QString pass = ui->loginPassword->text(); // name can be empty when there are no profiles if (name.isEmpty()) { diff --git a/src/widget/maskablepixmapwidget.cpp b/src/widget/maskablepixmapwidget.cpp index 1554c2b7ff..1bab9b907e 100644 --- a/src/widget/maskablepixmapwidget.cpp +++ b/src/widget/maskablepixmapwidget.cpp @@ -60,7 +60,7 @@ void MaskablePixmapWidget::setSize(QSize size) delete renderTarget; renderTarget = new QPixmap(size); - QPixmap pmapMask = QPixmap(maskName); + const QPixmap pmapMask = QPixmap(maskName); if (!pmapMask.isNull()) { mask = pmapMask.scaled(size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); } @@ -84,8 +84,8 @@ void MaskablePixmapWidget::updatePixmap() { renderTarget->fill(Qt::transparent); - QPoint offset((width() - pixmap.size().width()) / 2, - (height() - pixmap.size().height()) / 2); // centering the pixmap + const QPoint offset((width() - pixmap.size().width()) / 2, + (height() - pixmap.size().height()) / 2); // centering the pixmap QPainter painter(renderTarget); painter.setCompositionMode(QPainter::CompositionMode_SourceOver); diff --git a/src/widget/notificationscrollarea.cpp b/src/widget/notificationscrollarea.cpp index c7d4c0530b..c4d5f0cf94 100644 --- a/src/widget/notificationscrollarea.cpp +++ b/src/widget/notificationscrollarea.cpp @@ -22,7 +22,7 @@ void NotificationScrollArea::trackWidget(Settings& settings, Style& style, Gener if (trackedWidgets.find(widget) != trackedWidgets.end()) return; - Visibility visibility = widgetVisible(widget); + const Visibility visibility = widgetVisible(widget); if (visibility != Visible) { if (visibility == Above) { if (referencesAbove++ == 0) { @@ -119,7 +119,7 @@ void NotificationScrollArea::findNextWidget() // Try finding a closer one. for (; i != trackedWidgets.end(); ++i) { if (i.value() == Below) { - int y = i.key()->mapTo(viewport(), QPoint()).y(); + const int y = i.key()->mapTo(viewport(), QPoint()).y(); if (y < value) { next = i.key(); value = y; @@ -149,7 +149,7 @@ void NotificationScrollArea::findPreviousWidget() // Try finding a closer one. for (; i != trackedWidgets.end(); ++i) { if (i.value() == Above) { - int y = i.key()->mapTo(viewport(), QPoint()).y(); + const int y = i.key()->mapTo(viewport(), QPoint()).y(); if (y > value) { next = i.key(); value = y; @@ -163,7 +163,7 @@ void NotificationScrollArea::findPreviousWidget() NotificationScrollArea::Visibility NotificationScrollArea::widgetVisible(QWidget* widget) const { - int y = widget->mapTo(viewport(), QPoint()).y(); + const int y = widget->mapTo(viewport(), QPoint()).y(); if (y < 0) return Above; diff --git a/src/widget/passwordedit.cpp b/src/widget/passwordedit.cpp index fd61ec7208..d32497cd42 100644 --- a/src/widget/passwordedit.cpp +++ b/src/widget/passwordedit.cpp @@ -87,7 +87,7 @@ PasswordEdit::EventHandler::~EventHandler() void PasswordEdit::EventHandler::updateActions() { - bool caps = Platform::capsLockEnabled(); + const bool caps = Platform::capsLockEnabled(); for (QAction* actionIt : actions) actionIt->setVisible(caps); diff --git a/src/widget/qrwidget.cpp b/src/widget/qrwidget.cpp index de65a55a55..5187555235 100644 --- a/src/widget/qrwidget.cpp +++ b/src/widget/qrwidget.cpp @@ -74,8 +74,8 @@ void QRWidget::paintImage() QRcode* qr = QRcode_encodeString(dataString.c_str(), 1, QR_ECLEVEL_M, QR_MODE_8, 1); if (qr != nullptr) { - QColor fg("black"); - QColor bg("white"); + const QColor fg("black"); + const QColor bg("white"); painter.setBrush(bg); painter.setPen(Qt::NoPen); painter.drawRect(0, 0, size.width(), size.height()); @@ -95,14 +95,14 @@ void QRWidget::paintImage() const unsigned char b = qr->data[xx]; if (b & 0x01) { const double rx1 = x * scale, ry1 = y * scale; - QRectF r(rx1, ry1, scale, scale); + const QRectF r(rx1, ry1, scale, scale); painter.drawRects(&r, 1); } } } QRcode_free(qr); } else { - QColor error("red"); + const QColor error("red"); painter.setBrush(error); painter.drawRect(0, 0, width(), height()); qDebug() << "QR FAIL: " << strerror(errno); diff --git a/src/widget/searchform.cpp b/src/widget/searchform.cpp index 4e8d6507d1..5296583d04 100644 --- a/src/widget/searchform.cpp +++ b/src/widget/searchform.cpp @@ -303,7 +303,7 @@ LineEdit::LineEdit(QWidget* parent) void LineEdit::keyPressEvent(QKeyEvent* event) { - int key = event->key(); + const int key = event->key(); if ((key == Qt::Key_Enter || key == Qt::Key_Return)) { if ((event->modifiers() & Qt::ShiftModifier)) { diff --git a/src/widget/splitterrestorer.cpp b/src/widget/splitterrestorer.cpp index 4068ae3103..64afd72562 100644 --- a/src/widget/splitterrestorer.cpp +++ b/src/widget/splitterrestorer.cpp @@ -42,8 +42,9 @@ SplitterRestorer::SplitterRestorer(QSplitter* splitter_) */ void SplitterRestorer::restore(const QByteArray& state, const QSize& windowSize) { - bool brokenSplitter = !splitter->restoreState(state) || splitter->orientation() != Qt::Horizontal - || splitter->handleWidth() > defaultWidth; + const bool brokenSplitter = !splitter->restoreState(state) + || splitter->orientation() != Qt::Horizontal + || splitter->handleWidth() > defaultWidth; if (splitter->count() == 2 && brokenSplitter) { splitter->setOrientation(Qt::Horizontal); diff --git a/src/widget/style.cpp b/src/widget/style.cpp index b78351e06d..cb70001c4d 100644 --- a/src/widget/style.cpp +++ b/src/widget/style.cpp @@ -212,7 +212,7 @@ QFont Style::getFont(Font font) const QString Style::resolve(const QString& filename, Settings& settings, const QFont& baseFont) { - QString themePath = getThemeFolder(settings); + const QString themePath = getThemeFolder(settings); QString fullPath = themePath + filename; QString qss; @@ -271,7 +271,7 @@ const QString Style::resolve(const QString& filename, Settings& settings, const QRegularExpressionMatchIterator i = re.globalMatch(qss); while (i.hasNext()) { - QRegularExpressionMatch match = i.next(); + const QRegularExpressionMatch match = i.next(); QString path = match.captured(0); const QString phrase = path; diff --git a/src/widget/tool/adjustingscrollarea.cpp b/src/widget/tool/adjustingscrollarea.cpp index 54381a11a5..b735f6337d 100644 --- a/src/widget/tool/adjustingscrollarea.cpp +++ b/src/widget/tool/adjustingscrollarea.cpp @@ -17,7 +17,7 @@ AdjustingScrollArea::AdjustingScrollArea(QWidget* parent) void AdjustingScrollArea::resizeEvent(QResizeEvent* ev) { - int scrollBarWidth = + const int scrollBarWidth = verticalScrollBar()->isVisible() ? verticalScrollBar()->sizeHint().width() : 0; if (layoutDirection() == Qt::RightToLeft) @@ -30,7 +30,7 @@ void AdjustingScrollArea::resizeEvent(QResizeEvent* ev) QSize AdjustingScrollArea::sizeHint() const { if (widget()) { - int scrollbarWidth = verticalScrollBar()->isVisible() ? verticalScrollBar()->width() : 0; + const int scrollbarWidth = verticalScrollBar()->isVisible() ? verticalScrollBar()->width() : 0; return widget()->sizeHint() + QSize(scrollbarWidth, 0); } diff --git a/src/widget/tool/callconfirmwidget.cpp b/src/widget/tool/callconfirmwidget.cpp index 970c454c82..1c6ae9bde4 100644 --- a/src/widget/tool/callconfirmwidget.cpp +++ b/src/widget/tool/callconfirmwidget.cpp @@ -62,11 +62,11 @@ CallConfirmWidget::CallConfirmWidget(Settings& settings, Style& style, const QWi // Note: At the moment this may not work properly. For languages written // from right to left, there is no translation for the phrase "Incoming call...". // In this situation, the phrase "Incoming call..." looks as "...oming call..." - Qt::TextElideMode elideMode = + const Qt::TextElideMode elideMode = (QGuiApplication::layoutDirection() == Qt::LeftToRight) ? Qt::ElideRight : Qt::ElideLeft; - int marginSize = 12; - QFontMetrics fontMetrics(callLabel->font()); - QString elidedText = + const int marginSize = 12; + const QFontMetrics fontMetrics(callLabel->font()); + const QString elidedText = fontMetrics.elidedText(callLabel->text(), elideMode, rectW - marginSize * 2 - 4); callLabel->setText(elidedText); diff --git a/src/widget/tool/chattextedit.cpp b/src/widget/tool/chattextedit.cpp index df28e5ba22..e3aa54fca6 100644 --- a/src/widget/tool/chattextedit.cpp +++ b/src/widget/tool/chattextedit.cpp @@ -29,7 +29,7 @@ ChatTextEdit::~ChatTextEdit() void ChatTextEdit::keyPressEvent(QKeyEvent* event) { - int key = event->key(); + const int key = event->key(); if ((key == Qt::Key_Enter || key == Qt::Key_Return) && !(event->modifiers() & Qt::ShiftModifier)) { emit enterPressed(); return; diff --git a/src/widget/tool/croppinglabel.cpp b/src/widget/tool/croppinglabel.cpp index 625081d800..6daa1bf85e 100644 --- a/src/widget/tool/croppinglabel.cpp +++ b/src/widget/tool/croppinglabel.cpp @@ -117,7 +117,7 @@ void CroppingLabel::paintEvent(QPaintEvent* paintEvent) void CroppingLabel::setElidedText() { - QString elidedText = fontMetrics().elidedText(origText, elideMode, width()); + const QString elidedText = fontMetrics().elidedText(origText, elideMode, width()); if (elidedText != origText) setToolTip(Qt::convertFromPlainText(origText, Qt::WhiteSpaceNormal)); else @@ -164,7 +164,7 @@ void CroppingLabel::minimizeMaximumWidth() void CroppingLabel::editingFinished() { hideTextEdit(); - QString newText = + const QString newText = textEdit->text().trimmed().remove(QRegularExpression("[\\t\\n\\v\\f\\r\\x0000]")); if (origText != newText) diff --git a/src/widget/tool/flyoutoverlaywidget.cpp b/src/widget/tool/flyoutoverlaywidget.cpp index 9658e193a5..d4d32a5cf1 100644 --- a/src/widget/tool/flyoutoverlaywidget.cpp +++ b/src/widget/tool/flyoutoverlaywidget.cpp @@ -48,7 +48,7 @@ void FlyoutOverlayWidget::setFlyoutPercent(qreal progress) { percent = progress; - QSize self = size(); + const QSize self = size(); setMask(QRegion(0, 0, self.width() * progress + 1, self.height())); move(startPos.x() + self.width() - self.width() * percent, startPos.y()); setVisible(progress != 0); @@ -90,7 +90,7 @@ void FlyoutOverlayWidget::animateHide() void FlyoutOverlayWidget::finishedAnimation() { - bool hide = (animation->direction() == QAbstractAnimation::Backward); + const bool hide = (animation->direction() == QAbstractAnimation::Backward); // Delay it by a few frames to let the system catch up on rendering if (hide) diff --git a/src/widget/tool/messageboxmanager.cpp b/src/widget/tool/messageboxmanager.cpp index 5bee2fbcb2..0d48aeb12f 100644 --- a/src/widget/tool/messageboxmanager.cpp +++ b/src/widget/tool/messageboxmanager.cpp @@ -126,12 +126,12 @@ void MessageBoxManager::confirmExecutableOpen(const QFileInfo& file) "ws", "wsc", "wsf", "wsh"}; if (dangerousExtensions.contains(file.suffix())) { - bool answer = 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); + const bool answer = 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); if (!answer) { return; } @@ -168,8 +168,8 @@ void MessageBoxManager::_showError(const QString& title, const QString& msg) bool MessageBoxManager::_askQuestion(const QString& title, const QString& msg, bool defaultAns, bool warning, bool yesno) { - QString positiveButton = yesno ? QApplication::tr("Yes") : QApplication::tr("Ok"); - QString negativeButton = yesno ? QApplication::tr("No") : QApplication::tr("Cancel"); + const QString positiveButton = yesno ? QApplication::tr("Yes") : QApplication::tr("Ok"); + const QString negativeButton = yesno ? QApplication::tr("No") : QApplication::tr("Cancel"); return _askQuestion(title, msg, positiveButton, negativeButton, defaultAns, warning); } @@ -177,7 +177,7 @@ bool MessageBoxManager::_askQuestion(const QString& title, const QString& msg, b bool MessageBoxManager::_askQuestion(const QString& title, const QString& msg, const QString& button1, const QString& button2, bool defaultAns, bool warning) { - QMessageBox::Icon icon = warning ? QMessageBox::Warning : QMessageBox::Question; + const QMessageBox::Icon icon = warning ? QMessageBox::Warning : QMessageBox::Question; QMessageBox box(icon, title, msg, QMessageBox::NoButton, this); QPushButton* pushButton1 = box.addButton(button1, QMessageBox::AcceptRole); QPushButton* pushButton2 = box.addButton(button2, QMessageBox::RejectRole); diff --git a/src/widget/tool/movablewidget.cpp b/src/widget/tool/movablewidget.cpp index c257b3b59c..78d6b74781 100644 --- a/src/widget/tool/movablewidget.cpp +++ b/src/widget/tool/movablewidget.cpp @@ -38,11 +38,12 @@ void MovableWidget::setBoundary(QRect newBoundary) return; } - qreal changeX = newBoundary.width() / static_cast(boundaryRect.width()); - qreal changeY = newBoundary.height() / static_cast(boundaryRect.height()); + const qreal changeX = newBoundary.width() / static_cast(boundaryRect.width()); + const qreal changeY = newBoundary.height() / static_cast(boundaryRect.height()); - qreal percentageX = (x() - boundaryRect.x()) / static_cast(boundaryRect.width() - width()); - qreal percentageY = + const qreal percentageX = + (x() - boundaryRect.x()) / static_cast(boundaryRect.width() - width()); + const qreal percentageY = (y() - boundaryRect.y()) / static_cast(boundaryRect.height() - height()); actualSize.setWidth(actualSize.width() * changeX); @@ -60,7 +61,7 @@ void MovableWidget::setBoundary(QRect newBoundary) percentageY * (newBoundary.height() - height())); actualPos += QPointF(newBoundary.topLeft()); - QPoint moveTo = QPoint(round(actualPos.x()), round(actualPos.y())); + const QPoint moveTo = QPoint(round(actualPos.x()), round(actualPos.y())); move(moveTo); boundaryRect = newBoundary; @@ -143,7 +144,7 @@ void MovableWidget::mouseMoveEvent(QMouseEvent* event) if (event->buttons() & Qt::LeftButton) { QPoint lastPosition = pos(); - QPoint displacement = lastPoint - event->globalPosition().toPoint(); + const QPoint displacement = lastPoint - event->globalPosition().toPoint(); QSize lastSize = size(); @@ -179,7 +180,7 @@ void MovableWidget::mouseMoveEvent(QMouseEvent* event) if (mode & (ResizeLeft | ResizeRight)) { if (mode & (ResizeUp | ResizeDown)) { - int height = lastSize.width() / getRatio(); + const int height = lastSize.width() / getRatio(); if (!(mode & ResizeDown)) lastPosition.setY(lastPosition.y() - (height - lastSize.height())); diff --git a/src/widget/tool/profileimporter.cpp b/src/widget/tool/profileimporter.cpp index ca14a664e2..2362e94e40 100644 --- a/src/widget/tool/profileimporter.cpp +++ b/src/widget/tool/profileimporter.cpp @@ -33,14 +33,14 @@ ProfileImporter::ProfileImporter(Settings& settings_, QWidget* parent) */ bool ProfileImporter::importProfile() { - QString title = tr("Import profile", "import dialog title"); - QString filter = tr("Tox save file (*.tox)", "import dialog filter"); - QString dir = QDir::homePath(); + const QString title = tr("Import profile", "import dialog title"); + const QString filter = tr("Tox save file (*.tox)", "import dialog filter"); + const QString dir = QDir::homePath(); // TODO: Change all QFileDialog instances across project to use // this instead of Q_NULLPTR. Possibly requires >Qt 5.9 due to: // https://bugreports.qt.io/browse/QTBUG-59184 - QString path = QFileDialog::getOpenFileName(Q_NULLPTR, title, dir, filter); + const QString path = QFileDialog::getOpenFileName(Q_NULLPTR, title, dir, filter); return importProfile(path); } @@ -53,7 +53,7 @@ bool ProfileImporter::importProfile() */ bool ProfileImporter::askQuestion(QString title, QString message) { - QMessageBox::Icon icon = QMessageBox::Warning; + const QMessageBox::Icon icon = QMessageBox::Warning; QMessageBox box(icon, title, message, QMessageBox::NoButton, this); QPushButton* pushButton1 = box.addButton(QApplication::tr("Yes"), QMessageBox::AcceptRole); QPushButton* pushButton2 = box.addButton(QApplication::tr("No"), QMessageBox::RejectRole); @@ -74,14 +74,14 @@ bool ProfileImporter::importProfile(const QString& path) if (path.isEmpty()) return false; - QFileInfo info(path); + const QFileInfo info(path); if (!info.exists()) { QMessageBox::warning(this, tr("File doesn't exist"), tr("Profile doesn't exist"), QMessageBox::Ok); return false; } - QString profile = info.completeBaseName(); + const QString profile = info.completeBaseName(); if (info.suffix() != "tox") { QMessageBox::warning(this, tr("Ignoring non-Tox file", "popup title"), @@ -92,16 +92,16 @@ bool ProfileImporter::importProfile(const QString& path) return false; // ingore importing non-tox file } - QString settingsPath = settings.getPaths().getSettingsDirPath(); - QString profilePath = QDir(settingsPath).filePath(profile + Core::TOX_EXT); + const QString settingsPath = settings.getPaths().getSettingsDirPath(); + const QString profilePath = QDir(settingsPath).filePath(profile + Core::TOX_EXT); if (QFileInfo(profilePath).exists()) { - QString title = tr("Profile already exists", "import confirm title"); - QString message = tr("A profile named \"%1\" already exists. " - "Do you want to erase it?", - "import confirm text") - .arg(profile); - bool erase = askQuestion(title, message); + const QString title = tr("Profile already exists", "import confirm title"); + const QString message = tr("A profile named \"%1\" already exists. " + "Do you want to erase it?", + "import confirm text") + .arg(profile); + const bool erase = askQuestion(title, message); if (!erase) return false; // import canelled diff --git a/src/widget/tool/removechatdialog.cpp b/src/widget/tool/removechatdialog.cpp index f4a8698213..013080116d 100644 --- a/src/widget/tool/removechatdialog.cpp +++ b/src/widget/tool/removechatdialog.cpp @@ -15,9 +15,9 @@ RemoveChatDialog::RemoveChatDialog(QWidget* parent, const Chat& contact) setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); setAttribute(Qt::WA_QuitOnClose, false); ui.setupUi(this); - QString name = contact.getDisplayedName().toHtmlEscaped(); - QString text = tr("Are you sure you want to remove %1 from your contacts list?") - .arg(QString("%1").arg(name)); + const QString name = contact.getDisplayedName().toHtmlEscaped(); + const QString text = tr("Are you sure you want to remove %1 from your contacts list?") + .arg(QString("%1").arg(name)); ui.label->setText(text); auto removeButton = ui.buttonBox->button(QDialogButtonBox::Ok); diff --git a/src/widget/tool/screengrabberchooserrectitem.cpp b/src/widget/tool/screengrabberchooserrectitem.cpp index cf82433588..31944590c6 100644 --- a/src/widget/tool/screengrabberchooserrectitem.cpp +++ b/src/widget/tool/screengrabberchooserrectitem.cpp @@ -112,11 +112,11 @@ void ScreenGrabberChooserRectItem::mousePress(QGraphicsSceneMouseEvent* event) void ScreenGrabberChooserRectItem::mouseMove(QGraphicsSceneMouseEvent* event) { if (state == Moving) { - QPointF delta = event->scenePos() - event->lastScenePos(); + const QPointF delta = event->scenePos() - event->lastScenePos(); moveBy(delta.x(), delta.y()); } else if (state == Resizing) { prepareGeometryChange(); - QPointF size = event->scenePos() - scenePos(); + const QPointF size = event->scenePos() - scenePos(); mainRect->setRect(0, 0, size.x(), size.y()); rectWidth = size.x(); rectHeight = size.y(); @@ -134,12 +134,12 @@ void ScreenGrabberChooserRectItem::mouseRelease(QGraphicsSceneMouseEvent* event) if (event->button() == Qt::LeftButton) { setCursor(QCursor(Qt::OpenHandCursor)); - QPointF delta = (event->scenePos() - startPos); + const QPointF delta = (event->scenePos() - startPos); if (qAbs(delta.x()) < MinRectSize || qAbs(delta.y()) < MinRectSize) { rectWidth = rectHeight = 0; mainRect->setRect(QRect()); } else { - QRect normalized = chosenRect(); + const QRect normalized = chosenRect(); rectWidth = normalized.width(); rectHeight = normalized.height(); @@ -181,8 +181,8 @@ void ScreenGrabberChooserRectItem::mouseMoveHandle(int x, int y, QGraphicsSceneM delta.ry() *= qAbs(y); // We increase if the multiplier and the delta have the same sign - bool increaseX = ((x < 0) == (delta.x() < 0)); - bool increaseY = ((y < 0) == (delta.y() < 0)); + const bool increaseX = ((x < 0) == (delta.x() < 0)); + const bool increaseY = ((y < 0) == (delta.y() < 0)); if ((delta.x() < 0 && increaseX) || (delta.x() >= 0 && !increaseX)) { moveBy(delta.x(), 0); @@ -296,7 +296,7 @@ void ScreenGrabberChooserRectItem::forwardMainRectEvent(QEvent* event) void ScreenGrabberChooserRectItem::forwardHandleEvent(QGraphicsItem* watched, QEvent* event) { QGraphicsSceneMouseEvent* mouseEvent = static_cast(event); - QPoint multiplier = getHandleMultiplier(watched); + const QPoint multiplier = getHandleMultiplier(watched); if (multiplier.isNull()) return; diff --git a/src/widget/tool/screengrabberoverlayitem.cpp b/src/widget/tool/screengrabberoverlayitem.cpp index 0b663a7f43..dcb754730d 100644 --- a/src/widget/tool/screengrabberoverlayitem.cpp +++ b/src/widget/tool/screengrabberoverlayitem.cpp @@ -16,7 +16,7 @@ ScreenGrabberOverlayItem::ScreenGrabberOverlayItem(ScreenshotGrabber* grabber) : screnshootGrabber(grabber) { - QBrush overlayBrush(QColor(0x00, 0x00, 0x00, 0x70)); // Translucent black + const QBrush overlayBrush(QColor(0x00, 0x00, 0x00, 0x70)); // Translucent black setCursor(QCursor(Qt::CrossCursor)); setBrush(overlayBrush); @@ -27,7 +27,7 @@ ScreenGrabberOverlayItem::~ScreenGrabberOverlayItem() {} void ScreenGrabberOverlayItem::setChosenRect(QRect rect) { - QRect oldRect = chosenRect; + const QRect oldRect = chosenRect; chosenRect = rect; update(oldRect.united(rect)); } @@ -46,11 +46,11 @@ void ScreenGrabberOverlayItem::paint(QPainter* painter, const QStyleOptionGraphi painter->setBrush(brush()); painter->setPen(pen()); - QRectF self = rect(); - qreal leftX = chosenRect.x(); - qreal rightX = chosenRect.x() + chosenRect.width(); - qreal topY = chosenRect.y(); - qreal bottomY = chosenRect.y() + chosenRect.height(); + const QRectF self = rect(); + const qreal leftX = chosenRect.x(); + const qreal rightX = chosenRect.x() + chosenRect.width(); + const qreal topY = chosenRect.y(); + const qreal bottomY = chosenRect.y() + chosenRect.height(); painter->drawRect(0, 0, leftX, self.height()); // Left of chosen painter->drawRect(rightX, 0, self.width() - rightX, self.height()); // Right of chosen diff --git a/src/widget/tool/screenshotgrabber.cpp b/src/widget/tool/screenshotgrabber.cpp index cbc3f4ed11..286852077e 100644 --- a/src/widget/tool/screenshotgrabber.cpp +++ b/src/widget/tool/screenshotgrabber.cpp @@ -68,8 +68,8 @@ void ScreenshotGrabber::showGrabber() window->setFocus(); window->grabKeyboard(); - QRect fullGrabbedRect = screenGrab.rect(); - QRect rec = QApplication::primaryScreen()->virtualGeometry(); + const QRect fullGrabbedRect = screenGrab.rect(); + const QRect rec = QApplication::primaryScreen()->virtualGeometry(); window->setGeometry(rec); scene->setSceneRect(fullGrabbedRect); @@ -115,7 +115,7 @@ void ScreenshotGrabber::acceptRegion() emit regionChosen(rect); qDebug() << "Screenshot accepted, chosen region" << rect; - QPixmap pixmap = screenGrab.copy(rect); + const QPixmap pixmap = screenGrab.copy(rect); restoreHiddenWindows(); emit screenshotTaken(pixmap); @@ -187,11 +187,11 @@ void ScreenshotGrabber::chooseHelperTooltipText(QRect rect) */ void ScreenshotGrabber::adjustTooltipPosition() { - QRect recGL = QGuiApplication::primaryScreen()->virtualGeometry(); + const QRect recGL = QGuiApplication::primaryScreen()->virtualGeometry(); const auto rec = QGuiApplication::screenAt(QCursor::pos())->geometry(); const QRectF ttRect = helperToolbox->childrenBoundingRect(); - int x = qAbs(recGL.x()) + rec.x() + ((rec.width() - ttRect.width()) / 2); - int y = qAbs(recGL.y()) + rec.y(); + const int x = qAbs(recGL.x()) + rec.x() + ((rec.width() - ttRect.width()) / 2); + const int y = qAbs(recGL.y()) + rec.y(); helperToolbox->setX(x); helperToolbox->setY(y); @@ -206,7 +206,7 @@ void ScreenshotGrabber::reject() QPixmap ScreenshotGrabber::grabScreen() { QScreen* screen = QGuiApplication::primaryScreen(); - QRect rec = screen->virtualGeometry(); + const QRect rec = screen->virtualGeometry(); // Multiply by devicePixelRatio to get actual desktop size return screen->grabWindow(0, rec.x() * pixRatio, rec.y() * pixRatio, rec.width() * pixRatio, @@ -238,7 +238,7 @@ void ScreenshotGrabber::restoreHiddenWindows() void ScreenshotGrabber::beginRectChooser(QGraphicsSceneMouseEvent* event) { - QPointF pos = event->scenePos(); + const QPointF pos = event->scenePos(); chooserRect->setX(pos.x()); chooserRect->setY(pos.y()); chooserRect->beginResize(event->scenePos()); diff --git a/src/widget/translator.cpp b/src/widget/translator.cpp index 9ea235dc68..c6e8811a11 100644 --- a/src/widget/translator.cpp +++ b/src/widget/translator.cpp @@ -24,7 +24,7 @@ QMutex Translator::lock; */ void Translator::translate(const QString& localeName) { - QMutexLocker locker{&lock}; + const QMutexLocker locker{&lock}; if (!core_translator) core_translator = new QTranslator(); @@ -37,14 +37,15 @@ void Translator::translate(const QString& localeName) QApplication::removeTranslator(app_translator); // Load translations - QString locale = localeName.isEmpty() ? QLocale::system().name().section('_', 0, 0) : localeName; + const QString locale = + localeName.isEmpty() ? QLocale::system().name().section('_', 0, 0) : localeName; if (core_translator->load(locale, ":translations/")) { qDebug() << "Loaded translation" << locale; // System menu translation - QString s_locale = "qt_" + locale; - QString location = QLibraryInfo::path(QLibraryInfo::TranslationsPath); + const QString s_locale = "qt_" + locale; + const QString location = QLibraryInfo::path(QLibraryInfo::TranslationsPath); if (app_translator->load(s_locale, location)) { QApplication::installTranslator(app_translator); qDebug() << "System translation loaded" << locale; @@ -78,7 +79,7 @@ void Translator::translate(const QString& localeName) */ void Translator::registerHandler(const std::function& f, void* owner) { - QMutexLocker locker{&lock}; + const QMutexLocker locker{&lock}; callbacks.push_back({owner, f}); } @@ -88,7 +89,7 @@ void Translator::registerHandler(const std::function& f, void* owner) */ void Translator::unregister(void* owner) { - QMutexLocker locker{&lock}; + const QMutexLocker locker{&lock}; callbacks.erase(std::remove_if(begin(callbacks), end(callbacks), [=](const Callback& c) { return c.first == owner; }), end(callbacks)); diff --git a/src/widget/widget.cpp b/src/widget/widget.cpp index baf11bee97..6440edeedd 100644 --- a/src/widget/widget.cpp +++ b/src/widget/widget.cpp @@ -80,7 +80,7 @@ namespace { bool tryRemoveFile(const QString& filepath) { QFile tmp(filepath); - bool writable = tmp.open(QIODevice::WriteOnly); + const bool writable = tmp.open(QIODevice::WriteOnly); tmp.remove(); return writable; } @@ -104,8 +104,8 @@ void Widget::acceptFileTransfer(const ToxFile& file, const QString& path) QString filepath; int number = 0; - QString suffix = QFileInfo(file.fileName).completeSuffix(); - QString base = QFileInfo(file.fileName).baseName(); + const QString suffix = QFileInfo(file.fileName).completeSuffix(); + const QString base = QFileInfo(file.fileName).baseName(); do { filepath = QString("%1/%2%3.%4") @@ -154,7 +154,7 @@ Widget::Widget(Profile& profile_, IAudioControl& audio_, CameraSource& cameraSou , nexus{nexus_} { installEventFilter(this); - QString locale = settings.getTranslation(); + const QString locale = settings.getTranslation(); Translator::translate(locale); } @@ -162,7 +162,7 @@ void Widget::init() { ui->setupUi(this); - QIcon themeIcon = QIcon::fromTheme("qtox"); + const QIcon themeIcon = QIcon::fromTheme("qtox"); if (!themeIcon.isNull()) { setWindowIcon(themeIcon); } @@ -520,7 +520,7 @@ void Widget::init() bool Widget::eventFilter(QObject* obj, QEvent* event) { QWindowStateChangeEvent* ce = nullptr; - Qt::WindowStates state = windowState(); + const Qt::WindowStates state = windowState(); switch (event->type()) { case QEvent::Close: @@ -585,8 +585,9 @@ void Widget::updateIcons() if (!hasThemeIconBug && QIcon::hasThemeIcon("qtox-" + assetSuffix)) { ico = QIcon::fromTheme("qtox-" + assetSuffix); } else { - QString color = settings.getLightTrayIcon() ? QStringLiteral("light") : QStringLiteral("dark"); - QString path = ":/img/taskbar/" + color + "/taskbar_" + assetSuffix + ".svg"; + const QString color = + settings.getLightTrayIcon() ? QStringLiteral("light") : QStringLiteral("dark"); + const QString path = ":/img/taskbar/" + color + "/taskbar_" + assetSuffix + ".svg"; QSvgRenderer renderer(path); // Prepare a QImage with desired characteritisc @@ -609,7 +610,7 @@ Widget::~Widget() ipc.unregisterEventHandler(activateHandlerKey); #endif - QWidgetList windowList = QApplication::topLevelWidgets(); + QWidgetList const windowList = QApplication::topLevelWidgets(); for (QWidget* window : windowList) { if (window != this) { @@ -802,7 +803,7 @@ void Widget::onSeparateWindowClicked(bool separate) void Widget::onSeparateWindowChanged(bool separate, bool clicked) { if (!separate) { - QWindowList windowList = QGuiApplication::topLevelWindows(); + const QWindowList windowList = QGuiApplication::topLevelWindows(); for (QWindow* window : windowList) { if (window->objectName() == "detachedWindow") { @@ -823,7 +824,7 @@ void Widget::onSeparateWindowChanged(bool separate, bool clicked) onShowSettings(); } else { - int width = ui->friendList->size().width(); + const int width = ui->friendList->size().width(); QSize size; QPoint pos; @@ -1112,7 +1113,7 @@ void Widget::dispatchFile(ToxFile file) } auto maxAutoAcceptSize = settings.getMaxAutoAcceptSize(); - bool autoAcceptSizeCheckPassed = + const bool autoAcceptSizeCheckPassed = maxAutoAcceptSize == 0 || maxAutoAcceptSize >= file.progress.getFileSize(); if (!autoAcceptDir.isEmpty() && autoAcceptSizeCheckPassed) { @@ -1159,7 +1160,7 @@ void Widget::addFriend(uint32_t friendId, const ToxPk& friendPk) Friend* newfriend = friendList->addFriend(friendId, friendPk, settings); auto rawChatroom = new FriendChatroom(newfriend, contentDialogManager.get(), *core, settings, *groupList); - std::shared_ptr chatroom(rawChatroom); + const std::shared_ptr chatroom(rawChatroom); const auto compact = settings.getCompactLayout(); auto widget = new FriendWidget(chatroom, compact, settings, style, *messageBoxManager, profile); connectFriendWidget(*widget); @@ -1227,7 +1228,7 @@ void Widget::addFriend(uint32_t friendId, const ToxPk& friendPk) connect(&profile, &Profile::friendAvatarRemoved, widget, &FriendWidget::onAvatarRemoved); // Try to get the avatar from the cache - QPixmap avatar = profile.loadAvatar(friendPk); + const QPixmap avatar = profile.loadAvatar(friendPk); if (!avatar.isNull()) { friendForm->onAvatarChanged(friendPk, avatar); widget->onAvatarSet(friendPk, avatar); @@ -1459,9 +1460,9 @@ void Widget::addFriendDialog(const Friend* frnd, ContentDialog* dialog) { const ToxPk& friendPk = frnd->getPublicKey(); ContentDialog* contentDialog = contentDialogManager->getFriendDialog(friendPk); - bool isSeparate = settings.getSeparateWindow(); + const bool isSeparate = settings.getSeparateWindow(); FriendWidget* widget = friendWidgets[friendPk]; - bool isCurrent = activeChatroomWidget == widget; + const bool isCurrent = activeChatroomWidget == widget; if (!contentDialog && !isSeparate && isCurrent) { onAddClicked(); } @@ -1500,7 +1501,7 @@ void Widget::addFriendDialog(const Friend* frnd, ContentDialog* dialog) connect(&profile, &Profile::friendAvatarSet, friendWidget, &FriendWidget::onAvatarSet); connect(&profile, &Profile::friendAvatarRemoved, friendWidget, &FriendWidget::onAvatarRemoved); - QPixmap avatar = profile.loadAvatar(frnd->getPublicKey()); + const QPixmap avatar = profile.loadAvatar(frnd->getPublicKey()); if (!avatar.isNull()) { friendWidget->onAvatarSet(frnd->getPublicKey(), avatar); } @@ -1510,9 +1511,9 @@ void Widget::addGroupDialog(const Group* group, ContentDialog* dialog) { const GroupId& groupId = group->getPersistentId(); ContentDialog* groupDialog = contentDialogManager->getGroupDialog(groupId); - bool separated = settings.getSeparateWindow(); + const bool separated = settings.getSeparateWindow(); GroupWidget* widget = groupWidgets[groupId]; - bool isCurrentWindow = activeChatroomWidget == widget; + const bool isCurrentWindow = activeChatroomWidget == widget; if (!groupDialog && !separated && isCurrentWindow) { onAddClicked(); } @@ -1672,7 +1673,7 @@ QString Widget::fromDialogType(DialogType type) bool Widget::newMessageAlert(QWidget* currentWindow, bool isActive, bool sound, bool notify) { - bool inactiveWindow = isMinimized() || !currentWindow->isActiveWindow(); + const bool inactiveWindow = isMinimized() || !currentWindow->isActiveWindow(); if (!inactiveWindow && isActive) { return false; @@ -1694,9 +1695,9 @@ bool Widget::newMessageAlert(QWidget* currentWindow, bool isActive, bool sound, #endif eventFlag = true; } - bool isBusy = core->getStatus() == Status::Status::Busy; - bool busySound = settings.getBusySound(); - bool notifySound = settings.getNotifySound(); + const bool isBusy = core->getStatus() == Status::Status::Busy; + const bool busySound = settings.getBusySound(); + const bool notifySound = settings.getNotifySound(); if (notifySound && sound && (!isBusy || busySound)) { playNotificationSound(IAudioSink::Sound::NewMessage); @@ -1997,7 +1998,7 @@ void Widget::onGroupMessageReceived(int groupnumber, int peernumber, const QStri const GroupId& groupId = groupList->id2Key(groupnumber); assert(groupList->findGroup(groupId)); - ToxPk author = core->getGroupPeerPk(groupnumber, peernumber); + const ToxPk author = core->getGroupPeerPk(groupnumber, peernumber); groupMessageDispatchers[groupId]->onMessageReceived(author, isAction, message); } @@ -2136,7 +2137,7 @@ Group* Widget::createGroup(uint32_t groupnumber, const GroupId& groupId) }); } auto rawChatroom = new GroupChatroom(newgroup, contentDialogManager.get(), *core, *friendList); - std::shared_ptr chatroom(rawChatroom); + const std::shared_ptr chatroom(rawChatroom); const auto compact = settings.getCompactLayout(); auto widget = new GroupWidget(chatroom, compact, settings, style); @@ -2263,10 +2264,10 @@ bool Widget::event(QEvent* e) void Widget::onUserAwayCheck() { #ifdef QTOX_PLATFORM_EXT - uint32_t autoAwayTime = settings.getAutoAwayTime() * 60 * 1000; - bool online = static_cast(ui->statusButton->property("status").toInt()) - == Status::Status::Online; - bool away = autoAwayTime && Platform::getIdleTime() >= autoAwayTime; + uint32_t const autoAwayTime = settings.getAutoAwayTime() * 60 * 1000; + const bool online = static_cast(ui->statusButton->property("status").toInt()) + == Status::Status::Online; + const bool away = autoAwayTime && Platform::getIdleTime() >= autoAwayTime; if (online && away) { qDebug() << "auto away activated at" << QTime::currentTime().toString(); @@ -2453,7 +2454,7 @@ bool Widget::filterOnline(FilterCriteria index) void Widget::clearAllReceipts() { - QList frnds = friendList->getAllFriends(); + const QList frnds = friendList->getAllFriends(); for (Friend* f : frnds) { friendMessageDispatchers[f->getPublicKey()]->clearOutgoingMessages(); } @@ -2462,13 +2463,13 @@ void Widget::clearAllReceipts() void Widget::reloadTheme() { setStyleSheet(""); - QWidgetList wgts = findChildren(); + const QWidgetList wgts = findChildren(); for (auto x : wgts) { x->setStyleSheet(""); } setStyleSheet(style.getStylesheet("window/general.css", settings)); - QString statusPanelStyle = style.getStylesheet("window/statusPanel.css", settings); + const QString statusPanelStyle = style.getStylesheet("window/statusPanel.css", settings); ui->tooliconsZone->setStyleSheet(style.getStylesheet("tooliconsZone/tooliconsZone.css", settings)); ui->statusPanel->setStyleSheet(statusPanelStyle); ui->statusHead->setStyleSheet(statusPanelStyle); @@ -2520,8 +2521,8 @@ inline QIcon Widget::prepareIcon(QString path, int w, int h) void Widget::searchChats() { - QString searchString = ui->searchContactText->text(); - FilterCriteria filter = getFilterCriteria(); + const QString searchString = ui->searchContactText->text(); + const FilterCriteria filter = getFilterCriteria(); chatListWidget->searchChatrooms(searchString, filterOnline(filter), filterOffline(filter), filterGroups(filter)); @@ -2547,7 +2548,7 @@ void Widget::changeDisplayMode() void Widget::updateFilterText() { - QString action = filterDisplayGroup->checkedAction()->text(); + const QString action = filterDisplayGroup->checkedAction()->text(); QString text = filterGroup->checkedAction()->text(); text = action + QStringLiteral(" | ") + text; ui->searchContactFilterBox->setText(text); @@ -2572,15 +2573,15 @@ Widget::FilterCriteria Widget::getFilterCriteria() const void Widget::searchCircle(CircleWidget& circleWidget) { if (chatListWidget->getMode() == FriendListWidget::SortingMode::Name) { - FilterCriteria filter = getFilterCriteria(); - QString text = ui->searchContactText->text(); + const FilterCriteria filter = getFilterCriteria(); + const QString text = ui->searchContactText->text(); circleWidget.search(text, true, filterOnline(filter), filterOffline(filter)); } } bool Widget::groupsVisible() const { - FilterCriteria filter = getFilterCriteria(); + const FilterCriteria filter = getFilterCriteria(); return !filterGroups(filter); } @@ -2600,7 +2601,7 @@ void Widget::friendListContextMenu(const QPoint& pos) void Widget::friendRequestsUpdate() { - unsigned int unreadFriendRequests = settings.getUnreadFriendRequests(); + const unsigned int unreadFriendRequests = settings.getUnreadFriendRequests(); if (unreadFriendRequests == 0) { delete friendRequestsButton; diff --git a/test/chatlog/textformatter_test.cpp b/test/chatlog/textformatter_test.cpp index 4c708beffa..1d45945255 100644 --- a/test/chatlog/textformatter_test.cpp +++ b/test/chatlog/textformatter_test.cpp @@ -285,9 +285,9 @@ void workCasesTest(MarkdownFunction applyMarkdown, const QVector for (const MarkdownToTags& mtt : markdownToTags) { for (const StringPair& data : testData) { const QString input = processInput != nullptr ? processInput(data.first, mtt) : data.first; - QString output = processOutput != nullptr ? processOutput(data.second, mtt, showSymbols) - : data.second; - QString result = applyMarkdown(input, showSymbols); + const QString output = + processOutput != nullptr ? processOutput(data.second, mtt, showSymbols) : data.second; + const QString result = applyMarkdown(input, showSymbols); QVERIFY(output == result); } } @@ -307,7 +307,7 @@ void exceptionsTest(MarkdownFunction applyMarkdown, const QVector& pairs) { for (const auto& p : pairs) { - QString result = applyMarkdown(p.first, false); + const QString result = applyMarkdown(p.first, false); QVERIFY(p.second == result); } } @@ -336,7 +336,7 @@ using UrlHighlightFunction = QString (*)(const QString&); void urlHighlightTest(UrlHighlightFunction function, const QVector>& data) { for (const QPair& p : data) { - QString result = function(p.first); + const QString result = function(p.first); QVERIFY(p.second == result); } } diff --git a/test/core/chatid_test.cpp b/test/core/chatid_test.cpp index 308dc68efa..edaebc978b 100644 --- a/test/core/chatid_test.cpp +++ b/test/core/chatid_test.cpp @@ -39,15 +39,15 @@ private slots: void TestChatId::toStringTest() { - ToxPk pk(testPk); + const ToxPk pk(testPk); QVERIFY(testStr == pk.toString()); } void TestChatId::equalTest() { - ToxPk pk1(testPk); - ToxPk pk2(testPk); - ToxPk pk3(echoPk); + const ToxPk pk1(testPk); + const ToxPk pk2(testPk); + const ToxPk pk3(echoPk); QVERIFY(pk1 == pk2); QVERIFY(pk1 != pk3); QVERIFY(!(pk1 != pk2)); @@ -55,22 +55,22 @@ void TestChatId::equalTest() void TestChatId::clearTest() { - ToxPk empty; - ToxPk pk(testPk); + const ToxPk empty; + const ToxPk pk(testPk); QVERIFY(empty.isEmpty()); QVERIFY(!pk.isEmpty()); } void TestChatId::copyTest() { - ToxPk src(testPk); - ToxPk copy = src; + const ToxPk src(testPk); + const ToxPk copy = src; QVERIFY(copy == src); } void TestChatId::dataTest() { - ToxPk pk(testPk); + const ToxPk pk(testPk); QVERIFY(testPk == pk.getByteArray()); for (int i = 0; i < pk.getSize(); i++) { QVERIFY(testPkArray[i] == pk.getData()[i]); @@ -79,18 +79,18 @@ void TestChatId::dataTest() void TestChatId::sizeTest() { - ToxPk pk; - GroupId id; + const ToxPk pk; + const GroupId id; QVERIFY(pk.getSize() == ToxPk::size); QVERIFY(id.getSize() == GroupId::size); } void TestChatId::hashableTest() { - ToxPk pk1{testPkArray}; - ToxPk pk2{testPk}; + const ToxPk pk1{testPkArray}; + const ToxPk pk2{testPk}; QVERIFY(qHash(pk1) == qHash(pk2)); - ToxPk pk3{echoPk}; + const ToxPk pk3{echoPk}; QVERIFY(qHash(pk1) != qHash(pk3)); } diff --git a/test/core/core_test.cpp b/test/core/core_test.cpp index 249be9fbf6..df1f9fa198 100644 --- a/test/core/core_test.cpp +++ b/test/core/core_test.cpp @@ -65,8 +65,8 @@ void bootstrapToxes(Core& alice, MockBootstrapListGenerator& alicesNodes, Core& alicesNodes.setBootstrapNodes(MockBootstrapListGenerator::makeListFromSelf(bob)); bobsNodes.setBootstrapNodes(MockBootstrapListGenerator::makeListFromSelf(alice)); - QSignalSpy spyAlice(&alice, &Core::connected); - QSignalSpy spyBob(&bob, &Core::connected); + const QSignalSpy spyAlice(&alice, &Core::connected); + const QSignalSpy spyBob(&bob, &Core::connected); alice.start(); bob.start(); @@ -152,7 +152,7 @@ void TestCore::change_name() // Change the name of Alice to "Alice" const QLatin1String aliceName{"Alice"}; - QSignalSpy aliceSaveRequest(alice.get(), &Core::saveRequest); + const QSignalSpy aliceSaveRequest(alice.get(), &Core::saveRequest); QSignalSpy aliceUsernameChanged(alice.get(), &Core::usernameSet); QSignalSpy bobUsernameChangeReceived(bob.get(), &Core::friendUsernameChanged); @@ -183,7 +183,7 @@ void TestCore::change_status_message() // Change the status message of Alice const QLatin1String aliceStatusMsg{"Testing a lot"}; - QSignalSpy aliceSaveRequest(alice.get(), &Core::saveRequest); + const QSignalSpy aliceSaveRequest(alice.get(), &Core::saveRequest); QSignalSpy aliceStatusMsgChanged(alice.get(), &Core::statusMessageSet); QSignalSpy bobStatusMsgChangeReceived(bob.get(), &Core::friendStatusMessageChanged); @@ -211,7 +211,7 @@ void TestCore::change_status_message() void TestCore::change_status() { - QSignalSpy aliceSaveRequest(alice.get(), &Core::saveRequest); + const QSignalSpy aliceSaveRequest(alice.get(), &Core::saveRequest); QSignalSpy aliceStatusChanged(alice.get(), &Core::statusSet); QSignalSpy bobStatusChangeReceived(bob.get(), &Core::friendStatusChanged); diff --git a/test/core/toxid_test.cpp b/test/core/toxid_test.cpp index fc58e75a37..dd1cbe9f79 100644 --- a/test/core/toxid_test.cpp +++ b/test/core/toxid_test.cpp @@ -32,28 +32,28 @@ private slots: void TestToxId::toStringTest() { - ToxId toxId(testToxId); + const ToxId toxId(testToxId); QVERIFY(testToxId == toxId.toString()); } void TestToxId::equalTest() { - ToxId toxId1(testToxId); - ToxId toxId2(newNoSpam); + const ToxId toxId1(testToxId); + const ToxId toxId2(newNoSpam); QVERIFY(toxId1 == toxId2); QVERIFY(!(toxId1 != toxId2)); } void TestToxId::notEqualTest() { - ToxId toxId1(testToxId); - ToxId toxId2(echoToxId); + const ToxId toxId1(testToxId); + const ToxId toxId2(echoToxId); QVERIFY(toxId1 != toxId2); } void TestToxId::clearTest() { - ToxId empty; + const ToxId empty; ToxId test(testToxId); QVERIFY(empty != test); test.clear(); @@ -62,8 +62,8 @@ void TestToxId::clearTest() void TestToxId::copyTest() { - ToxId src(testToxId); - ToxId copy = src; + const ToxId src(testToxId); + const ToxId copy = src; QVERIFY(copy == src); } diff --git a/test/core/toxstring_test.cpp b/test/core/toxstring_test.cpp index 5c15be2f81..78d2b79c83 100644 --- a/test/core/toxstring_test.cpp +++ b/test/core/toxstring_test.cpp @@ -57,19 +57,19 @@ const int TestToxString::emptyLength = 0; void TestToxString::QStringTest() { // Create Test Object with QString constructor - ToxString test(testStr); + const ToxString test(testStr); // Check QString - QString test_string = test.getQString(); + const QString test_string = test.getQString(); QVERIFY(testStr == test_string); // Check QByteArray - QByteArray test_byte = test.getBytes(); + const QByteArray test_byte = test.getBytes(); QVERIFY(testByte == test_byte); // Check uint8_t pointer const uint8_t* test_int = test.data(); - size_t test_size = test.size(); + const size_t test_size = test.size(); QVERIFY(lengthUINT8 == test_size); for (int i = 0; i <= lengthUINT8; i++) { QVERIFY(testUINT8[i] == test_int[i]); @@ -83,19 +83,19 @@ void TestToxString::QStringTest() void TestToxString::QByteArrayTest() { // Create Test Object with QByteArray constructor - ToxString test(testByte); + const ToxString test(testByte); // Check QString - QString test_string = test.getQString(); + const QString test_string = test.getQString(); QVERIFY(testStr == test_string); // Check QByteArray - QByteArray test_byte = test.getBytes(); + const QByteArray test_byte = test.getBytes(); QVERIFY(testByte == test_byte); // Check uint8_t pointer const uint8_t* test_int = test.data(); - size_t test_size = test.size(); + const size_t test_size = test.size(); QVERIFY(lengthUINT8 == test_size); for (int i = 0; i <= lengthUINT8; i++) { QVERIFY(testUINT8[i] == test_int[i]); @@ -109,19 +109,19 @@ void TestToxString::QByteArrayTest() void TestToxString::uint8_tTest() { // Create Test Object with uint8_t constructor - ToxString test(testUINT8, lengthUINT8); + const ToxString test(testUINT8, lengthUINT8); // Check QString - QString test_string = test.getQString(); + const QString test_string = test.getQString(); QVERIFY(testStr == test_string); // Check QByteArray - QByteArray test_byte = test.getBytes(); + const QByteArray test_byte = test.getBytes(); QVERIFY(testByte == test_byte); // Check uint8_t pointer const uint8_t* test_int = test.data(); - size_t test_size = test.size(); + const size_t test_size = test.size(); QVERIFY(lengthUINT8 == test_size); for (int i = 0; i <= lengthUINT8; i++) { QVERIFY(testUINT8[i] == test_int[i]); @@ -135,19 +135,19 @@ void TestToxString::uint8_tTest() void TestToxString::emptyQStrTest() { // Create Test Object with QString constructor - ToxString test(emptyStr); + const ToxString test(emptyStr); // Check QString - QString test_string = test.getQString(); + const QString test_string = test.getQString(); QVERIFY(emptyStr == test_string); // Check QByteArray - QByteArray test_byte = test.getBytes(); + const QByteArray test_byte = test.getBytes(); QVERIFY(emptyByte == test_byte); // Check uint8_t pointer const uint8_t* test_int = test.data(); - size_t test_size = test.size(); + const size_t test_size = test.size(); QVERIFY(emptyLength == test_size); for (int i = 0; i <= emptyLength; i++) { QVERIFY(emptyUINT8[i] == test_int[i]); @@ -161,19 +161,19 @@ void TestToxString::emptyQStrTest() void TestToxString::emptyQByteTest() { // Create Test Object with QByteArray constructor - ToxString test(emptyByte); + const ToxString test(emptyByte); // Check QString - QString test_string = test.getQString(); + const QString test_string = test.getQString(); QVERIFY(emptyStr == test_string); // Check QByteArray - QByteArray test_byte = test.getBytes(); + const QByteArray test_byte = test.getBytes(); QVERIFY(emptyByte == test_byte); // Check uint8_t pointer const uint8_t* test_int = test.data(); - size_t test_size = test.size(); + const size_t test_size = test.size(); QVERIFY(emptyLength == test_size); for (int i = 0; i <= emptyLength; i++) { QVERIFY(emptyUINT8[i] == test_int[i]); @@ -187,19 +187,19 @@ void TestToxString::emptyQByteTest() void TestToxString::emptyUINT8Test() { // Create Test Object with uint8_t constructor - ToxString test(emptyUINT8, emptyLength); + const ToxString test(emptyUINT8, emptyLength); // Check QString - QString test_string = test.getQString(); + const QString test_string = test.getQString(); QVERIFY(emptyStr == test_string); // Check QByteArray - QByteArray test_byte = test.getBytes(); + const QByteArray test_byte = test.getBytes(); QVERIFY(emptyByte == test_byte); // Check uint8_t pointer const uint8_t* test_int = test.data(); - size_t test_size = test.size(); + const size_t test_size = test.size(); QVERIFY(emptyLength == test_size); for (int i = 0; i <= emptyLength; i++) { QVERIFY(emptyUINT8[i] == test_int[i]); @@ -213,19 +213,19 @@ void TestToxString::emptyUINT8Test() void TestToxString::nullptrUINT8Test() { // Create Test Object with uint8_t constructor - ToxString test(nullptr, 5); // nullptr and length = 5 + const ToxString test(nullptr, 5); // nullptr and length = 5 // Check QString - QString test_string = test.getQString(); + const QString test_string = test.getQString(); QVERIFY(emptyStr == test_string); // Check QByteArray - QByteArray test_byte = test.getBytes(); + const QByteArray test_byte = test.getBytes(); QVERIFY(emptyByte == test_byte); // Check uint8_t pointer const uint8_t* test_int = test.data(); - size_t test_size = test.size(); + const size_t test_size = test.size(); QVERIFY(emptyLength == test_size); for (int i = 0; i <= emptyLength; i++) { QVERIFY(emptyUINT8[i] == test_int[i]); diff --git a/test/model/friendlistmanager_test.cpp b/test/model/friendlistmanager_test.cpp index d8314c2757..24e1b36992 100644 --- a/test/model/friendlistmanager_test.cpp +++ b/test/model/friendlistmanager_test.cpp @@ -145,8 +145,8 @@ class FriendItemsBuilder "user with long nickname two"}; for (int i = 0; i < testNames.size(); ++i) { - int unsortedIndex = i % 2 ? i - 1 : testNames.size() - i - 1; // Mixes positions - int sortedByActivityIndex = testNames.size() - i - 1; + const int unsortedIndex = i % 2 ? i - 1 : testNames.size() - i - 1; // Mixes positions + const int sortedByActivityIndex = testNames.size() - i - 1; unsortedAllFriends.append(testNames[unsortedIndex]); sortedByNameOfflineFriends.append(testNames[i]); sortedByActivityFriends.append(testNames[sortedByActivityIndex]); @@ -169,8 +169,8 @@ class FriendItemsBuilder "user with long nickname two online"}; for (int i = 0; i < testNames.size(); ++i) { - int unsortedIndex = i % 2 ? i - 1 : testNames.size() - i - 1; - int sortedByActivityIndex = testNames.size() - i - 1; + const int unsortedIndex = i % 2 ? i - 1 : testNames.size() - i - 1; + const int sortedByActivityIndex = testNames.size() - i - 1; unsortedAllFriends.append(testNames[unsortedIndex]); sortedByNameOnlineFriends.append(testNames[i]); sortedByActivityFriends.append(testNames[sortedByActivityIndex]); @@ -278,9 +278,9 @@ class FriendItemsBuilder } // Add friends and set the date of the last activity by index - QDateTime dateTime = QDateTime::currentDateTime(); + const QDateTime dateTime = QDateTime::currentDateTime(); for (int i = 0; i < sortedByActivityFriends.size(); ++i) { - QString name = sortedByActivityFriends.at(i); + const QString name = sortedByActivityFriends.at(i); vec.push_back(std::shared_ptr( new MockFriend(name, isOnline(name), getDateTime(name)))); } @@ -324,7 +324,7 @@ class FriendItemsBuilder QDateTime getDateTime(const QString& name) { QDateTime dateTime = QDateTime::currentDateTime(); - int pos = sortedByActivityFriends.indexOf(name); + const int pos = sortedByActivityFriends.indexOf(name); if (pos == -1) { return dateTime; } @@ -399,7 +399,7 @@ void TestFriendListManager::testSortByName() auto manager = createManagerWithItems(unsortedVec); manager->sortByName(); - bool success = manager->getPositionsChanged(); + const bool success = manager->getPositionsChanged(); manager->sortByName(); QCOMPARE(success, true); @@ -409,7 +409,7 @@ void TestFriendListManager::testSortByName() for (int i = 0; i < sortedVec.size(); ++i) { IFriendListItem* fromManager = manager->getItems().at(i).get(); - std::shared_ptr fromSortedVec = sortedVec.at(i); + const std::shared_ptr fromSortedVec = sortedVec.at(i); QCOMPARE(fromManager->getNameItem(), fromSortedVec->getNameItem()); } } @@ -424,7 +424,7 @@ void TestFriendListManager::testSortByActivity() std::unique_ptr manager = createManagerWithItems(unsortedVec); manager->sortByActivity(); - bool success = manager->getPositionsChanged(); + const bool success = manager->getPositionsChanged(); manager->sortByActivity(); QCOMPARE(success, true); @@ -442,7 +442,7 @@ void TestFriendListManager::testSetFilter() FriendItemsBuilder listBuilder; auto manager = createManagerWithItems( listBuilder.addOfflineFriends()->addOnlineFriends()->addGroups()->buildUnsorted()); - QSignalSpy spy(manager.get(), &FriendListManager::itemsChanged); + const QSignalSpy spy(manager.get(), &FriendListManager::itemsChanged); manager->setFilter("", false, false, false); @@ -460,8 +460,8 @@ void TestFriendListManager::testApplyFilterSearchString() auto manager = createManagerWithItems( listBuilder.addOfflineFriends()->addOnlineFriends()->addGroups()->buildUnsorted()); QVector> resultVec; - QString testNameA = "NOITEMSWITHTHISNAME"; - QString testNameB = "Test Name B"; + const QString testNameA = "NOITEMSWITHTHISNAME"; + const QString testNameB = "Test Name B"; manager->sortByName(); manager->setFilter(testNameA, false, false, false); manager->applyFilter(); diff --git a/test/model/messageprocessor_test.cpp b/test/model/messageprocessor_test.cpp index 7a391eaf95..8639185ffa 100644 --- a/test/model/messageprocessor_test.cpp +++ b/test/model/messageprocessor_test.cpp @@ -76,7 +76,7 @@ void TestMessageProcessor::testSelfMention() QVERIFY(!messageHasSelfMention(processedMessage)); // make lower case - QString lower = QString(str).toLower(); + const QString lower = QString(str).toLower(); // The regex should be case insensitive processedMessage = messageProcessor.processIncomingCoreMessage(false, lower % " hi"); diff --git a/test/model/notificationgenerator_test.cpp b/test/model/notificationgenerator_test.cpp index 438dbffd19..0bfdcb3507 100644 --- a/test/model/notificationgenerator_test.cpp +++ b/test/model/notificationgenerator_test.cpp @@ -214,8 +214,8 @@ void TestNotificationGenerator::testMultipleGroupSourceMessages() { Group g(0, GroupId(QByteArray(32, 0)), "groupName", false, "selfName", *groupQuery, *coreIdHandler, *friendList); - Group g2(1, GroupId(QByteArray(32, 1)), "groupName2", false, "selfName", *groupQuery, - *coreIdHandler, *friendList); + const Group g2(1, GroupId(QByteArray(32, 1)), "groupName2", false, "selfName", *groupQuery, + *coreIdHandler, *friendList); auto sender = groupQuery->getGroupPeerPk(0, 0); g.updateUsername(sender, "sender1"); @@ -300,7 +300,7 @@ void TestNotificationGenerator::testGroupInviteUncounted() void TestNotificationGenerator::testFriendRequest() { - ToxPk sender(QByteArray(32, 0)); + const ToxPk sender(QByteArray(32, 0)); auto notificationData = notificationGenerator->friendRequestNotification(sender, "request"); @@ -312,7 +312,7 @@ void TestNotificationGenerator::testFriendRequestUncounted() { Friend f(0, ToxPk()); f.setName("friend"); - ToxPk sender(QByteArray(32, 0)); + const ToxPk sender(QByteArray(32, 0)); notificationGenerator->friendMessageNotification(&f, "test"); notificationGenerator->friendRequestNotification(sender, "request"); @@ -363,7 +363,7 @@ void TestNotificationGenerator::testSimpleGroupMessage() void TestNotificationGenerator::testSimpleFriendRequest() { - ToxPk sender(QByteArray(32, 0)); + const ToxPk sender(QByteArray(32, 0)); notificationSettings->setNotifyHide(true); diff --git a/test/net/bsu_test.cpp b/test/net/bsu_test.cpp index 3dcc90f5cd..f26bdcecd7 100644 --- a/test/net/bsu_test.cpp +++ b/test/net/bsu_test.cpp @@ -37,7 +37,7 @@ TestBootstrapNodesUpdater::TestBootstrapNodesUpdater() void TestBootstrapNodesUpdater::testOnline() { - QNetworkProxy proxy{QNetworkProxy::ProxyType::NoProxy}; + const QNetworkProxy proxy{QNetworkProxy::ProxyType::NoProxy}; Paths paths{Paths::Portable::NonPortable}; BootstrapNodeUpdater updater{proxy, paths}; @@ -47,13 +47,13 @@ void TestBootstrapNodesUpdater::testOnline() spy.wait(10000); // increase wait time for sporadic CI failures with slow nodes server QCOMPARE(spy.count(), 1); // make sure the signal was emitted exactly one time - QList result = qvariant_cast>(spy.at(0).at(0)); + const QList result = qvariant_cast>(spy.at(0).at(0)); QVERIFY(result.size() > 0); // some data should be returned } void TestBootstrapNodesUpdater::testLocal() { - QList defaultNodes = BootstrapNodeUpdater::loadDefaultBootstrapNodes(); + const QList defaultNodes = BootstrapNodeUpdater::loadDefaultBootstrapNodes(); QVERIFY(defaultNodes.size() > 0); } diff --git a/test/persistence/dbschema_test.cpp b/test/persistence/dbschema_test.cpp index ade48414a0..27392526dd 100644 --- a/test/persistence/dbschema_test.cpp +++ b/test/persistence/dbschema_test.cpp @@ -21,8 +21,8 @@ namespace { bool insertFileId(RawDatabase& db, int row, bool valid) { - QByteArray validResumeId(32, 1); - QByteArray invalidResumeId; + const QByteArray validResumeId(32, 1); + const QByteArray invalidResumeId; QByteArray resumeId; if (valid) { @@ -153,7 +153,7 @@ void TestDbSchema::cleanup() void TestDbSchema::testCreation() { - QVector queries; + const QVector queries; auto db = std::shared_ptr{new RawDatabase{testDatabaseFile->fileName(), {}, {}}}; QVERIFY(DbUpgrader::createCurrentSchema(*db)); DbUtility::verifyDb(db, DbUtility::schema11); @@ -177,11 +177,11 @@ void TestDbSchema::testNewerDb() { auto db = std::shared_ptr{new RawDatabase{testDatabaseFile->fileName(), {}, {}}}; createSchemaAtVersion(db, DbUtility::schema0); - int futureSchemaVersion = 1000000; + const int futureSchemaVersion = 1000000; db->execNow( RawDatabase::Query(QStringLiteral("PRAGMA user_version = %1").arg(futureSchemaVersion))); MockMessageBoxManager messageBoxManager; - bool success = DbUpgrader::dbSchemaUpgrade(db, messageBoxManager); + const bool success = DbUpgrader::dbSchemaUpgrade(db, messageBoxManager); QVERIFY(success == false); QVERIFY(messageBoxManager.getErrorsShown() == 1); } @@ -266,28 +266,28 @@ void TestDbSchema::test1to2() DbUtility::verifyDb(db, DbUtility::schema2); long brokenCount = -1; - RawDatabase::Query brokenCountQuery = {"SELECT COUNT(*) FROM broken_messages;", - [&](const QVector& row) { - brokenCount = row[0].toLongLong(); - }}; + const RawDatabase::Query brokenCountQuery = {"SELECT COUNT(*) FROM broken_messages;", + [&](const QVector& row) { + brokenCount = row[0].toLongLong(); + }}; QVERIFY(db->execNow(brokenCountQuery)); QVERIFY(brokenCount == 1); // only friend 1's first message is "broken" int fauxOfflineCount = -1; - RawDatabase::Query fauxOfflineCountQuery = {"SELECT COUNT(*) FROM faux_offline_pending;", - [&](const QVector& row) { - fauxOfflineCount = row[0].toLongLong(); - }}; + const RawDatabase::Query fauxOfflineCountQuery = {"SELECT COUNT(*) FROM faux_offline_pending;", + [&](const QVector& row) { + fauxOfflineCount = row[0].toLongLong(); + }}; QVERIFY(db->execNow(fauxOfflineCountQuery)); // both friend 1's third message and friend 2's third message should still be pending. // The broken message should no longer be pending. QVERIFY(fauxOfflineCount == 2); int totalHisoryCount = -1; - RawDatabase::Query totalHistoryCountQuery = {"SELECT COUNT(*) FROM history;", - [&](const QVector& row) { - totalHisoryCount = row[0].toLongLong(); - }}; + const RawDatabase::Query totalHistoryCountQuery = {"SELECT COUNT(*) FROM history;", + [&](const QVector& row) { + totalHisoryCount = row[0].toLongLong(); + }}; QVERIFY(db->execNow(totalHistoryCountQuery)); QVERIFY(totalHisoryCount == 6); // all messages should still be in history. } @@ -331,26 +331,26 @@ void TestDbSchema::test2to3() QVERIFY(DbUpgrader::dbSchema2to3(*db)); long brokenCount = -1; - RawDatabase::Query brokenCountQuery = {"SELECT COUNT(*) FROM broken_messages;", - [&](const QVector& row) { - brokenCount = row[0].toLongLong(); - }}; + const RawDatabase::Query brokenCountQuery = {"SELECT COUNT(*) FROM broken_messages;", + [&](const QVector& row) { + brokenCount = row[0].toLongLong(); + }}; QVERIFY(db->execNow(brokenCountQuery)); QVERIFY(brokenCount == 1); int fauxOfflineCount = -1; - RawDatabase::Query fauxOfflineCountQuery = {"SELECT COUNT(*) FROM faux_offline_pending;", - [&](const QVector& row) { - fauxOfflineCount = row[0].toLongLong(); - }}; + const RawDatabase::Query fauxOfflineCountQuery = {"SELECT COUNT(*) FROM faux_offline_pending;", + [&](const QVector& row) { + fauxOfflineCount = row[0].toLongLong(); + }}; QVERIFY(db->execNow(fauxOfflineCountQuery)); QVERIFY(fauxOfflineCount == 1); int totalHisoryCount = -1; - RawDatabase::Query totalHistoryCountQuery = {"SELECT COUNT(*) FROM history;", - [&](const QVector& row) { - totalHisoryCount = row[0].toLongLong(); - }}; + const RawDatabase::Query totalHistoryCountQuery = {"SELECT COUNT(*) FROM history;", + [&](const QVector& row) { + totalHisoryCount = row[0].toLongLong(); + }}; QVERIFY(db->execNow(totalHistoryCountQuery)); QVERIFY(totalHisoryCount == 4); diff --git a/test/persistence/offlinemsgengine_test.cpp b/test/persistence/offlinemsgengine_test.cpp index 7ab4d864e1..74addc61e6 100644 --- a/test/persistence/offlinemsgengine_test.cpp +++ b/test/persistence/offlinemsgengine_test.cpp @@ -34,7 +34,7 @@ void TestOfflineMsgEngine::testReceiptBeforeMessage() { OfflineMsgEngine offlineMsgEngine; - Message msg{false, QString(), QDateTime(), {}, {}}; + const Message msg{false, QString(), QDateTime(), {}, {}}; auto const receipt = ReceiptNum(0); offlineMsgEngine.onReceiptReceived(receipt); @@ -131,8 +131,8 @@ void TestOfflineMsgEngine::testCallback() size_t numCallbacks = 0; auto callback = [&numCallbacks](bool) { numCallbacks++; }; - Message msg{false, QString(), QDateTime(), {}, {}}; - ReceiptNum receipt; + const Message msg{false, QString(), QDateTime(), {}, {}}; + const ReceiptNum receipt; offlineMsgEngine.addSentCoreMessage(ReceiptNum(1), Message(), callback); offlineMsgEngine.addSentCoreMessage(ReceiptNum(2), Message(), callback); diff --git a/test/persistence/paths_test.cpp b/test/persistence/paths_test.cpp index 05e86895ff..c3b0ae7800 100644 --- a/test/persistence/paths_test.cpp +++ b/test/persistence/paths_test.cpp @@ -45,7 +45,7 @@ const QString sep{QDir::separator()}; */ void TestPaths::constructAuto() { - Paths paths{Paths::Portable::Auto}; + const Paths paths{Paths::Portable::Auto}; // auto detection should succeed // the test environment should not provide a `qtox.ini` QVERIFY(paths.isPortable() == false); @@ -56,7 +56,7 @@ void TestPaths::constructAuto() */ void TestPaths::constructPortable() { - Paths paths{Paths::Portable::Portable}; + const Paths paths{Paths::Portable::Portable}; // portable construction should succeed even though qtox.ini doesn't exist QVERIFY(paths.isPortable() == true); } @@ -66,7 +66,7 @@ void TestPaths::constructPortable() */ void TestPaths::constructNonPortable() { - Paths paths{Paths::Portable::NonPortable}; + const Paths paths{Paths::Portable::NonPortable}; // Non portable should succeed // the test environment should not provide a `qtox.ini` QVERIFY(paths.isPortable() == false); diff --git a/test/platform/posixsignalnotifier_test.cpp b/test/platform/posixsignalnotifier_test.cpp index c41fd9376e..4d0a661719 100644 --- a/test/platform/posixsignalnotifier_test.cpp +++ b/test/platform/posixsignalnotifier_test.cpp @@ -24,7 +24,7 @@ constexpr int TIMEOUT = 10; void TestPosixSignalNotifier::checkUsrSignalHandling() { - PosixSignalNotifier& psn = PosixSignalNotifier::globalInstance(); + const PosixSignalNotifier& psn = PosixSignalNotifier::globalInstance(); psn.watchSignal(SIGUSR1); QSignalSpy spy(&psn, &PosixSignalNotifier::activated); kill(getpid(), SIGUSR1); @@ -48,9 +48,9 @@ void sighandler(int sig) void TestPosixSignalNotifier::checkIgnoreExtraSignals() { - PosixSignalNotifier& psn = PosixSignalNotifier::globalInstance(); + const PosixSignalNotifier& psn = PosixSignalNotifier::globalInstance(); psn.watchSignal(SIGUSR1); - QSignalSpy spy(&psn, &PosixSignalNotifier::activated); + const QSignalSpy spy(&psn, &PosixSignalNotifier::activated); // To avoid kiiling signal(SIGUSR2, sighandler); @@ -66,12 +66,12 @@ void TestPosixSignalNotifier::checkIgnoreExtraSignals() void TestPosixSignalNotifier::checkTermSignalsHandling() { - PosixSignalNotifier& psn = PosixSignalNotifier::globalInstance(); + const PosixSignalNotifier& psn = PosixSignalNotifier::globalInstance(); psn.watchCommonTerminatingSignals(); - QSignalSpy spy(&psn, &PosixSignalNotifier::activated); + const QSignalSpy spy(&psn, &PosixSignalNotifier::activated); const std::initializer_list termSignals = {SIGHUP, SIGINT, SIGQUIT, SIGTERM}; - for (int signal : termSignals) { + for (const int signal : termSignals) { QCoreApplication::processEvents(); kill(getpid(), signal); sleep(1); @@ -86,7 +86,7 @@ void TestPosixSignalNotifier::checkTermSignalsHandling() for (size_t i = 0; i < termSignals.size(); ++i) { const QList& args = spy.at(static_cast(i)); - int signal = *(termSignals.begin() + i); + const int signal = *(termSignals.begin() + i); QCOMPARE(args.first().toInt(), signal); } }