From f95291af3ec82fb1faf9164a5ba920e752d75ea9 Mon Sep 17 00:00:00 2001 From: Zetok Zalbavar Date: Fri, 20 Mar 2015 18:38:10 +0000 Subject: [PATCH 1/2] Some style fixes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit "if(" → "if (" "for(" → "for (" "while(" → "while (" --- src/chatlog/chatline.cpp | 52 +++---- src/chatlog/chatlog.cpp | 156 ++++++++++----------- src/chatlog/chatmessage.cpp | 10 +- src/chatlog/content/filetransferwidget.cpp | 58 ++++---- src/chatlog/content/notificationicon.cpp | 4 +- src/chatlog/content/spinner.cpp | 4 +- src/chatlog/content/text.cpp | 62 ++++---- src/chatlog/documentcache.cpp | 6 +- src/chatlog/pixmapcache.cpp | 2 +- src/misc/smileypack.cpp | 2 +- src/video/cameraworker.cpp | 2 +- src/widget/form/chatform.cpp | 12 +- src/widget/form/genericchatform.cpp | 10 +- src/widget/friendwidget.cpp | 2 +- src/widget/widget.cpp | 4 +- 15 files changed, 193 insertions(+), 193 deletions(-) diff --git a/src/chatlog/chatline.cpp b/src/chatlog/chatline.cpp index d3617b347..592d19a94 100644 --- a/src/chatlog/chatline.cpp +++ b/src/chatlog/chatline.cpp @@ -27,9 +27,9 @@ ChatLine::ChatLine() ChatLine::~ChatLine() { - for(ChatLineContent* c : content) + for (ChatLineContent* c : content) { - if(c->scene()) + if (c->scene()) c->scene()->removeItem(c); delete c; @@ -40,15 +40,15 @@ void ChatLine::setRow(int idx) { row = idx; - for(int c = 0; c < static_cast(content.size()); ++c) + for (int c = 0; c < static_cast(content.size()); ++c) content[c]->setIndex(row, c); } void ChatLine::visibilityChanged(bool visible) { - if(isVisible != visible) + if (isVisible != visible) { - for(ChatLineContent* c : content) + for (ChatLineContent* c : content) c->visibilityChanged(visible); } @@ -62,7 +62,7 @@ int ChatLine::getRow() const ChatLineContent *ChatLine::getContent(int col) const { - if(col < static_cast(content.size()) && col >= 0) + if (col < static_cast(content.size()) && col >= 0) return content[col]; return nullptr; @@ -70,9 +70,9 @@ ChatLineContent *ChatLine::getContent(int col) const ChatLineContent *ChatLine::getContent(QPointF scenePos) const { - for(ChatLineContent* c: content) + for (ChatLineContent* c: content) { - if(c->sceneBoundingRect().contains(scenePos)) + if (c->sceneBoundingRect().contains(scenePos)) return c; } @@ -81,37 +81,37 @@ ChatLineContent *ChatLine::getContent(QPointF scenePos) const void ChatLine::removeFromScene() { - for(ChatLineContent* c : content) + for (ChatLineContent* c : content) { - if(c->scene()) + if (c->scene()) c->scene()->removeItem(c); } } void ChatLine::addToScene(QGraphicsScene *scene) { - if(!scene) + if (!scene) return; - for(ChatLineContent* c : content) + for (ChatLineContent* c : content) scene->addItem(c); } void ChatLine::setVisible(bool visible) { - for(ChatLineContent* c : content) + for (ChatLineContent* c : content) c->setVisible(visible); } void ChatLine::selectionCleared() { - for(ChatLineContent* c : content) + for (ChatLineContent* c : content) c->selectionCleared(); } void ChatLine::selectionFocusChanged(bool focusIn) { - for(ChatLineContent* c : content) + for (ChatLineContent* c : content) c->selectionFocusChanged(focusIn); } @@ -125,7 +125,7 @@ void ChatLine::updateBBox() bbox.setHeight(0); bbox.setWidth(width); - for(ChatLineContent* c : content) + for (ChatLineContent* c : content) bbox.setHeight(qMax(c->sceneBoundingRect().top() - bbox.top() + c->sceneBoundingRect().height(), bbox.height())); } @@ -136,7 +136,7 @@ QRectF ChatLine::sceneBoundingRect() const void ChatLine::addColumn(ChatLineContent* item, ColumnFormat fmt) { - if(!item) + if (!item) return; format.push_back(fmt); @@ -145,7 +145,7 @@ void ChatLine::addColumn(ChatLineContent* item, ColumnFormat fmt) void ChatLine::replaceContent(int col, ChatLineContent *lineContent) { - if(col >= 0 && col < static_cast(content.size()) && lineContent) + if (col >= 0 && col < static_cast(content.size()) && lineContent) { QGraphicsScene* scene = content[col]->scene(); delete content[col]; @@ -153,7 +153,7 @@ void ChatLine::replaceContent(int col, ChatLineContent *lineContent) content[col] = lineContent; lineContent->setIndex(row, col); - if(scene) + if (scene) scene->addItem(content[col]); layout(width, bbox.topLeft()); @@ -170,15 +170,15 @@ void ChatLine::layout(qreal w, QPointF scenePos) qreal fixedWidth = (content.size()-1) * columnSpacing; qreal varWidth = 0.0; // used for normalisation - for(int i = 0; i < static_cast(format.size()); ++i) + for (int i = 0; i < static_cast(format.size()); ++i) { - if(format[i].policy == ColumnFormat::FixedSize) + if (format[i].policy == ColumnFormat::FixedSize) fixedWidth += format[i].size; else varWidth += format[i].size; } - if(varWidth == 0.0) + if (varWidth == 0.0) varWidth = 1.0; qreal leftover = qMax(0.0, width - fixedWidth); @@ -188,11 +188,11 @@ void ChatLine::layout(qreal w, QPointF scenePos) qreal xPos[content.size()]; - for(int i = 0; i < static_cast(content.size()); ++i) + for (int i = 0; i < static_cast(content.size()); ++i) { // calculate the effective width of the current column qreal width; - if(format[i].policy == ColumnFormat::FixedSize) + if (format[i].policy == ColumnFormat::FixedSize) width = format[i].size; else width = format[i].size / varWidth * leftover; @@ -222,7 +222,7 @@ void ChatLine::layout(qreal w, QPointF scenePos) maxVOffset = qMax(maxVOffset, content[i]->getAscent()); } - for(int i = 0; i < static_cast(content.size()); ++i) + for (int i = 0; i < static_cast(content.size()); ++i) { // calculate vertical alignment // vertical alignment may depend on width, so we do it in a second pass @@ -238,7 +238,7 @@ void ChatLine::layout(qreal w, QPointF scenePos) void ChatLine::moveBy(qreal deltaY) { // reposition only - for(ChatLineContent* c : content) + for (ChatLineContent* c : content) c->moveBy(0, deltaY); bbox.moveTop(bbox.top() + deltaY); diff --git a/src/chatlog/chatlog.cpp b/src/chatlog/chatlog.cpp index 7a3795912..1ba19ccc1 100644 --- a/src/chatlog/chatlog.cpp +++ b/src/chatlog/chatlog.cpp @@ -30,9 +30,9 @@ template T clamp(T x, T min, T max) { - if(x > max) + if (x > max) return max; - if(x < min) + if (x < min) return min; return x; } @@ -110,22 +110,22 @@ ChatLog::ChatLog(QWidget* parent) ChatLog::~ChatLog() { // Remove chatlines from scene - for(ChatLine::Ptr l : lines) + for (ChatLine::Ptr l : lines) l->removeFromScene(); - if(busyNotification) + if (busyNotification) busyNotification->removeFromScene(); - if(typingNotification) + if (typingNotification) typingNotification->removeFromScene(); } void ChatLog::clearSelection() { - if(selectionMode == None) + if (selectionMode == None) return; - for(int i=selFirstRow; i<=selLastRow; ++i) + for (int i=selFirstRow; i<=selLastRow; ++i) lines[i]->selectionCleared(); selFirstRow = -1; @@ -151,20 +151,20 @@ void ChatLog::updateSceneRect() void ChatLog::layout(int start, int end, qreal width) { - if(lines.empty()) + if (lines.empty()) return; qreal h = 0.0; // Line at start-1 is considered to have the correct position. All following lines are // positioned in respect to this line. - if(start - 1 >= 0) + if (start - 1 >= 0) h = lines[start - 1]->sceneBoundingRect().bottom() + lineSpacing; start = clamp(start, 0, lines.size()); end = clamp(end + 1, 0, lines.size()); - for(int i = start; i < end; ++i) + for (int i = start; i < end; ++i) { ChatLine* l = lines[i].get(); @@ -179,15 +179,15 @@ void ChatLog::mousePressEvent(QMouseEvent* ev) QPointF scenePos = mapToScene(ev->pos()); - if(ev->button() == Qt::LeftButton) + if (ev->button() == Qt::LeftButton) { clickPos = ev->pos(); clearSelection(); } - if(ev->button() == Qt::RightButton) + if (ev->button() == Qt::RightButton) { - if(!isOverSelection(scenePos)) + if (!isOverSelection(scenePos)) clearSelection(); } } @@ -198,9 +198,9 @@ void ChatLog::mouseReleaseEvent(QMouseEvent* ev) QPointF scenePos = mapToScene(ev->pos()); - if(ev->button() == Qt::RightButton) + if (ev->button() == Qt::RightButton) { - if(!isOverSelection(scenePos)) + if (!isOverSelection(scenePos)) clearSelection(); } @@ -213,24 +213,24 @@ void ChatLog::mouseMoveEvent(QMouseEvent* ev) QPointF scenePos = mapToScene(ev->pos()); - if(ev->buttons() & Qt::LeftButton) + if (ev->buttons() & Qt::LeftButton) { //autoscroll - if(ev->pos().y() < 0) + if (ev->pos().y() < 0) selectionScrollDir = Up; - else if(ev->pos().y() > height()) + else if (ev->pos().y() > height()) selectionScrollDir = Down; else selectionScrollDir = NoDirection; //select - if(selectionMode == None && (clickPos - ev->pos()).manhattanLength() > QApplication::startDragDistance()) + if (selectionMode == None && (clickPos - ev->pos()).manhattanLength() > QApplication::startDragDistance()) { QPointF sceneClickPos = mapToScene(clickPos.toPoint()); ChatLine::Ptr line = findLineByPosY(scenePos.y()); ChatLineContent* content = getContentFromPos(sceneClickPos); - if(content) + if (content) { selClickedRow = content->getRow(); selClickedCol = content->getColumn(); @@ -242,10 +242,10 @@ void ChatLog::mouseMoveEvent(QMouseEvent* ev) selectionMode = Precise; // ungrab mouse grabber - if(scene->mouseGrabberItem()) + if (scene->mouseGrabberItem()) scene->mouseGrabberItem()->ungrabMouse(); } - else if(line.get()) + else if (line.get()) { selClickedRow = line->getRow(); selFirstRow = selClickedRow; @@ -255,37 +255,37 @@ void ChatLog::mouseMoveEvent(QMouseEvent* ev) } } - if(selectionMode != None) + if (selectionMode != None) { ChatLineContent* content = getContentFromPos(scenePos); ChatLine::Ptr line = findLineByPosY(scenePos.y()); int row; - if(content) + if (content) { row = content->getRow(); int col = content->getColumn(); - if(row == selClickedRow && col == selClickedCol) + if (row == selClickedRow && col == selClickedCol) { selectionMode = Precise; content->selectionMouseMove(scenePos); selGraphItem->hide(); } - else if(col != selClickedCol) + else if (col != selClickedCol) { selectionMode = Multi; lines[selClickedRow]->selectionCleared(); } } - else if(line.get()) + else if (line.get()) { row = line->getRow(); - if(row != selClickedRow) + if (row != selClickedRow) { selectionMode = Multi; @@ -296,10 +296,10 @@ void ChatLog::mouseMoveEvent(QMouseEvent* ev) else return; - if(row >= selClickedRow) + if (row >= selClickedRow) selLastRow = row; - if(row <= selClickedRow) + if (row <= selClickedRow) selFirstRow = row; updateMultiSelectionRect(); @@ -312,13 +312,13 @@ void ChatLog::mouseMoveEvent(QMouseEvent* ev) //Much faster than QGraphicsScene::itemAt()! ChatLineContent* ChatLog::getContentFromPos(QPointF scenePos) const { - if(lines.empty()) + if (lines.empty()) return nullptr; auto itr = std::lower_bound(lines.cbegin(), lines.cend(), scenePos.y(), ChatLine::lessThanBSRectBottom); //find content - if(itr != lines.cend() && (*itr)->sceneBoundingRect().contains(scenePos)) + if (itr != lines.cend() && (*itr)->sceneBoundingRect().contains(scenePos)) return (*itr)->getContent(scenePos); return nullptr; @@ -326,16 +326,16 @@ ChatLineContent* ChatLog::getContentFromPos(QPointF scenePos) const bool ChatLog::isOverSelection(QPointF scenePos) const { - if(selectionMode == Precise) + if (selectionMode == Precise) { ChatLineContent* content = getContentFromPos(scenePos); - if(content) + if (content) return content->isOverSelection(scenePos); } - else if(selectionMode == Multi) + else if (selectionMode == Multi) { - if(selGraphItem->rect().contains(scenePos)) + if (selGraphItem->rect().contains(scenePos)) return true; } @@ -349,13 +349,13 @@ qreal ChatLog::useableWidth() const void ChatLog::reposition(int start, int end, qreal deltaY) { - if(lines.isEmpty()) + if (lines.isEmpty()) return; start = clamp(start, 0, lines.size() - 1); end = clamp(end + 1, 0, lines.size()); - for(int i = start; i < end; ++i) + for (int i = start; i < end; ++i) { ChatLine* l = lines[i].get(); l->moveBy(deltaY); @@ -364,7 +364,7 @@ void ChatLog::reposition(int start, int end, qreal deltaY) void ChatLog::insertChatlineAtBottom(ChatLine::Ptr l) { - if(!l.get()) + if (!l.get()) return; bool stickToBtm = stickToBottom(); @@ -378,7 +378,7 @@ void ChatLog::insertChatlineAtBottom(ChatLine::Ptr l) layout(lines.last()->getRow(), lines.size(), useableWidth()); updateSceneRect(); - if(stickToBtm) + if (stickToBtm) scrollToBottom(); checkVisibility(); @@ -387,7 +387,7 @@ void ChatLog::insertChatlineAtBottom(ChatLine::Ptr l) void ChatLog::insertChatlineOnTop(ChatLine::Ptr l) { - if(!l.get()) + if (!l.get()) return; insertChatlineOnTop(QList() << l); @@ -395,7 +395,7 @@ void ChatLog::insertChatlineOnTop(ChatLine::Ptr l) void ChatLog::insertChatlineOnTop(const QList& newLines) { - if(newLines.isEmpty()) + if (newLines.isEmpty()) return; QGraphicsScene::ItemIndexMethod oldIndexMeth = scene->itemIndexMethod(); @@ -407,7 +407,7 @@ void ChatLog::insertChatlineOnTop(const QList& newLines) // add the new lines int i = 0; - for(ChatLine::Ptr l : newLines) + for (ChatLine::Ptr l : newLines) { l->addToScene(scene); l->visibilityChanged(false); @@ -416,7 +416,7 @@ void ChatLog::insertChatlineOnTop(const QList& newLines) } // add the old lines - for(ChatLine::Ptr l : lines) + for (ChatLine::Ptr l : lines) { l->setRow(i++); combLines.push_back(l); @@ -443,16 +443,16 @@ void ChatLog::scrollToBottom() void ChatLog::startResizeWorker() { - if(lines.empty()) + if (lines.empty()) return; // (re)start the worker - if(!workerTimer->isActive()) + if (!workerTimer->isActive()) { // these values must not be reevaluated while the worker is running workerStb = stickToBottom(); - if(!visibleLines.empty()) + if (!visibleLines.empty()) workerAnchorLine = visibleLines.first(); } @@ -480,7 +480,7 @@ void ChatLog::mouseDoubleClickEvent(QMouseEvent *ev) QPointF scenePos = mapToScene(ev->pos()); ChatLineContent* content = getContentFromPos(scenePos); - if(content) + if (content) { content->selectionDoubleClick(scenePos); selClickedCol = content->getColumn(); @@ -495,18 +495,18 @@ void ChatLog::mouseDoubleClickEvent(QMouseEvent *ev) QString ChatLog::getSelectedText() const { - if(selectionMode == Precise) + if (selectionMode == Precise) { return lines[selClickedRow]->content[selClickedCol]->getSelectedText(); } - else if(selectionMode == Multi) + else if (selectionMode == Multi) { // build a nicely formatted message QString out; - for(int i=selFirstRow; i<=selLastRow; ++i) + for (int i=selFirstRow; i<=selLastRow; ++i) { - if(lines[i]->content[1]->getText().isEmpty()) + if (lines[i]->content[1]->getText().isEmpty()) continue; QString timestamp = lines[i]->content[2]->getText().isEmpty() ? tr("pending") : lines[i]->content[2]->getText(); @@ -546,7 +546,7 @@ void ChatLog::clear() { clearSelection(); - for(ChatLine::Ptr l : lines) + for (ChatLine::Ptr l : lines) l->removeFromScene(); lines.clear(); @@ -560,13 +560,13 @@ void ChatLog::copySelectedText(bool toSelectionBuffer) const QString text = getSelectedText(); QClipboard* clipboard = QApplication::clipboard(); - if(clipboard && !text.isNull()) + if (clipboard && !text.isNull()) clipboard->setText(text, toSelectionBuffer ? QClipboard::Selection : QClipboard::Clipboard); } void ChatLog::setBusyNotification(ChatLine::Ptr notification) { - if(!notification.get()) + if (!notification.get()) return; busyNotification = notification; @@ -585,7 +585,7 @@ void ChatLog::setTypingNotification(ChatLine::Ptr notification) void ChatLog::setTypingNotificationVisible(bool visible) { - if(typingNotification.get()) + if (typingNotification.get()) { typingNotification->setVisible(visible); updateTypingNotification(); @@ -594,7 +594,7 @@ void ChatLog::setTypingNotificationVisible(bool visible) void ChatLog::scrollToLine(ChatLine::Ptr line) { - if(!line.get()) + if (!line.get()) return; updateSceneRect(); @@ -603,7 +603,7 @@ void ChatLog::scrollToLine(ChatLine::Ptr line) void ChatLog::selectAll() { - if(lines.empty()) + if (lines.empty()) return; clearSelection(); @@ -623,7 +623,7 @@ void ChatLog::forceRelayout() void ChatLog::checkVisibility() { - if(lines.empty()) + if (lines.empty()) return; // find first visible line @@ -634,18 +634,18 @@ void ChatLog::checkVisibility() // set visibilty QList newVisibleLines; - for(auto itr = lowerBound; itr != upperBound; ++itr) + for (auto itr = lowerBound; itr != upperBound; ++itr) { newVisibleLines.append(*itr); - if(!visibleLines.contains(*itr)) + if (!visibleLines.contains(*itr)) (*itr)->visibilityChanged(true); visibleLines.removeOne(*itr); } // these lines are no longer visible - for(ChatLine::Ptr line : visibleLines) + for (ChatLine::Ptr line : visibleLines) line->visibilityChanged(false); visibleLines = newVisibleLines; @@ -653,7 +653,7 @@ void ChatLog::checkVisibility() // enforce order std::sort(visibleLines.begin(), visibleLines.end(), ChatLine::lessThanRowIndex); - //if(!visibleLines.empty()) + //if (!visibleLines.empty()) // qDebug() << "visible from " << visibleLines.first()->getRow() << "to " << visibleLines.last()->getRow() << " total " << visibleLines.size(); } @@ -667,7 +667,7 @@ void ChatLog::resizeEvent(QResizeEvent* ev) { bool stb = stickToBottom(); - if(ev->size().width() != ev->oldSize().width()) + if (ev->size().width() != ev->oldSize().width()) { startResizeWorker(); stb = false; // let the resize worker handle it @@ -675,7 +675,7 @@ void ChatLog::resizeEvent(QResizeEvent* ev) QGraphicsView::resizeEvent(ev); - if(stb) + if (stb) scrollToBottom(); updateBusyNotification(); @@ -683,13 +683,13 @@ void ChatLog::resizeEvent(QResizeEvent* ev) void ChatLog::updateMultiSelectionRect() { - if(selectionMode == Multi && selFirstRow >= 0 && selLastRow >= 0) + if (selectionMode == Multi && selFirstRow >= 0 && selLastRow >= 0) { QRectF selBBox; selBBox = selBBox.united(lines[selFirstRow]->sceneBoundingRect()); selBBox = selBBox.united(lines[selLastRow]->sceneBoundingRect()); - if(selGraphItem->rect() != selBBox) + if (selGraphItem->rect() != selBBox) scene->invalidate(selGraphItem->rect()); selGraphItem->setRect(selBBox); @@ -704,12 +704,12 @@ void ChatLog::updateMultiSelectionRect() void ChatLog::updateTypingNotification() { ChatLine* notification = typingNotification.get(); - if(!notification) + if (!notification) return; qreal posY = 0.0; - if(!lines.empty()) + if (!lines.empty()) posY = lines.last()->sceneBoundingRect().bottom() + lineSpacing; notification->layout(useableWidth(), QPointF(0.0, posY)); @@ -717,7 +717,7 @@ void ChatLog::updateTypingNotification() void ChatLog::updateBusyNotification() { - if(busyNotification.get()) + if (busyNotification.get()) { //repoisition the busy notification (centered) busyNotification->layout(useableWidth(), getVisibleRect().topLeft() + QPointF(0, getVisibleRect().height()/2.0)); @@ -728,7 +728,7 @@ ChatLine::Ptr ChatLog::findLineByPosY(qreal yPos) const { auto itr = std::lower_bound(lines.cbegin(), lines.cend(), yPos, ChatLine::lessThanBSRectBottom); - if(itr != lines.cend()) + if (itr != lines.cend()) return *itr; return ChatLine::Ptr(); @@ -738,7 +738,7 @@ QRectF ChatLog::calculateSceneRect() const { qreal bottom = (lines.empty() ? 0.0 : lines.last()->sceneBoundingRect().bottom()); - if(typingNotification.get() != nullptr) + if (typingNotification.get() != nullptr) bottom += typingNotification->sceneBoundingRect().height() + lineSpacing; return QRectF(-margins.left(), -margins.top(), useableWidth(), bottom + margins.bottom() + margins.top()); @@ -771,7 +771,7 @@ void ChatLog::onWorkerTimeout() workerLastIndex += stepSize; // done? - if(workerLastIndex >= lines.size()) + if (workerLastIndex >= lines.size()) { workerTimer->stop(); @@ -785,7 +785,7 @@ void ChatLog::onWorkerTimeout() updateMultiSelectionRect(); // scroll - if(workerStb) + if (workerStb) scrollToBottom(); else scrollToLine(workerAnchorLine); @@ -809,11 +809,11 @@ void ChatLog::focusInEvent(QFocusEvent* ev) { QGraphicsView::focusInEvent(ev); - if(selectionMode != None) + if (selectionMode != None) { selGraphItem->setBrush(QBrush(selectionRectColor)); - for(int i=selFirstRow; i<=selLastRow; ++i) + for (int i=selFirstRow; i<=selLastRow; ++i) lines[i]->selectionFocusChanged(true); } } @@ -822,11 +822,11 @@ void ChatLog::focusOutEvent(QFocusEvent* ev) { QGraphicsView::focusOutEvent(ev); - if(selectionMode != None) + if (selectionMode != None) { selGraphItem->setBrush(QBrush(selectionRectColor.lighter(120))); - for(int i=selFirstRow; i<=selLastRow; ++i) + for (int i=selFirstRow; i<=selLastRow; ++i) lines[i]->selectionFocusChanged(false); } } diff --git a/src/chatlog/chatmessage.cpp b/src/chatlog/chatmessage.cpp index c58b3209d..58c3b2025 100644 --- a/src/chatlog/chatmessage.cpp +++ b/src/chatlog/chatmessage.cpp @@ -45,7 +45,7 @@ ChatMessage::Ptr ChatMessage::createChatMessage(const QString &sender, const QSt const QColor actionColor = QColor("#1818FF"); // has to match the color in innerStyle.css (div.action) //smileys - if(Settings::getInstance().getUseEmoticons()) + if (Settings::getInstance().getUseEmoticons()) text = SmileyPack::getInstance().smileyfied(text); //quotes (green text) @@ -70,7 +70,7 @@ ChatMessage::Ptr ChatMessage::createChatMessage(const QString &sender, const QSt msg->addColumn(new Text(text, Style::getFont(Style::Big), false, type == ACTION ? QString("*%1 %2*").arg(sender, rawMessage) : rawMessage), ColumnFormat(1.0, ColumnFormat::VariableSize)); msg->addColumn(new Spinner(":/ui/chatArea/spinner.svg", QSize(16, 16), 360.0/1.6), ColumnFormat(TIME_COL_WIDTH, ColumnFormat::FixedSize, ColumnFormat::Right)); - if(!date.isNull()) + if (!date.isNull()) msg->markAsSent(date); return msg; @@ -137,7 +137,7 @@ void ChatMessage::markAsSent(const QDateTime &time) QString ChatMessage::toString() const { ChatLineContent* c = getContent(1); - if(c) + if (c) return c->getText(); return QString(); @@ -156,14 +156,14 @@ void ChatMessage::setAsAction() void ChatMessage::hideSender() { ChatLineContent* c = getContent(0); - if(c) + if (c) c->hide(); } void ChatMessage::hideDate() { ChatLineContent* c = getContent(2); - if(c) + if (c) c->hide(); } diff --git a/src/chatlog/content/filetransferwidget.cpp b/src/chatlog/content/filetransferwidget.cpp index 3347bcc80..81a16d435 100644 --- a/src/chatlog/content/filetransferwidget.cpp +++ b/src/chatlog/content/filetransferwidget.cpp @@ -81,7 +81,7 @@ FileTransferWidget::FileTransferWidget(QWidget *parent, ToxFile file) setupButtons(); //preview - if(fileInfo.direction == ToxFile::SENDING) + if (fileInfo.direction == ToxFile::SENDING) { showPreview(fileInfo.filePath); ui->progressLabel->setText(tr("Waiting to send...", "file transfer widget")); @@ -110,7 +110,7 @@ void FileTransferWidget::autoAcceptTransfer(const QString &path) filepath = QString("%1/%2%3.%4").arg(path, base, number > 0 ? QString(" (%1)").arg(QString::number(number)) : QString(), suffix); number++; } - while(QFileInfo(filepath).exists()); + while (QFileInfo(filepath).exists()); //Do not automatically accept the file-transfer if the path is not writable. //The user can still accept it manually. @@ -122,11 +122,11 @@ void FileTransferWidget::autoAcceptTransfer(const QString &path) void FileTransferWidget::acceptTransfer(const QString &filepath) { - if(filepath.isEmpty()) + if (filepath.isEmpty()) return; //test if writable - if(!Nexus::isFilePathWritable(filepath)) + if (!Nexus::isFilePathWritable(filepath)) { QMessageBox::warning(0, tr("Location not writable","Title of permissions popup"), @@ -140,7 +140,7 @@ void FileTransferWidget::acceptTransfer(const QString &filepath) void FileTransferWidget::setBackgroundColor(const QColor &c, bool whiteFont) { - if(c != backgroundColor) + if (c != backgroundColor) { backgroundColorAnimation->setStartValue(backgroundColor); backgroundColorAnimation->setEndValue(c); @@ -157,7 +157,7 @@ void FileTransferWidget::setBackgroundColor(const QColor &c, bool whiteFont) void FileTransferWidget::setButtonColor(const QColor &c) { - if(c != buttonColor) + if (c != buttonColor) { buttonColorAnimation->setStartValue(buttonColor); buttonColorAnimation->setEndValue(c); @@ -184,12 +184,12 @@ void FileTransferWidget::paintEvent(QPaintEvent *) const int lineWidth = 1; // draw background - if(drawButtonAreaNeeded()) + if (drawButtonAreaNeeded()) painter.setClipRect(QRect(0,0,width()-buttonFieldWidth,height())); painter.setBrush(QBrush(backgroundColor)); painter.drawRoundRect(geometry(), r * ratio, r); - if(drawButtonAreaNeeded()) + if (drawButtonAreaNeeded()) { // draw button background (top) painter.setBrush(QBrush(buttonColor)); @@ -208,12 +208,12 @@ void FileTransferWidget::onFileTransferInfo(ToxFile file) QTime now = QTime::currentTime(); qint64 dt = lastTick.msecsTo(now); //ms - if(fileInfo != file || dt < 1000) + if (fileInfo != file || dt < 1000) return; fileInfo = file; - if(fileInfo.status == ToxFile::TRANSMITTING) + if (fileInfo.status == ToxFile::TRANSMITTING) { // update progress qreal progress = static_cast(file.bytesSent) / static_cast(file.filesize); @@ -230,13 +230,13 @@ void FileTransferWidget::onFileTransferInfo(ToxFile file) meanData[meanIndex++] = bytesPerSec; qreal meanBytesPerSec = 0.0; - for(size_t i = 0; i < TRANSFER_ROLLING_AVG_COUNT; ++i) + for (size_t i = 0; i < TRANSFER_ROLLING_AVG_COUNT; ++i) meanBytesPerSec += meanData[i]; meanBytesPerSec /= static_cast(TRANSFER_ROLLING_AVG_COUNT); // update UI - if(meanBytesPerSec > 0) + if (meanBytesPerSec > 0) { // ETA QTime toGo = QTime(0,0).addSecs((file.filesize - file.bytesSent) / meanBytesPerSec); @@ -261,7 +261,7 @@ void FileTransferWidget::onFileTransferInfo(ToxFile file) void FileTransferWidget::onFileTransferAccepted(ToxFile file) { - if(fileInfo != file) + if (fileInfo != file) return; fileInfo = file; @@ -273,7 +273,7 @@ void FileTransferWidget::onFileTransferAccepted(ToxFile file) void FileTransferWidget::onFileTransferCancelled(ToxFile file) { - if(fileInfo != file) + if (fileInfo != file) return; fileInfo = file; @@ -288,7 +288,7 @@ void FileTransferWidget::onFileTransferCancelled(ToxFile file) void FileTransferWidget::onFileTransferPaused(ToxFile file) { - if(fileInfo != file) + if (fileInfo != file) return; fileInfo = file; @@ -298,7 +298,7 @@ void FileTransferWidget::onFileTransferPaused(ToxFile file) // reset mean meanIndex = 0; - for(size_t i=0; ibottomButton->show(); // preview - if(fileInfo.direction == ToxFile::RECEIVING) + if (fileInfo.direction == ToxFile::RECEIVING) showPreview(fileInfo.filePath); disconnect(Core::getInstance(), 0, this, 0); @@ -382,7 +382,7 @@ void FileTransferWidget::setupButtons() ui->topButton->setIcon(QIcon(":/ui/fileTransferInstance/no.svg")); ui->topButton->setObjectName("cancel"); - if(fileInfo.direction == ToxFile::SENDING) + if (fileInfo.direction == ToxFile::SENDING) { ui->bottomButton->setIcon(QIcon(":/ui/fileTransferInstance/pause.svg")); ui->bottomButton->setObjectName("pause"); @@ -398,31 +398,31 @@ void FileTransferWidget::setupButtons() void FileTransferWidget::handleButton(QPushButton *btn) { - if(fileInfo.direction == ToxFile::SENDING) + if (fileInfo.direction == ToxFile::SENDING) { - if(btn->objectName() == "cancel") + if (btn->objectName() == "cancel") Core::getInstance()->cancelFileSend(fileInfo.friendId, fileInfo.fileNum); - else if(btn->objectName() == "pause") + else if (btn->objectName() == "pause") Core::getInstance()->pauseResumeFileSend(fileInfo.friendId, fileInfo.fileNum); - else if(btn->objectName() == "resume") + else if (btn->objectName() == "resume") Core::getInstance()->pauseResumeFileSend(fileInfo.friendId, fileInfo.fileNum); } else { - if(btn->objectName() == "cancel") + if (btn->objectName() == "cancel") Core::getInstance()->cancelFileRecv(fileInfo.friendId, fileInfo.fileNum); - else if(btn->objectName() == "pause") + else if (btn->objectName() == "pause") Core::getInstance()->pauseResumeFileRecv(fileInfo.friendId, fileInfo.fileNum); - else if(btn->objectName() == "resume") + else if (btn->objectName() == "resume") Core::getInstance()->pauseResumeFileRecv(fileInfo.friendId, fileInfo.fileNum); - else if(btn->objectName() == "accept") + else if (btn->objectName() == "accept") { QString path = QFileDialog::getSaveFileName(0, tr("Save a file","Title of the file saving dialog"), QDir::home().filePath(fileInfo.fileName)); acceptTransfer(path); } } - if(btn->objectName() == "ok") + if (btn->objectName() == "ok") { Widget::confirmExecutableOpen(QFileInfo(fileInfo.filePath)); } @@ -438,7 +438,7 @@ void FileTransferWidget::showPreview(const QString &filename) { static const QStringList previewExtensions = { "png", "jpeg", "jpg", "gif" }; - if(previewExtensions.contains(QFileInfo(filename).suffix())) + if (previewExtensions.contains(QFileInfo(filename).suffix())) { const int size = qMax(ui->previewLabel->width(), ui->previewLabel->height()); QPixmap pmap = QPixmap(filename).scaled(QSize(size, size), Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation); diff --git a/src/chatlog/content/notificationicon.cpp b/src/chatlog/content/notificationicon.cpp index f91e72cae..d093d1f32 100644 --- a/src/chatlog/content/notificationicon.cpp +++ b/src/chatlog/content/notificationicon.cpp @@ -68,7 +68,7 @@ void NotificationIcon::updateGradient() { alpha += 0.01; - if(alpha + dotWidth >= 1.0) + if (alpha + dotWidth >= 1.0) alpha = 0.0; grad = QLinearGradient(QPointF(-0.5*size.width(),0), QPointF(3.0/2.0*size.width(),0)); @@ -78,6 +78,6 @@ void NotificationIcon::updateGradient() grad.setColorAt(qMin(1.0, alpha + dotWidth), Qt::lightGray); grad.setColorAt(1, Qt::lightGray); - if(scene() && isVisible()) + if (scene() && isVisible()) scene()->invalidate(sceneBoundingRect()); } diff --git a/src/chatlog/content/spinner.cpp b/src/chatlog/content/spinner.cpp index 0f43a22b2..1bb143b09 100644 --- a/src/chatlog/content/spinner.cpp +++ b/src/chatlog/content/spinner.cpp @@ -70,7 +70,7 @@ void Spinner::setWidth(qreal width) void Spinner::visibilityChanged(bool visible) { - if(visible) + if (visible) timer.start(); else timer.stop(); @@ -83,6 +83,6 @@ qreal Spinner::getAscent() const void Spinner::timeout() { - if(scene()) + if (scene()) scene()->invalidate(sceneBoundingRect()); } diff --git a/src/chatlog/content/text.cpp b/src/chatlog/content/text.cpp index b5a61476a..da8175221 100644 --- a/src/chatlog/content/text.cpp +++ b/src/chatlog/content/text.cpp @@ -41,7 +41,7 @@ Text::Text(const QString& txt, QFont font, bool enableElide, const QString &rwTe Text::~Text() { - if(doc) + if (doc) DocumentCache::getInstance().push(doc); } @@ -56,7 +56,7 @@ void Text::setWidth(qreal w) width = w; dirty = true; - if(elide) + if (elide) { QFontMetrics metrics = QFontMetrics(defFont); elidedText = metrics.elidedText(text, Qt::ElideRight, width); @@ -67,11 +67,11 @@ void Text::setWidth(qreal w) void Text::selectionMouseMove(QPointF scenePos) { - if(!doc) + if (!doc) return; int cur = cursorFromPos(scenePos); - if(cur >= 0) + if (cur >= 0) { selectionEnd = cur; selectedText = extractSanitizedText(getSelectionStart(), getSelectionEnd()); @@ -83,7 +83,7 @@ void Text::selectionMouseMove(QPointF scenePos) void Text::selectionStarted(QPointF scenePos) { int cur = cursorFromPos(scenePos); - if(cur >= 0) + if (cur >= 0) { selectionEnd = cur; selectionAnchor = cur; @@ -103,12 +103,12 @@ void Text::selectionCleared() void Text::selectionDoubleClick(QPointF scenePos) { - if(!doc) + if (!doc) return; int cur = cursorFromPos(scenePos); - if(cur >= 0) + if (cur >= 0) { QTextCursor cursor(doc); cursor.setPosition(cur); @@ -132,7 +132,7 @@ void Text::selectionFocusChanged(bool focusIn) bool Text::isOverSelection(QPointF scenePos) const { int cur = cursorFromPos(scenePos); - if(getSelectionStart() < cur && getSelectionEnd() >= cur) + if (getSelectionStart() < cur && getSelectionEnd() >= cur) return true; return false; @@ -150,7 +150,7 @@ QRectF Text::boundingRect() const void Text::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) { - if(doc) + if (doc) { painter->setClipRect(boundingRect()); @@ -158,7 +158,7 @@ void Text::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWid QAbstractTextDocumentLayout::PaintContext ctx; QAbstractTextDocumentLayout::Selection sel; - if(hasSelection()) + if (hasSelection()) { sel.cursor = QTextCursor(doc); sel.cursor.setPosition(getSelectionStart()); @@ -194,30 +194,30 @@ qreal Text::getAscent() const void Text::mousePressEvent(QGraphicsSceneMouseEvent *event) { - if(event->button() == Qt::LeftButton) + if (event->button() == Qt::LeftButton) event->accept(); // grabber } void Text::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { - if(!doc) + if (!doc) return; QString anchor = doc->documentLayout()->anchorAt(event->pos()); // open anchor in browser - if(!anchor.isEmpty()) + if (!anchor.isEmpty()) QDesktopServices::openUrl(anchor); } void Text::hoverMoveEvent(QGraphicsSceneHoverEvent *event) { - if(!doc) + if (!doc) return; QString anchor = doc->documentLayout()->anchorAt(event->pos()); - if(!anchor.isEmpty()) + if (!anchor.isEmpty()) setCursor(QCursor(Qt::PointingHandCursor)); else setCursor(QCursor()); @@ -233,17 +233,17 @@ QString Text::getText() const void Text::regenerate() { - if(!doc) + if (!doc) { doc = DocumentCache::getInstance().pop(); dirty = true; } - if(dirty) + if (dirty) { doc->setDefaultFont(defFont); - if(!elide) + if (!elide) doc->setHtml(text); else doc->setPlainText(elidedText); @@ -258,11 +258,11 @@ void Text::regenerate() doc->documentLayout()->update(); // update ascent - if(doc->firstBlock().layout()->lineCount() > 0) + if (doc->firstBlock().layout()->lineCount() > 0) ascent = doc->firstBlock().layout()->lineAt(0).ascent(); // let the scene know about our change in size - if(size != idealSize()) + if (size != idealSize()) prepareGeometryChange(); // get the new width and height @@ -272,7 +272,7 @@ void Text::regenerate() } // if we are not visible -> free mem - if(!keepInMemory) + if (!keepInMemory) freeResources(); } @@ -284,7 +284,7 @@ void Text::freeResources() QSizeF Text::idealSize() { - if(doc) + if (doc) return QSizeF(qMin(doc->idealWidth(), width), doc->size().height()); return size; @@ -292,7 +292,7 @@ QSizeF Text::idealSize() int Text::cursorFromPos(QPointF scenePos, bool fuzzy) const { - if(doc) + if (doc) return doc->documentLayout()->hitTest(mapFromScene(scenePos), fuzzy ? Qt::FuzzyHit : Qt::ExactHit); return -1; @@ -315,23 +315,23 @@ bool Text::hasSelection() const QString Text::extractSanitizedText(int from, int to) const { - if(!doc) + if (!doc) return ""; QString txt; QTextBlock block = doc->firstBlock(); - for(QTextBlock::Iterator itr = block.begin(); itr!=block.end(); ++itr) + 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()) + 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); - if(pos >= from && pos < to) + if (pos >= from && pos < to) { txt += rune; pos++; @@ -339,9 +339,9 @@ QString Text::extractSanitizedText(int from, int to) const } else { - for(QChar c : itr.fragment().text()) + for (QChar c : itr.fragment().text()) { - if(pos >= from && pos < to) + if (pos >= from && pos < to) txt += c; pos++; @@ -354,9 +354,9 @@ QString Text::extractSanitizedText(int from, int to) const QString Text::extractImgTooltip(int pos) const { - for(QTextBlock::Iterator itr = doc->firstBlock().begin(); itr!=doc->firstBlock().end(); ++itr) + for (QTextBlock::Iterator itr = doc->firstBlock().begin(); itr!=doc->firstBlock().end(); ++itr) { - if(itr.fragment().contains(pos) && itr.fragment().charFormat().isImageFormat()) + if (itr.fragment().contains(pos) && itr.fragment().charFormat().isImageFormat()) { QTextImageFormat imgFmt = itr.fragment().charFormat().toImageFormat(); return imgFmt.toolTip(); diff --git a/src/chatlog/documentcache.cpp b/src/chatlog/documentcache.cpp index 093fa7ece..eb7d541a6 100644 --- a/src/chatlog/documentcache.cpp +++ b/src/chatlog/documentcache.cpp @@ -19,13 +19,13 @@ DocumentCache::~DocumentCache() { - while(!documents.isEmpty()) + while (!documents.isEmpty()) delete documents.pop(); } QTextDocument* DocumentCache::pop() { - if(documents.empty()) + if (documents.empty()) documents.push(new CustomTextDocument); return documents.pop(); @@ -33,7 +33,7 @@ QTextDocument* DocumentCache::pop() void DocumentCache::push(QTextDocument *doc) { - if(doc) + if (doc) { doc->clear(); documents.push(doc); diff --git a/src/chatlog/pixmapcache.cpp b/src/chatlog/pixmapcache.cpp index e2461704c..b171dbc90 100644 --- a/src/chatlog/pixmapcache.cpp +++ b/src/chatlog/pixmapcache.cpp @@ -20,7 +20,7 @@ QPixmap PixmapCache::get(const QString &filename, QSize size) { auto itr = cache.find(filename); - if(itr == cache.end()) + if (itr == cache.end()) { QIcon icon; icon.addFile(filename); diff --git a/src/misc/smileypack.cpp b/src/misc/smileypack.cpp index 73c07d979..7fd004c76 100644 --- a/src/misc/smileypack.cpp +++ b/src/misc/smileypack.cpp @@ -136,7 +136,7 @@ bool SmileyPack::load(const QString& filename) cacheSmiley(file); // preload all smileys - if(!getCachedSmiley(emoticon).isNull()) + if (!getCachedSmiley(emoticon).isNull()) emoticonSet.push_back(emoticon); stringElement = stringElement.nextSibling().toElement(); diff --git a/src/video/cameraworker.cpp b/src/video/cameraworker.cpp index 47acb377a..2ed27c686 100644 --- a/src/video/cameraworker.cpp +++ b/src/video/cameraworker.cpp @@ -157,7 +157,7 @@ void CameraWorker::subscribe() qDebug() << "CameraWorker:" << "OpenCV exception caught: " << e.what(); } - if(!bSuccess) + if (!bSuccess) { qDebug() << "CameraWorker: Could not open camera"; } diff --git a/src/widget/form/chatform.cpp b/src/widget/form/chatform.cpp index 14388f735..bcd4dc668 100644 --- a/src/widget/form/chatform.cpp +++ b/src/widget/form/chatform.cpp @@ -244,11 +244,11 @@ void ChatForm::onFileRecvRequest(ToxFile file) || Settings::getInstance().getAutoSaveEnabled()) { ChatLineContentProxy* proxy = dynamic_cast(msg->getContent(1)); - if(proxy) + if (proxy) { FileTransferWidget* tfWidget = dynamic_cast(proxy->getWidget()); - if(tfWidget) + if (tfWidget) tfWidget->autoAcceptTransfer(Settings::getInstance().getAutoAcceptDir(f->getToxID())); } } @@ -563,7 +563,7 @@ void ChatForm::onHangupCallTriggered() qDebug() << "onHangupCallTriggered"; //Fixes an OS X bug with ending a call while in full screen - if(netcam->isFullScreen()) + if (netcam->isFullScreen()) { netcam->showNormal(); } @@ -663,7 +663,7 @@ void ChatForm::enableCallButtons() videoButton->setToolTip(""); videoButton->disconnect(); - if(disableCallButtonsTimer == nullptr) + if (disableCallButtonsTimer == nullptr) { disableCallButtonsTimer = new QTimer(); connect(disableCallButtonsTimer, SIGNAL(timeout()), @@ -843,7 +843,7 @@ void ChatForm::loadHistory(QDateTime since, bool processUndelivered) authorId.isMine(), QDateTime()); - if(!isAction && prevId == authorId) + if (!isAction && prevId == authorId) msg->hideSender(); prevId = authorId; @@ -951,7 +951,7 @@ void ChatForm::setFriendTyping(bool isTyping) Text* text = dynamic_cast(chatWidget->getTypingNotification()->getContent(1)); - if(text) + if (text) text->setText("
" + QString("%1 is typing").arg(f->getDisplayedName()) + "
"); } diff --git a/src/widget/form/genericchatform.cpp b/src/widget/form/genericchatform.cpp index 760c028e4..d99138a94 100644 --- a/src/widget/form/genericchatform.cpp +++ b/src/widget/form/genericchatform.cpp @@ -225,7 +225,7 @@ ChatMessage::Ptr GenericChatForm::addMessage(const ToxID& author, const QString QString authorStr = author.isMine() ? Core::getInstance()->getUsername() : resolveToxID(author); ChatMessage::Ptr msg; - if(isAction) + if (isAction) { msg = ChatMessage::createChatMessage(authorStr, message, ChatMessage::ACTION, false); previousId.clear(); @@ -233,7 +233,7 @@ ChatMessage::Ptr GenericChatForm::addMessage(const ToxID& author, const QString else { msg = ChatMessage::createChatMessage(authorStr, message, ChatMessage::NORMAL, author.isMine()); - if(author == previousId) + if (author == previousId) msg->hideSender(); previousId = author; @@ -241,7 +241,7 @@ ChatMessage::Ptr GenericChatForm::addMessage(const ToxID& author, const QString insertChatMessage(msg); - if(isSent) + if (isSent) msg->markAsSent(datetime); return msg; @@ -258,7 +258,7 @@ void GenericChatForm::addAlertMessage(const ToxID &author, QString message, QDat ChatMessage::Ptr msg = ChatMessage::createChatMessage(authorStr, message, ChatMessage::ALERT, author.isMine(), datetime); insertChatMessage(msg); - if(author == previousId) + if (author == previousId) msg->hideSender(); previousId = author; @@ -303,7 +303,7 @@ void GenericChatForm::onSaveLogClicked() QString plainText; auto lines = chatWidget->getLines(); - for(ChatLine::Ptr l : lines) + for (ChatLine::Ptr l : lines) { Timestamp* rightCol = dynamic_cast(l->getContent(2)); ChatLineContent* middleCol = l->getContent(1); diff --git a/src/widget/friendwidget.cpp b/src/widget/friendwidget.cpp index 821f2d732..72686cadf 100644 --- a/src/widget/friendwidget.cpp +++ b/src/widget/friendwidget.cpp @@ -131,7 +131,7 @@ void FriendWidget::setAsActiveChatroom() if (isDefaultAvatar) avatar->setPixmap(QPixmap(":img/contact_dark.svg"), Qt::transparent); - if(!historyLoaded) + if (!historyLoaded) { Friend* f = FriendList::findFriend(friendId); if (Settings::getInstance().getEnableLogging()) diff --git a/src/widget/widget.cpp b/src/widget/widget.cpp index 5b9a415a3..992ab31f7 100644 --- a/src/widget/widget.cpp +++ b/src/widget/widget.cpp @@ -225,7 +225,7 @@ void Widget::setTranslation() bool Widget::eventFilter(QObject *obj, QEvent *event) { - if(event->type() == QEvent::WindowStateChange && obj != NULL) + if (event->type() == QEvent::WindowStateChange && obj != NULL) { QWindowStateChangeEvent * ce = static_cast(event); if (windowState() & Qt::WindowMinimized) @@ -426,7 +426,7 @@ void Widget::confirmExecutableOpen(const QFileInfo file) if (dangerousExtensions.contains(file.suffix())) { - if(!GUI::askQuestion(tr("Executable file", "popup title"), tr("You have asked qTox to open an executable file. Executable files can potentially damage your computer. Are you sure want to open this file?", "popup text"), false, true)) + if (!GUI::askQuestion(tr("Executable file", "popup title"), tr("You have asked qTox to open an executable file. Executable files can potentially damage your computer. Are you sure want to open this file?", "popup text"), false, true)) { return; } From f3aa3073b016ec6b1e04ba964df353277e463806 Mon Sep 17 00:00:00 2001 From: Zetok Zalbavar Date: Sat, 21 Mar 2015 08:59:28 +0000 Subject: [PATCH 2/2] Fix coding style and add copyright header MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * added copyright header to src/platform/statusnotifier/enums.c * 'switch(' → 'switch (' * use Allman style ---- for / if / while / switch () { ↓ for / if / while / switch () { ---- ---- for / if / while () { 1_line; } ↓ for / if / while () 1_line; ---- ---- for / if / while () 1_line; line_out_of_loop; ↓ for / if / while () 1_line; line_out_of_loop; ---- --- src/core.cpp | 119 ++++++++++++------ src/coreencryption.cpp | 21 +++- src/historykeeper.cpp | 3 +- src/main.cpp | 11 +- src/misc/flowlayout.cpp | 29 +++-- src/misc/settings.cpp | 49 +++++--- src/misc/smileypack.cpp | 3 +- src/platform/statusnotifier/enums.c | 91 ++++++++------ src/toxdns.cpp | 56 ++++++--- src/widget/form/addfriendform.cpp | 12 +- src/widget/form/groupchatform.cpp | 3 + src/widget/form/tabcompleter.cpp | 15 ++- src/widget/widget.cpp | 34 ++--- .../qtox-updater-genflist/main.cpp | 8 +- updater/widget.cpp | 7 +- 15 files changed, 303 insertions(+), 158 deletions(-) diff --git a/src/core.cpp b/src/core.cpp index b407ee2f3..680040d24 100644 --- a/src/core.cpp +++ b/src/core.cpp @@ -171,6 +171,7 @@ void Core::make_tox() toxOptions.proxy_type = TOX_PROXY_SOCKS5; else if (proxyType == ProxyType::ptHTTP) toxOptions.proxy_type = TOX_PROXY_HTTP; + uint16_t sz = CString::fromString(proxyAddr, (unsigned char*)toxOptions.proxy_address); toxOptions.proxy_address[sz] = 0; toxOptions.proxy_port = proxyPort; @@ -260,6 +261,7 @@ void Core::start() QString id = getSelfId().toString(); if (!id.isEmpty()) emit idSet(id); + setStatusMessage(tr("Toxing on qTox")); // this also solves the not updating issue setUsername(tr("qTox User")); } @@ -309,7 +311,9 @@ void Core::start() setAvatar(TOX_AVATAR_FORMAT_PNG, data); } else + { qDebug() << "Core: Error loading self avatar"; + } ready = true; @@ -340,7 +344,9 @@ void Core::process() #endif if (checkConnection()) + { tolerance = CORE_DISCONNECT_TOLERANCE; + } else if (!(--tolerance)) { bootstrapDht(); @@ -356,13 +362,16 @@ bool Core::checkConnection() //static int count = 0; bool toxConnected = tox_isconnected(tox); - if (toxConnected && !isConnected) { + if (toxConnected && !isConnected) + { qDebug() << "Core: Connected to DHT"; emit connected(); isConnected = true; //if (count) qDebug() << "Core: disconnect count:" << count; //count = 0; - } else if (!toxConnected && isConnected) { + } + else if (!toxConnected && isConnected) + { qDebug() << "Core: Disconnected to DHT"; emit disconnected(); isConnected = false; @@ -430,7 +439,8 @@ void Core::onStatusMessageChanged(Tox*/* tox*/, int friendId, const uint8_t* cMe void Core::onUserStatusChanged(Tox*/* tox*/, int friendId, uint8_t userstatus, void* core) { Status status; - switch (userstatus) { + switch (userstatus) + { case TOX_USERSTATUS_NONE: status = Status::Online; break; @@ -474,7 +484,9 @@ void Core::onConnectionStatusChanged(Tox*/* tox*/, int friendId, uint8_t status, emit static_cast(core)->fileTransferBrokenUnbroken(f, true); } } - } else { + } + else + { for (ToxFile& f : fileRecvQueue) { if (f.friendId == friendId && f.status == ToxFile::BROKEN) @@ -536,6 +548,7 @@ void Core::onGroupTitleChange(Tox*, int groupnumber, int peernumber, const uint8 QString author; if (peernumber >= 0) author = core->getGroupPeerName(groupnumber, peernumber); + emit core->groupTitleChanged(groupnumber, author, CString::toString(title, len)); } @@ -749,9 +762,12 @@ void Core::onReadReceiptCallback(Tox*, int32_t friendnumber, uint32_t receipt, v void Core::acceptFriendRequest(const QString& userId) { int friendId = tox_add_friend_norequest(tox, CUserId(userId).data()); - if (friendId == -1) { + if (friendId == -1) + { emit failedToAddFriend(userId); - } else { + } + else + { saveConfiguration(); emit friendAdded(friendId, userId); } @@ -782,6 +798,7 @@ void Core::requestFriendship(const QString& friendAddress, const QString& messag QString inviteStr = tr("/me offers friendship."); if (message.length()) inviteStr = tr("/me offers friendship, \"%1\"").arg(message); + HistoryKeeper::getInstance()->addChatEntry(userId, inviteStr, getSelfId().publicKey, QDateTime::currentDateTime(), true); emit friendAdded(friendId, userId); } @@ -1035,9 +1052,13 @@ void Core::removeFriend(int friendId, bool fake) { if (!isReady() || fake) return; - if (tox_del_friend(tox, friendId) == -1) { + + if (tox_del_friend(tox, friendId) == -1) + { emit failedToRemoveFriend(friendId); - } else { + } + else + { saveConfiguration(); emit friendRemoved(friendId); } @@ -1047,6 +1068,7 @@ void Core::removeGroup(int groupId, bool fake) { if (!isReady() || fake) return; + tox_del_groupchat(tox, groupId); if (groupCalls[groupId].active) @@ -1060,6 +1082,7 @@ QString Core::getUsername() const uint8_t* name = new uint8_t[size]; if (tox_get_self_name(tox, name) == size) sname = CString::toString(name, size); + delete[] name; return sname; } @@ -1068,9 +1091,12 @@ void Core::setUsername(const QString& username) { CString cUsername(username); - if (tox_set_name(tox, cUsername.data(), cUsername.size()) == -1) { + if (tox_set_name(tox, cUsername.data(), cUsername.size()) == -1) + { emit failedToSetUsername(username); - } else { + } + else + { emit usernameSet(username); saveConfiguration(); } @@ -1130,6 +1156,7 @@ QString Core::getStatusMessage() const uint8_t* name = new uint8_t[size]; if (tox_get_self_status_message(tox, name, size) == size) sname = CString::toString(name, size); + delete[] name; return sname; } @@ -1138,9 +1165,12 @@ void Core::setStatusMessage(const QString& message) { CString cMessage(message); - if (tox_set_status_message(tox, cMessage.data(), cMessage.size()) == -1) { + if (tox_set_status_message(tox, cMessage.data(), cMessage.size()) == -1) + { emit failedToSetStatusMessage(message); - } else { + } + else + { saveConfiguration(); emit statusMessageSet(message); } @@ -1149,7 +1179,8 @@ void Core::setStatusMessage(const QString& message) void Core::setStatus(Status status) { TOX_USERSTATUS userstatus; - switch (status) { + switch (status) + { case Status::Online: userstatus = TOX_USERSTATUS_NONE; break; @@ -1164,10 +1195,13 @@ void Core::setStatus(Status status) break; } - if (tox_set_user_status(tox, userstatus) == 0) { + if (tox_set_user_status(tox, userstatus) == 0) + { saveConfiguration(); emit statusSet(status); - } else { + } + else + { emit failedToSetStatus(status); } } @@ -1186,11 +1220,14 @@ QString Core::sanitize(QString name) QList banned = {'/', '\\', ':', '<', '>', '"', '|', '?', '*'}; for (QChar c : banned) name.replace(c, '_'); + // also remove leading and trailing periods if (name[0] == '.') name[0] = '_'; + if (name.endsWith('.')) name[name.length()-1] = '_'; + return name; } @@ -1201,18 +1238,21 @@ bool Core::loadConfiguration(QString path) QFile configurationFile(path); qDebug() << "Core::loadConfiguration: reading from " << path; - if (!configurationFile.exists()) { + if (!configurationFile.exists()) + { qWarning() << "The Tox configuration file was not found"; return true; } - if (!configurationFile.open(QIODevice::ReadOnly)) { + if (!configurationFile.open(QIODevice::ReadOnly)) + { qCritical() << "File " << path << " cannot be opened"; return true; } qint64 fileSize = configurationFile.size(); - if (fileSize > 0) { + if (fileSize > 0) + { QByteArray data = configurationFile.readAll(); int error = tox_load(tox, reinterpret_cast(data.data()), data.size()); if (error < 0) @@ -1272,6 +1312,7 @@ void Core::saveConfiguration() QDir directory(dir); if (!directory.exists() && !directory.mkpath(directory.absolutePath())) { qCritical() << "Error while creating directory " << dir; + return; } @@ -1329,30 +1370,35 @@ void Core::switchConfiguration(const QString& profile) void Core::loadFriends() { const uint32_t friendCount = tox_count_friendlist(tox); - if (friendCount > 0) { + if (friendCount > 0) + { // assuming there are not that many friends to fill up the whole stack int32_t *ids = new int32_t[friendCount]; tox_get_friendlist(tox, ids, friendCount); uint8_t clientId[TOX_PUBLIC_KEY_SIZE]; - for (int32_t i = 0; i < static_cast(friendCount); ++i) { - if (tox_get_client_id(tox, ids[i], clientId) == 0) { + for (int32_t i = 0; i < static_cast(friendCount); ++i) + { + if (tox_get_client_id(tox, ids[i], clientId) == 0) + { emit friendAdded(ids[i], CUserId::toString(clientId)); const int nameSize = tox_get_name_size(tox, ids[i]); - if (nameSize > 0) { + if (nameSize > 0) + { uint8_t *name = new uint8_t[nameSize]; - if (tox_get_name(tox, ids[i], name) == nameSize) { + if (tox_get_name(tox, ids[i], name) == nameSize) emit friendUsernameChanged(ids[i], CString::toString(name, nameSize)); - } + delete[] name; } const int statusMessageSize = tox_get_status_message_size(tox, ids[i]); - if (statusMessageSize > 0) { + if (statusMessageSize > 0) + { uint8_t *statusMessage = new uint8_t[statusMessageSize]; - if (tox_get_status_message(tox, ids[i], statusMessage, statusMessageSize) == statusMessageSize) { + if (tox_get_status_message(tox, ids[i], statusMessage, statusMessageSize) == statusMessageSize) emit friendStatusMessageChanged(ids[i], CString::toString(statusMessage, statusMessageSize)); - } + delete[] statusMessage; } @@ -1366,9 +1412,8 @@ void Core::loadFriends() void Core::checkLastOnline(int friendId) { const uint64_t lastOnline = tox_get_last_online(tox, friendId); - if (lastOnline > 0) { + if (lastOnline > 0) emit friendLastSeenChanged(friendId, QDateTime::fromTime_t(lastOnline)); - } } int Core::getGroupNumberPeers(int groupId) const @@ -1425,6 +1470,7 @@ QList Core::getGroupPeerNames(int groupId) const } for (int i=0; i Core::splitMessage(const QString &message, int maxLen) splitPos = maxLen; if (ba_message[splitPos] & 0x80) { - do { + do splitPos--; - } while (!(ba_message[splitPos] & 0x40)); + + while (!(ba_message[splitPos] & 0x40)); } splitPos--; } diff --git a/src/coreencryption.cpp b/src/coreencryption.cpp index b886d3504..84c33a551 100644 --- a/src/coreencryption.cpp +++ b/src/coreencryption.cpp @@ -107,6 +107,7 @@ QByteArray Core::encryptData(const QByteArray& data, PasswordType passtype) { if (!pwsaltedkeys[passtype]) return QByteArray(); + uint8_t encrypted[data.size() + tox_pass_encryption_extra_length()]; if (tox_pass_key_encrypt(reinterpret_cast(data.data()), data.size(), pwsaltedkeys[passtype], encrypted) == -1) { @@ -120,6 +121,7 @@ QByteArray Core::decryptData(const QByteArray& data, PasswordType passtype) { if (!pwsaltedkeys[passtype]) return QByteArray(); + int sz = data.size() - tox_pass_encryption_extra_length(); uint8_t decrypted[sz]; int decr_size = tox_pass_key_decrypt(reinterpret_cast(data.data()), data.size(), pwsaltedkeys[passtype], decrypted); @@ -183,7 +185,9 @@ bool Core::loadEncryptedSave(QByteArray& data) dialogtxt = tr("The profile password failed. Please try another?", "used only when pw set before load() doesn't work"); } else + { dialogtxt = a; + } uint8_t salt[tox_pass_salt_length()]; tox_get_salt(reinterpret_cast(data.data()), salt); @@ -198,11 +202,14 @@ bool Core::loadEncryptedSave(QByteArray& data) return false; } else + { setPassword(pw, ptMain, salt); + } error = tox_encrypted_key_load(tox, reinterpret_cast(data.data()), data.size(), pwsaltedkeys[ptMain]); dialogtxt = a + "\n" + b; - } while (error != 0); + } + while (error != 0); Settings::getInstance().setEncryptTox(true); return true; @@ -232,10 +239,12 @@ void Core::checkEncryptedHistory() { if (!exists || HistoryKeeper::checkPassword()) return; + dialogtxt = tr("The chat history password failed. Please try another?", "used only when pw set before load() doesn't work"); } else dialogtxt = a; + dialogtxt += "\n" + c; if (pwsaltedkeys[ptMain]) @@ -263,11 +272,14 @@ void Core::checkEncryptedHistory() return; } else + { setPassword(pw, ptHistory, reinterpret_cast(salt.data())); + } error = exists && !HistoryKeeper::checkPassword(); dialogtxt = a + "\n" + c + "\n" + b; - } while (error); + } + while (error); } void Core::saveConfiguration(const QString& path) @@ -282,7 +294,8 @@ void Core::saveConfiguration(const QString& path) } QSaveFile configurationFile(path); - if (!configurationFile.open(QIODevice::WriteOnly)) { + if (!configurationFile.open(QIODevice::WriteOnly)) + { qCritical() << "File " << path << " cannot be opened"; return; } @@ -318,7 +331,9 @@ void Core::saveConfiguration(const QString& path) } } else + { tox_save(tox, data); + } configurationFile.write(reinterpret_cast(data), fileSize); configurationFile.commit(); diff --git a/src/historykeeper.cpp b/src/historykeeper.cpp index d72f6a09d..09bb2390c 100644 --- a/src/historykeeper.cpp +++ b/src/historykeeper.cpp @@ -372,7 +372,8 @@ void HistoryKeeper::setSyncType(Db::syncType sType) { QString syncCmd; - switch (sType) { + switch (sType) + { case Db::syncType::stFull: syncCmd = "FULL"; break; diff --git a/src/main.cpp b/src/main.cpp index ee9efacc9..3488fe0de 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -179,15 +179,17 @@ int main(int argc, char *argv[]) sudoprocess->start(sudo); //Where the magic actually happens, safety checks ^ sudoprocess->waitForFinished(); - if (old_app.removeRecursively()) { //We've just deleted the running program + if (old_app.removeRecursively()) //We've just deleted the running program + { qDebug() << "OS X: Cleaned up old directory"; - } else { + } + else + { qDebug() << "OS X: This should never happen, the directory failed to delete"; } - if (fork() != 0) { //Forking is required otherwise it won't actually cleanly launch + if (fork() != 0) //Forking is required otherwise it won't actually cleanly launch return EXIT_UPDATE_MACX; - } qtoxprocess->start(qtox); @@ -259,6 +261,7 @@ int main(int argc, char *argv[]) uint32_t dest = 0; if (parser.isSet("p")) dest = Settings::getInstance().getCurrentProfileId(); + time_t event = ipc.postEvent("activate", QByteArray(), dest); if (ipc.waitUntilAccepted(event, 2)) { diff --git a/src/misc/flowlayout.cpp b/src/misc/flowlayout.cpp index c13df9957..cd2f93e79 100644 --- a/src/misc/flowlayout.cpp +++ b/src/misc/flowlayout.cpp @@ -67,20 +67,18 @@ void FlowLayout::addItem(QLayoutItem *item) int FlowLayout::horizontalSpacing() const { - if (m_hSpace >= 0) { + if (m_hSpace >= 0) return m_hSpace; - } else { + else return smartSpacing(QStyle::PM_LayoutHorizontalSpacing); - } } int FlowLayout::verticalSpacing() const { - if (m_vSpace >= 0) { + if (m_vSpace >= 0) return m_vSpace; - } else { + else return smartSpacing(QStyle::PM_LayoutVerticalSpacing); - } } int FlowLayout::count() const @@ -149,18 +147,22 @@ int FlowLayout::doLayout(const QRect &rect, bool testOnly) const int lineHeight = 0; QLayoutItem *item; - foreach (item, itemList) { + foreach (item, itemList) + { QWidget *wid = item->widget(); int spaceX = horizontalSpacing(); if (spaceX == -1) spaceX = wid->style()->layoutSpacing( QSizePolicy::PushButton, QSizePolicy::PushButton, Qt::Horizontal); + int spaceY = verticalSpacing(); if (spaceY == -1) spaceY = wid->style()->layoutSpacing( QSizePolicy::PushButton, QSizePolicy::PushButton, Qt::Vertical); + int nextX = x + item->sizeHint().width() + spaceX; - if (nextX - spaceX > effectiveRect.right() && lineHeight > 0) { + if (nextX - spaceX > effectiveRect.right() && lineHeight > 0) + { x = effectiveRect.x(); y = y + lineHeight + spaceY; nextX = x + item->sizeHint().width() + spaceX; @@ -178,12 +180,17 @@ int FlowLayout::doLayout(const QRect &rect, bool testOnly) const int FlowLayout::smartSpacing(QStyle::PixelMetric pm) const { QObject *parent = this->parent(); - if (!parent) { + if (!parent) + { return -1; - } else if (parent->isWidgetType()) { + } + else if (parent->isWidgetType()) + { QWidget *pw = static_cast(parent); return pw->style()->pixelMetric(pm, 0, pw); - } else { + } + else + { return static_cast(parent)->spacing(); } } diff --git a/src/misc/settings.cpp b/src/misc/settings.cpp index 750520f9c..f743f0dd6 100644 --- a/src/misc/settings.cpp +++ b/src/misc/settings.cpp @@ -54,6 +54,7 @@ Settings& Settings::getInstance() { if (!settings) settings = new Settings(); + return *settings; } @@ -91,7 +92,9 @@ QString Settings::detectProfile() { profile = askProfiles(); if (profile.isEmpty()) + { return ""; + } else { switchProfile(profile); @@ -111,6 +114,7 @@ QList Settings::searchProfiles() dir.setNameFilters(QStringList("*.tox")); for (QFileInfo file : dir.entryInfoList()) out += file.completeBaseName(); + return out; } @@ -153,7 +157,9 @@ void Settings::load() ps.endGroup(); } else + { makeToxPortable = false; + } QDir dir(getSettingsDirPath()); QString filePath = dir.filePath(FILENAME); @@ -177,7 +183,8 @@ void Settings::load() useCustomDhtList = true; qDebug() << "Using custom bootstrap nodes list"; int serverListSize = s.beginReadArray("dhtServerList"); - for (int i = 0; i < serverListSize; i ++) { + for (int i = 0; i < serverListSize; i ++) + { s.setArrayIndex(i); DhtServer server; server.name = s.value("name").toString(); @@ -189,7 +196,9 @@ void Settings::load() s.endArray(); } else + { useCustomDhtList=false; + } s.endGroup(); s.beginGroup("General"); @@ -225,9 +234,9 @@ void Settings::load() s.beginGroup("Widgets"); QList objectNames = s.childKeys(); - for (const QString& name : objectNames) { + for (const QString& name : objectNames) widgetSettings[name] = s.value(name).toByteArray(); - } + s.endGroup(); s.beginGroup("GUI"); @@ -279,7 +288,8 @@ void Settings::load() QSettings rcs(":/conf/settings.ini", QSettings::IniFormat); rcs.beginGroup("DHT Server"); int serverListSize = rcs.beginReadArray("dhtServerList"); - for (int i = 0; i < serverListSize; i ++) { + for (int i = 0; i < serverListSize; i ++) + { rcs.setArrayIndex(i); DhtServer server; server.name = rcs.value("name").toString(); @@ -354,7 +364,8 @@ void Settings::saveGlobal(QString path) s.beginGroup("DHT Server"); s.setValue("useCustomList", useCustomDhtList); s.beginWriteArray("dhtServerList", dhtServerList.size()); - for (int i = 0; i < dhtServerList.size(); i ++) { + for (int i = 0; i < dhtServerList.size(); i ++) + { s.setArrayIndex(i); s.setValue("name", dhtServerList[i].name); s.setValue("userId", dhtServerList[i].userId); @@ -393,9 +404,9 @@ void Settings::saveGlobal(QString path) s.beginGroup("Widgets"); const QList widgetNames = widgetSettings.keys(); - for (const QString& name : widgetNames) { + for (const QString& name : widgetNames) s.setValue(name, widgetSettings.value(name)); - } + s.endGroup(); s.beginGroup("GUI"); @@ -499,12 +510,15 @@ QPixmap Settings::getSavedAvatar(const QString &ownerId) QString filePath = dir.filePath("avatar_"+ownerId.left(64)); if (!QFileInfo(filePath).exists()) // try without truncation, for old self avatars filePath = dir.filePath("avatar_"+ownerId); + pic.load(filePath); saveAvatar(pic, ownerId); QFile::remove(filePath); } else + { pic.load(filePath); + } return pic; } @@ -524,6 +538,7 @@ void Settings::saveAvatarHash(const QByteArray& hash, const QString& ownerId) QFile file(dir.filePath("avatars/"+ownerId.left(64)+".hash")); if (!file.open(QIODevice::WriteOnly)) return; + file.write(hash); file.close(); } @@ -535,6 +550,7 @@ QByteArray Settings::getAvatarHash(const QString& ownerId) QFile file(dir.filePath("avatars/"+ownerId.left(64)+".hash")); if (!file.open(QIODevice::ReadOnly)) return QByteArray(); + QByteArray out = file.readAll(); file.close(); return out; @@ -824,6 +840,7 @@ void Settings::setAutoAwayTime(int newValue) { if (newValue < 0) newValue = 10; + autoAwayTime = newValue; } @@ -833,9 +850,7 @@ QString Settings::getAutoAcceptDir(const ToxID& id) const auto it = friendLst.find(key); if (it != friendLst.end()) - { return it->autoAcceptDir; - } return QString(); } @@ -848,7 +863,9 @@ void Settings::setAutoAcceptDir(const ToxID &id, const QString& dir) if (it != friendLst.end()) { it->autoAcceptDir = dir; - } else { + } + else + { updateFriendAdress(id.toString()); setAutoAcceptDir(id, dir); } @@ -1084,9 +1101,7 @@ QString Settings::getFriendAdress(const QString &publicKey) const QString key = ToxID::fromString(publicKey).publicKey; auto it = friendLst.find(key); if (it != friendLst.end()) - { return it->addr; - } return QString(); } @@ -1098,7 +1113,9 @@ void Settings::updateFriendAdress(const QString &newAddr) if (it != friendLst.end()) { it->addr = newAddr; - } else { + } + else + { friendProp fp; fp.addr = newAddr; fp.alias = ""; @@ -1112,9 +1129,7 @@ QString Settings::getFriendAlias(const ToxID &id) const QString key = id.publicKey; auto it = friendLst.find(key); if (it != friendLst.end()) - { return it->alias; - } return QString(); } @@ -1126,7 +1141,9 @@ void Settings::setFriendAlias(const ToxID &id, const QString &alias) if (it != friendLst.end()) { it->alias = alias; - } else { + } + else + { friendProp fp; fp.addr = key; fp.alias = alias; diff --git a/src/misc/smileypack.cpp b/src/misc/smileypack.cpp index 7fd004c76..79f67975b 100644 --- a/src/misc/smileypack.cpp +++ b/src/misc/smileypack.cpp @@ -206,9 +206,8 @@ QIcon SmileyPack::getCachedSmiley(const QString &key) // cache it if needed QString file = filenameTable.value(key); - if (!iconCache.contains(file)) { + if (!iconCache.contains(file)) cacheSmiley(file); - } return iconCache.value(file); } diff --git a/src/platform/statusnotifier/enums.c b/src/platform/statusnotifier/enums.c index 5c72d8363..e7c1ef292 100644 --- a/src/platform/statusnotifier/enums.c +++ b/src/platform/statusnotifier/enums.c @@ -1,4 +1,18 @@ +/* + Copyright (C) 2015 by Project Tox + This file is part of qTox, a Qt-based graphical interface for Tox. + + This program is libre software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + + See the COPYING file for more details. +*/ #include "enums.h" @@ -6,13 +20,14 @@ GType status_notifier_error_get_type (void) { static GType etype = 0; - if (etype == 0) { + if (etype == 0) + { static const GEnumValue values[] = { - { STATUS_NOTIFIER_ERROR_NO_CONNECTION, "STATUS_NOTIFIER_ERROR_NO_CONNECTION", "connection" }, - { STATUS_NOTIFIER_ERROR_NO_NAME, "STATUS_NOTIFIER_ERROR_NO_NAME", "name" }, - { STATUS_NOTIFIER_ERROR_NO_WATCHER, "STATUS_NOTIFIER_ERROR_NO_WATCHER", "watcher" }, - { STATUS_NOTIFIER_ERROR_NO_HOST, "STATUS_NOTIFIER_ERROR_NO_HOST", "host" }, - { 0, NULL, NULL } + { STATUS_NOTIFIER_ERROR_NO_CONNECTION, "STATUS_NOTIFIER_ERROR_NO_CONNECTION", "connection" }, + { STATUS_NOTIFIER_ERROR_NO_NAME, "STATUS_NOTIFIER_ERROR_NO_NAME", "name" }, + { STATUS_NOTIFIER_ERROR_NO_WATCHER, "STATUS_NOTIFIER_ERROR_NO_WATCHER", "watcher" }, + { STATUS_NOTIFIER_ERROR_NO_HOST, "STATUS_NOTIFIER_ERROR_NO_HOST", "host" }, + { 0, NULL, NULL } }; etype = g_enum_register_static ("StatusNotifierError", values); } @@ -22,13 +37,14 @@ GType status_notifier_state_get_type (void) { static GType etype = 0; - if (etype == 0) { + if (etype == 0) + { static const GEnumValue values[] = { - { STATUS_NOTIFIER_STATE_NOT_REGISTERED, "STATUS_NOTIFIER_STATE_NOT_REGISTERED", "not-registered" }, - { STATUS_NOTIFIER_STATE_REGISTERING, "STATUS_NOTIFIER_STATE_REGISTERING", "registering" }, - { STATUS_NOTIFIER_STATE_REGISTERED, "STATUS_NOTIFIER_STATE_REGISTERED", "registered" }, - { STATUS_NOTIFIER_STATE_FAILED, "STATUS_NOTIFIER_STATE_FAILED", "failed" }, - { 0, NULL, NULL } + { STATUS_NOTIFIER_STATE_NOT_REGISTERED, "STATUS_NOTIFIER_STATE_NOT_REGISTERED", "not-registered" }, + { STATUS_NOTIFIER_STATE_REGISTERING, "STATUS_NOTIFIER_STATE_REGISTERING", "registering" }, + { STATUS_NOTIFIER_STATE_REGISTERED, "STATUS_NOTIFIER_STATE_REGISTERED", "registered" }, + { STATUS_NOTIFIER_STATE_FAILED, "STATUS_NOTIFIER_STATE_FAILED", "failed" }, + { 0, NULL, NULL } }; etype = g_enum_register_static ("StatusNotifierState", values); } @@ -38,14 +54,15 @@ GType status_notifier_icon_get_type (void) { static GType etype = 0; - if (etype == 0) { + if (etype == 0) + { static const GEnumValue values[] = { - { STATUS_NOTIFIER_ICON, "STATUS_NOTIFIER_ICON", "status-notifier-icon" }, - { STATUS_NOTIFIER_ATTENTION_ICON, "STATUS_NOTIFIER_ATTENTION_ICON", "status-notifier-attention-icon" }, - { STATUS_NOTIFIER_OVERLAY_ICON, "STATUS_NOTIFIER_OVERLAY_ICON", "status-notifier-overlay-icon" }, - { STATUS_NOTIFIER_TOOLTIP_ICON, "STATUS_NOTIFIER_TOOLTIP_ICON", "status-notifier-tooltip-icon" }, - { _NB_STATUS_NOTIFIER_ICONS, "_NB_STATUS_NOTIFIER_ICONS", "-nb-status-notifier-icons" }, - { 0, NULL, NULL } + { STATUS_NOTIFIER_ICON, "STATUS_NOTIFIER_ICON", "status-notifier-icon" }, + { STATUS_NOTIFIER_ATTENTION_ICON, "STATUS_NOTIFIER_ATTENTION_ICON", "status-notifier-attention-icon" }, + { STATUS_NOTIFIER_OVERLAY_ICON, "STATUS_NOTIFIER_OVERLAY_ICON", "status-notifier-overlay-icon" }, + { STATUS_NOTIFIER_TOOLTIP_ICON, "STATUS_NOTIFIER_TOOLTIP_ICON", "status-notifier-tooltip-icon" }, + { _NB_STATUS_NOTIFIER_ICONS, "_NB_STATUS_NOTIFIER_ICONS", "-nb-status-notifier-icons" }, + { 0, NULL, NULL } }; etype = g_enum_register_static ("StatusNotifierIcon", values); } @@ -55,13 +72,14 @@ GType status_notifier_category_get_type (void) { static GType etype = 0; - if (etype == 0) { + if (etype == 0) + { static const GEnumValue values[] = { - { STATUS_NOTIFIER_CATEGORY_APPLICATION_STATUS, "STATUS_NOTIFIER_CATEGORY_APPLICATION_STATUS", "application-status" }, - { STATUS_NOTIFIER_CATEGORY_COMMUNICATIONS, "STATUS_NOTIFIER_CATEGORY_COMMUNICATIONS", "communications" }, - { STATUS_NOTIFIER_CATEGORY_SYSTEM_SERVICES, "STATUS_NOTIFIER_CATEGORY_SYSTEM_SERVICES", "system-services" }, - { STATUS_NOTIFIER_CATEGORY_HARDWARE, "STATUS_NOTIFIER_CATEGORY_HARDWARE", "hardware" }, - { 0, NULL, NULL } + { STATUS_NOTIFIER_CATEGORY_APPLICATION_STATUS, "STATUS_NOTIFIER_CATEGORY_APPLICATION_STATUS", "application-status" }, + { STATUS_NOTIFIER_CATEGORY_COMMUNICATIONS, "STATUS_NOTIFIER_CATEGORY_COMMUNICATIONS", "communications" }, + { STATUS_NOTIFIER_CATEGORY_SYSTEM_SERVICES, "STATUS_NOTIFIER_CATEGORY_SYSTEM_SERVICES", "system-services" }, + { STATUS_NOTIFIER_CATEGORY_HARDWARE, "STATUS_NOTIFIER_CATEGORY_HARDWARE", "hardware" }, + { 0, NULL, NULL } }; etype = g_enum_register_static ("StatusNotifierCategory", values); } @@ -71,12 +89,13 @@ GType status_notifier_status_get_type (void) { static GType etype = 0; - if (etype == 0) { + if (etype == 0) + { static const GEnumValue values[] = { - { STATUS_NOTIFIER_STATUS_PASSIVE, "STATUS_NOTIFIER_STATUS_PASSIVE", "passive" }, - { STATUS_NOTIFIER_STATUS_ACTIVE, "STATUS_NOTIFIER_STATUS_ACTIVE", "active" }, - { STATUS_NOTIFIER_STATUS_NEEDS_ATTENTION, "STATUS_NOTIFIER_STATUS_NEEDS_ATTENTION", "needs-attention" }, - { 0, NULL, NULL } + { STATUS_NOTIFIER_STATUS_PASSIVE, "STATUS_NOTIFIER_STATUS_PASSIVE", "passive" }, + { STATUS_NOTIFIER_STATUS_ACTIVE, "STATUS_NOTIFIER_STATUS_ACTIVE", "active" }, + { STATUS_NOTIFIER_STATUS_NEEDS_ATTENTION, "STATUS_NOTIFIER_STATUS_NEEDS_ATTENTION", "needs-attention" }, + { 0, NULL, NULL } }; etype = g_enum_register_static ("StatusNotifierStatus", values); } @@ -86,16 +105,14 @@ GType status_notifier_scroll_orientation_get_type (void) { static GType etype = 0; - if (etype == 0) { + if (etype == 0) + { static const GEnumValue values[] = { - { STATUS_NOTIFIER_SCROLL_ORIENTATION_HORIZONTAL, "STATUS_NOTIFIER_SCROLL_ORIENTATION_HORIZONTAL", "horizontal" }, - { STATUS_NOTIFIER_SCROLL_ORIENTATION_VERTICAL, "STATUS_NOTIFIER_SCROLL_ORIENTATION_VERTICAL", "vertical" }, - { 0, NULL, NULL } + { STATUS_NOTIFIER_SCROLL_ORIENTATION_HORIZONTAL, "STATUS_NOTIFIER_SCROLL_ORIENTATION_HORIZONTAL", "horizontal" }, + { STATUS_NOTIFIER_SCROLL_ORIENTATION_VERTICAL, "STATUS_NOTIFIER_SCROLL_ORIENTATION_VERTICAL", "vertical" }, + { 0, NULL, NULL } }; etype = g_enum_register_static ("StatusNotifierScrollOrientation", values); } return etype; } - - - diff --git a/src/toxdns.cpp b/src/toxdns.cpp index 11cd1670f..3d2e92f6b 100644 --- a/src/toxdns.cpp +++ b/src/toxdns.cpp @@ -58,35 +58,45 @@ QByteArray ToxDNS::fetchLastTextRecord(const QString& record, bool silent) qApp->processEvents(); QThread::msleep(100); } - if (timeout >= 30) { + if (timeout >= 30) + { dns.abort(); if (!silent) showWarning(tr("The connection timed out","The DNS gives the Tox ID associated to toxme.se addresses")); + return result; } - if (dns.error() == QDnsLookup::NotFoundError) { + if (dns.error() == QDnsLookup::NotFoundError) + { if (!silent) showWarning(tr("This address does not exist","The DNS gives the Tox ID associated to toxme.se addresses")); + return result; } - else if (dns.error() != QDnsLookup::NoError) { + else if (dns.error() != QDnsLookup::NoError) + { if (!silent) showWarning(tr("Error while looking up DNS","The DNS gives the Tox ID associated to toxme.se addresses")); + return result; } const QList textRecords = dns.textRecords(); - if (textRecords.isEmpty()) { + if (textRecords.isEmpty()) + { if (!silent) showWarning(tr("No text record found", "Error with the DNS")); + return result; } const QList textRecordValues = textRecords.last().values(); - if (textRecordValues.length() != 1) { + if (textRecordValues.length() != 1) + { if (!silent) showWarning(tr("Unexpected number of values in text record", "Error with the DNS")); + return result; } @@ -104,7 +114,8 @@ QString ToxDNS::queryTox1(const QString& record, bool silent) // Check toxdns protocol version int verx = entry.indexOf("v="); - if (verx) { + if (verx) + { verx += 2; int verend = entry.indexOf(';', verx); if (verend) @@ -114,6 +125,7 @@ QString ToxDNS::queryTox1(const QString& record, bool silent) { if (!silent) showWarning(tr("The version of Tox DNS used by this server is not supported", "Error with the DNS")); + return toxId; } } @@ -121,23 +133,29 @@ QString ToxDNS::queryTox1(const QString& record, bool silent) // Get the tox id int idx = entry.indexOf("id="); - if (idx < 0) { + if (idx < 0) + { if (!silent) showWarning(tr("The DNS lookup does not contain any Tox ID", "Error with the DNS")); + return toxId; } idx += 3; - if (entry.length() < idx + static_cast(TOX_ID_LENGTH)) { + if (entry.length() < idx + static_cast(TOX_ID_LENGTH)) + { if (!silent) showWarning(tr("The DNS lookup does not contain a valid Tox ID", "Error with the DNS")); + return toxId; } toxId = entry.mid(idx, TOX_ID_LENGTH); - if (!ToxID::isToxId(toxId)) { + if (!ToxID::isToxId(toxId)) + { if (!silent) showWarning(tr("The DNS lookup does not contain a valid Tox ID", "Error with the DNS")); + return toxId; } @@ -178,7 +196,8 @@ QString ToxDNS::queryTox3(const tox3_server& server, const QString &record, bool // Check toxdns protocol version verx = entry.indexOf("v="); - if (verx!=-1) { + if (verx!=-1) + { verx += 2; int verend = entry.indexOf(';', verx); if (verend!=-1) @@ -194,7 +213,8 @@ QString ToxDNS::queryTox3(const tox3_server& server, const QString &record, bool // Get and decrypt the tox id idx = entry.indexOf("id="); - if (idx < 0) { + if (idx < 0) + { qWarning() << "queryTox3: Server "<getSelfId().toString().toUpper()) GUI::showWarning(tr("Couldn't add friend"), tr("You can't add yourself as a friend!","When trying to add your own Tox ID as friend")); else emit friendRequested(id, getMessage()); + this->toxId.clear(); this->message.clear(); - } else { + } + else + { if (Settings::getInstance().getProxyType() != ProxyType::ptNone) { QMessageBox::StandardButton btn = QMessageBox::warning(main, "qTox", tr("qTox needs to use the Tox DNS, but can't do it through a proxy.\n\ diff --git a/src/widget/form/groupchatform.cpp b/src/widget/form/groupchatform.cpp index fc4c6d499..5624c9da7 100644 --- a/src/widget/form/groupchatform.cpp +++ b/src/widget/form/groupchatform.cpp @@ -110,7 +110,9 @@ void GroupChatForm::onSendTriggered() emit sendAction(group->getGroupId(), msg); } else + { emit sendMessage(group->getGroupId(), msg); + } } else addSelfMessage(msg, msg.startsWith("/me "), QDateTime::currentDateTime(), true); @@ -150,6 +152,7 @@ void GroupChatForm::onUserListChanged() QLabel* label = orderizer[names[i]]; if (i != nNames - 1) label->setText(label->text() + ", "); + namesListLayout->addWidget(label); } diff --git a/src/widget/form/tabcompleter.cpp b/src/widget/form/tabcompleter.cpp index 382fb6c8f..c535299f2 100644 --- a/src/widget/form/tabcompleter.cpp +++ b/src/widget/form/tabcompleter.cpp @@ -64,12 +64,14 @@ void TabCompleter::buildCompletionList() void TabCompleter::complete() { - if (!enabled) { + if (!enabled) + { buildCompletionList(); enabled = true; } - if (nextCompletion != completionMap.end()) { + if (nextCompletion != completionMap.end()) + { // clear previous completion auto cur = msgEdit->textCursor(); cur.setPosition(cur.selectionEnd()); @@ -85,13 +87,16 @@ void TabCompleter::complete() nextCompletion++; // we're completing the first word of the line - if (msgEdit->textCursor().position() == lastCompletionLength) { + if (msgEdit->textCursor().position() == lastCompletionLength) + { msgEdit->insertPlainText(nickSuffix); lastCompletionLength += nickSuffix.length(); } } - else { // we're at the end of the list -> start over again - if (!completionMap.isEmpty()) { + else + { // we're at the end of the list -> start over again + if (!completionMap.isEmpty()) + { nextCompletion = completionMap.begin(); complete(); } diff --git a/src/widget/widget.cpp b/src/widget/widget.cpp index 992ab31f7..cad1c270c 100644 --- a/src/widget/widget.cpp +++ b/src/widget/widget.cpp @@ -71,6 +71,7 @@ bool toxActivateEventHandler(const QByteArray&) { if (!Widget::getInstance()->isActiveWindow()) Widget::getInstance()->forceShow(); + return true; } @@ -247,7 +248,9 @@ void Widget::updateIcons() QString status; if (eventIcon) + { status = "event"; + } else { status = ui->statusButton->property("status").toString(); @@ -273,6 +276,7 @@ Widget::~Widget() AutoUpdater::abortUpdates(); if (icon) icon->hide(); + hideMainForms(); delete profileForm; delete settingsWidget; @@ -295,6 +299,7 @@ Widget* Widget::getInstance() if (!instance) instance = new Widget(); + return instance; } @@ -319,9 +324,7 @@ void Widget::changeEvent(QEvent *event) if (event->type() == QEvent::WindowStateChange) { if (isMinimized() && Settings::getInstance().getMinimizeToTray()) - { this->hide(); - } } } @@ -427,9 +430,7 @@ void Widget::confirmExecutableOpen(const QFileInfo file) if (dangerousExtensions.contains(file.suffix())) { if (!GUI::askQuestion(tr("Executable file", "popup title"), tr("You have asked qTox to open an executable file. Executable files can potentially damage your computer. Are you sure want to open this file?", "popup text"), false, true)) - { return; - } // The user wants to run this file, so make it executable and run it QFile(file.filePath()).setPermissions(file.permissions() | QFile::ExeOwner | QFile::ExeUser | QFile::ExeGroup | QFile::ExeOther); @@ -513,13 +514,12 @@ void Widget::hideMainForms() QLayoutItem* item; while ((item = ui->mainHead->layout()->takeAt(0)) != 0) item->widget()->hide(); + while ((item = ui->mainContent->layout()->takeAt(0)) != 0) item->widget()->hide(); if (activeChatroomWidget != nullptr) - { activeChatroomWidget->setAsInactiveChatroom(); - } } void Widget::onUsernameChanged(const QString& newUsername, const QString& oldUsername) @@ -639,7 +639,8 @@ void Widget::onFriendStatusChanged(int friendId, Status status) && Settings::getInstance().getStatusChangeNotificationEnabled()) { QString fStatus = ""; - switch(f->getStatus()){ + switch (f->getStatus()) + { case Status::Away: fStatus = tr("away", "contact status"); break; case Status::Busy: @@ -689,9 +690,8 @@ void Widget::onChatroomWidgetClicked(GenericChatroomWidget *widget) hideMainForms(); widget->setChatForm(*ui); if (activeChatroomWidget != nullptr) - { activeChatroomWidget->setAsInactiveChatroom(); - } + activeChatroomWidget = widget; widget->setAsActiveChatroom(); setWindowTitle(widget->getName()); @@ -762,6 +762,7 @@ void Widget::playRingtone() { if (ui->statusButton->property("status").toString() == "busy") return; + QApplication::alert(this); static QFile sndFile1(":audio/ToxicIncomingCall.pcm"); // for whatever reason this plays slower/downshifted from what any other program plays the file as... but whatever @@ -902,7 +903,9 @@ void Widget::onGroupNamelistChanged(int groupnumber, int peernumber, uint8_t Cha // g->getChatForm()->addSystemInfoMessage(tr("%1 has left the chat").arg(name), "white", QDateTime::currentDateTime()); } else if (change == TOX_CHAT_CHANGE_PEER_NAME) // core overwrites old name before telling us it changed... + { g->updatePeer(peernumber,Nexus::getCore()->getGroupPeerName(groupnumber, peernumber)); + } } void Widget::onGroupTitleChanged(int groupnumber, const QString& author, const QString& title) @@ -989,7 +992,7 @@ bool Widget::isFriendWidgetCurActiveWidget(Friend* f) bool Widget::event(QEvent * e) { - switch(e->type()) + switch (e->type()) { case QEvent::WindowActivate: if (activeChatroomWidget != nullptr) @@ -1034,7 +1037,9 @@ void Widget::onUserAwayCheck() } } else if (autoAwayActive) + { autoAwayActive = false; + } #endif } @@ -1077,10 +1082,14 @@ void Widget::onTryCreateTrayIcon() setHidden(Settings::getInstance().getAutostartInTray()); } else + { show(); + } } else if (!isVisible()) + { show(); + } } else { @@ -1133,6 +1142,7 @@ void Widget::onFriendTypingChanged(int friendId, bool isTyping) Friend* f = FriendList::findFriend(friendId); if (!f) return; + f->getChatForm()->setFriendTyping(isTyping); } @@ -1166,9 +1176,7 @@ void Widget::processOfflineMsgs() { QList frnds = FriendList::getAllFriends(); for (Friend *f : frnds) - { f->getChatForm()->getOfflineMsgEngine()->deliverOfflineMsgs(); - } OfflineMsgEngine::globalMutex.unlock(); } @@ -1178,9 +1186,7 @@ void Widget::clearAllReceipts() { QList frnds = FriendList::getAllFriends(); for (Friend *f : frnds) - { f->getChatForm()->getOfflineMsgEngine()->removeAllReciepts(); - } } void Widget::reloadTheme() diff --git a/tools/update-server/qtox-updater-genflist/main.cpp b/tools/update-server/qtox-updater-genflist/main.cpp index 602ee041f..e95b60869 100644 --- a/tools/update-server/qtox-updater-genflist/main.cpp +++ b/tools/update-server/qtox-updater-genflist/main.cpp @@ -21,7 +21,8 @@ QList scanDir(QDir dir) QList files; QStack stack; stack.push(dir.absolutePath()); - while (!stack.isEmpty()) { + while (!stack.isEmpty()) + { QString sSubdir = stack.pop(); QDir subdir(sSubdir); @@ -29,11 +30,13 @@ QList scanDir(QDir dir) QList sublist = subdir.entryList(QDir::Files); for (QString& file : sublist) file = dir.relativeFilePath(sSubdir + '/' + file); + files += sublist; QFileInfoList infoEntries = subdir.entryInfoList(QStringList(), QDir::AllDirs | QDir::NoSymLinks | QDir::NoDotAndDotDot); - for (int i = 0; i < infoEntries.size(); i++) { + for (int i = 0; i < infoEntries.size(); i++) + { QFileInfo& item = infoEntries[i]; stack.push(item.absoluteFilePath()); } @@ -131,4 +134,3 @@ int main(int argc, char* argv[]) flistFile.close(); return 0; } - diff --git a/updater/widget.cpp b/updater/widget.cpp index 678c6a770..1117c47e5 100644 --- a/updater/widget.cpp +++ b/updater/widget.cpp @@ -43,9 +43,7 @@ Widget::Widget(QWidget *parent) : // Updates only for supported platforms if (!supported) - { fatalError(tr("The qTox updater is not supported on this platform.")); - } QMetaObject::invokeMethod(this, "update", Qt::QueuedConnection); } @@ -107,6 +105,7 @@ void Widget::update() QFile updateFlistFile(updateDirStr+"flist"); if (!updateFlistFile.open(QIODevice::ReadOnly)) fatalError(tr("The update is incomplete.")); + QByteArray updateFlistData = updateFlistFile.readAll(); updateFlistFile.close(); @@ -120,9 +119,8 @@ void Widget::update() if (!QFile::exists(updateDirStr+fileMeta.installpath)) fatalError(tr("The update is incomplete.")); - if (diff.size() == 0){ + if (diff.size() == 0) fatalError(tr("The diff list is empty.")); - } setProgress(5); @@ -137,6 +135,7 @@ void Widget::update() QFile fileFile(updateDirStr+fileMeta.installpath); if (!fileFile.open(QIODevice::ReadOnly)) fatalError(tr("Update files are unreadable.")); + file.data = fileFile.readAll(); fileFile.close();