summaryrefslogtreecommitdiffstats
path: root/Swift
diff options
context:
space:
mode:
Diffstat (limited to 'Swift')
-rw-r--r--Swift/Controllers/AdHocManager.cpp5
-rw-r--r--Swift/Controllers/AdHocManager.h5
-rw-r--r--Swift/Controllers/BlockListController.cpp9
-rw-r--r--Swift/Controllers/Chat/MUCController.cpp32
-rw-r--r--Swift/Controllers/Chat/UnitTest/ChatsManagerTest.cpp14
-rw-r--r--Swift/Controllers/Chat/UnitTest/MUCControllerTest.cpp10
-rw-r--r--Swift/Controllers/Chat/UserSearchController.cpp16
-rw-r--r--Swift/Controllers/ChatMessageSummarizer.cpp3
-rw-r--r--Swift/Controllers/ContactSuggester.cpp3
-rw-r--r--Swift/Controllers/ContactsFromXMPPRoster.cpp3
-rw-r--r--Swift/Controllers/FileTransfer/FileTransferOverview.cpp5
-rw-r--r--Swift/Controllers/HighlightManager.cpp2
-rw-r--r--Swift/Controllers/HighlightRule.cpp11
-rw-r--r--Swift/Controllers/Highlighter.cpp2
-rw-r--r--Swift/Controllers/HistoryViewController.cpp21
-rw-r--r--Swift/Controllers/PreviousStatusStore.cpp4
-rw-r--r--Swift/Controllers/PreviousStatusStore.h1
-rw-r--r--Swift/Controllers/ProfileSettingsProvider.cpp4
-rw-r--r--Swift/Controllers/ProfileSettingsProvider.h10
-rw-r--r--Swift/Controllers/Roster/ContactRosterItem.cpp1
-rw-r--r--Swift/Controllers/Roster/RosterGroupExpandinessPersister.cpp3
-rw-r--r--Swift/Controllers/Roster/TableRoster.cpp5
-rw-r--r--Swift/Controllers/Settings/SettingsProviderHierachy.cpp14
-rw-r--r--Swift/Controllers/ShowProfileController.cpp4
-rw-r--r--Swift/Controllers/Storages/AvatarFileStorage.cpp1
-rw-r--r--Swift/Controllers/Storages/CertificateMemoryStorage.cpp6
-rw-r--r--Swift/Controllers/Storages/VCardFileStorage.cpp1
-rw-r--r--Swift/Controllers/UIInterfaces/ChatListWindow.h12
-rw-r--r--Swift/Controllers/UnitTest/ContactSuggesterTest.cpp22
-rw-r--r--Swift/Controllers/WhiteboardManager.cpp5
-rw-r--r--Swift/Controllers/XMPPEvents/EventController.cpp6
-rw-r--r--Swift/QtUI/ChatList/ChatListGroupItem.h5
-rw-r--r--Swift/QtUI/ChatList/ChatListModel.cpp5
-rw-r--r--Swift/QtUI/ChatList/QtChatListWindow.cpp2
-rw-r--r--Swift/QtUI/ChatSnippet.cpp2
-rw-r--r--Swift/QtUI/ChatSnippet.h2
-rw-r--r--Swift/QtUI/CocoaUIHelpers.mm6
-rw-r--r--Swift/QtUI/EventViewer/EventModel.cpp4
-rw-r--r--Swift/QtUI/QtAdHocCommandWindow.cpp4
-rw-r--r--Swift/QtUI/QtAffiliationEditor.cpp2
-rw-r--r--Swift/QtUI/QtBlockListEditorWindow.cpp3
-rw-r--r--Swift/QtUI/QtCertificateViewerDialog.cpp8
-rw-r--r--Swift/QtUI/QtChatTabs.cpp2
-rw-r--r--Swift/QtUI/QtChatTabsShortcutOnlySubstitute.cpp3
-rw-r--r--Swift/QtUI/QtChatWindow.cpp5
-rw-r--r--Swift/QtUI/QtContactEditWidget.cpp12
-rw-r--r--Swift/QtUI/QtContactEditWidget.h4
-rw-r--r--Swift/QtUI/QtEmoticonsGrid.cpp10
-rw-r--r--Swift/QtUI/QtFormResultItemModel.cpp4
-rw-r--r--Swift/QtUI/QtFormWidget.cpp16
-rw-r--r--Swift/QtUI/QtHistoryWindow.cpp2
-rw-r--r--Swift/QtUI/QtLoginWindow.cpp2
-rw-r--r--Swift/QtUI/QtPlainChatView.cpp3
-rw-r--r--Swift/QtUI/QtProfileWindow.cpp2
-rw-r--r--Swift/QtUI/QtSettingsProvider.cpp4
-rw-r--r--Swift/QtUI/QtSingleWindow.cpp6
-rw-r--r--Swift/QtUI/QtSpellCheckHighlighter.cpp4
-rw-r--r--Swift/QtUI/QtStatusWidget.cpp8
-rw-r--r--Swift/QtUI/QtSubscriptionRequestWindow.cpp2
-rw-r--r--Swift/QtUI/QtTabbable.cpp1
-rw-r--r--Swift/QtUI/QtVCardWidget/QtTagComboBox.cpp6
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardAddressField.cpp4
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardGeneralField.cpp2
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardOrganizationField.cpp4
-rw-r--r--Swift/QtUI/QtWebKitChatView.cpp2
-rw-r--r--Swift/QtUI/Roster/QtFilterWidget.cpp4
-rw-r--r--Swift/QtUI/Roster/QtOccupantListWidget.cpp2
-rw-r--r--Swift/QtUI/Roster/RosterModel.cpp2
-rw-r--r--Swift/QtUI/Roster/RosterTooltip.cpp8
-rw-r--r--Swift/QtUI/UserSearch/ContactListModel.cpp1
-rw-r--r--Swift/QtUI/UserSearch/QtContactListWidget.cpp4
-rw-r--r--Swift/QtUI/WinUIHelpers.cpp2
72 files changed, 180 insertions, 234 deletions
diff --git a/Swift/Controllers/AdHocManager.cpp b/Swift/Controllers/AdHocManager.cpp
index 81f80e2..717f083 100644
--- a/Swift/Controllers/AdHocManager.cpp
+++ b/Swift/Controllers/AdHocManager.cpp
@@ -1,95 +1,94 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/Controllers/AdHocManager.h>
#include <memory>
#include <boost/bind.hpp>
#include <Swiften/AdHoc/OutgoingAdHocCommandSession.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Queries/IQRouter.h>
#include <Swift/Controllers/UIEvents/RequestAdHocUIEvent.h>
#include <Swift/Controllers/UIEvents/RequestAdHocWithJIDUIEvent.h>
#include <Swift/Controllers/UIEvents/UIEventStream.h>
#include <Swift/Controllers/UIInterfaces/AdHocCommandWindowFactory.h>
#include <Swift/Controllers/UIInterfaces/MainWindow.h>
namespace Swift {
AdHocManager::AdHocManager(const JID& jid, AdHocCommandWindowFactory* factory, IQRouter* iqRouter, UIEventStream* uiEventStream, MainWindow* mainWindow) : jid_(jid) {
iqRouter_ = iqRouter;
uiEventStream_ = uiEventStream;
mainWindow_ = mainWindow;
factory_ = factory;
uiEventStream_->onUIEvent.connect(boost::bind(&AdHocManager::handleUIEvent, this, _1));
}
AdHocManager::~AdHocManager() {
uiEventStream_->onUIEvent.disconnect(boost::bind(&AdHocManager::handleUIEvent, this, _1));
for (auto& controller : controllers_) {
controller->onDeleting.disconnect(boost::bind(&AdHocManager::removeController, this, controller));
}
}
void AdHocManager::removeController(std::shared_ptr<AdHocController> controller) {
controller->onDeleting.disconnect(boost::bind(&AdHocManager::removeController, this, controller));
controllers_.erase(std::find(controllers_.begin(), controllers_.end(), controller));
}
void AdHocManager::setServerDiscoInfo(std::shared_ptr<DiscoInfo> info) {
if (iqRouter_->isAvailable() && info->hasFeature(DiscoInfo::CommandsFeature)) {
if (discoItemsRequest_) {
discoItemsRequest_->onResponse.disconnect(boost::bind(&AdHocManager::handleServerDiscoItemsResponse, this, _1, _2));
discoItemsRequest_.reset();
}
discoItemsRequest_ = GetDiscoItemsRequest::create(JID(jid_.getDomain()), DiscoInfo::CommandsFeature, iqRouter_);
discoItemsRequest_->onResponse.connect(boost::bind(&AdHocManager::handleServerDiscoItemsResponse, this, _1, _2));
discoItemsRequest_->send();
} else {
mainWindow_->setAvailableAdHocCommands(std::vector<DiscoItems::Item>());
}
}
void AdHocManager::setOnline(bool online) {
- foreach (std::shared_ptr<AdHocController> controller, controllers_) {
+ for (auto&& controller : controllers_) {
controller->setOnline(online);
}
}
void AdHocManager::handleServerDiscoItemsResponse(std::shared_ptr<DiscoItems> items, ErrorPayload::ref error) {
std::vector<DiscoItems::Item> commands;
if (!error) {
- foreach (DiscoItems::Item item, items->getItems()) {
+ for (const auto& item : items->getItems()) {
if (item.getNode() != "http://isode.com/xmpp/commands#test") {
commands.push_back(item);
}
}
}
mainWindow_->setAvailableAdHocCommands(commands);
}
void AdHocManager::handleUIEvent(std::shared_ptr<UIEvent> event) {
std::shared_ptr<RequestAdHocUIEvent> adHocEvent = std::dynamic_pointer_cast<RequestAdHocUIEvent>(event);
if (adHocEvent) {
std::shared_ptr<OutgoingAdHocCommandSession> command = std::make_shared<OutgoingAdHocCommandSession>(adHocEvent->getCommand().getJID(), adHocEvent->getCommand().getNode(), iqRouter_);
std::shared_ptr<AdHocController> controller = std::make_shared<AdHocController>(factory_, command);
controller->onDeleting.connect(boost::bind(&AdHocManager::removeController, this, controller));
controllers_.push_back(controller);
}
std::shared_ptr<RequestAdHocWithJIDUIEvent> adHocJIDEvent = std::dynamic_pointer_cast<RequestAdHocWithJIDUIEvent>(event);
if (!!adHocJIDEvent) {
std::shared_ptr<OutgoingAdHocCommandSession> command = std::make_shared<OutgoingAdHocCommandSession>(adHocJIDEvent->getJID(), adHocJIDEvent->getNode(), iqRouter_);
std::shared_ptr<AdHocController> controller = std::make_shared<AdHocController>(factory_, command);
controller->onDeleting.connect(boost::bind(&AdHocManager::removeController, this, controller));
controllers_.push_back(controller);
}
}
}
diff --git a/Swift/Controllers/AdHocManager.h b/Swift/Controllers/AdHocManager.h
index 20e5db7..0786370 100644
--- a/Swift/Controllers/AdHocManager.h
+++ b/Swift/Controllers/AdHocManager.h
@@ -1,48 +1,51 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
#include <vector>
#include <boost/signals2.hpp>
-#include <Swiften/Client/Client.h>
#include <Swiften/Disco/GetDiscoItemsRequest.h>
#include <Swiften/Elements/DiscoInfo.h>
#include <Swiften/Elements/DiscoItems.h>
#include <Swiften/Elements/ErrorPayload.h>
#include <Swiften/JID/JID.h>
#include <Swift/Controllers/AdHocController.h>
#include <Swift/Controllers/UIEvents/UIEvent.h>
namespace Swift {
class IQRouter;
class MainWindow;
class UIEventStream;
class AdHocCommandWindowFactory;
+
class AdHocManager {
public:
AdHocManager(const JID& jid, AdHocCommandWindowFactory* factory, IQRouter* iqRouter, UIEventStream* uiEventStream, MainWindow* mainWindow);
~AdHocManager();
void removeController(std::shared_ptr<AdHocController> contoller);
void setServerDiscoInfo(std::shared_ptr<DiscoInfo> info);
void setOnline(bool online);
+
private:
void handleServerDiscoItemsResponse(std::shared_ptr<DiscoItems>, ErrorPayload::ref error);
void handleUIEvent(std::shared_ptr<UIEvent> event);
boost::signals2::signal<void (const AdHocController&)> onControllerComplete;
+
+private:
JID jid_;
IQRouter* iqRouter_;
UIEventStream* uiEventStream_;
MainWindow* mainWindow_;
AdHocCommandWindowFactory* factory_;
GetDiscoItemsRequest::ref discoItemsRequest_;
std::vector<std::shared_ptr<AdHocController> > controllers_;
};
}
diff --git a/Swift/Controllers/BlockListController.cpp b/Swift/Controllers/BlockListController.cpp
index 560a3f3..37c536b 100644
--- a/Swift/Controllers/BlockListController.cpp
+++ b/Swift/Controllers/BlockListController.cpp
@@ -1,79 +1,78 @@
/*
* Copyright (c) 2013 Tobias Markmann
* Licensed under the simplified BSD license.
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
/*
* Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/Controllers/BlockListController.h>
#include <boost/bind.hpp>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Base/format.h>
#include <Swiften/Client/ClientBlockListManager.h>
#include <Swift/Controllers/Intl.h>
#include <Swift/Controllers/UIEvents/RequestBlockListDialogUIEvent.h>
#include <Swift/Controllers/UIEvents/RequestChangeBlockStateUIEvent.h>
#include <Swift/Controllers/UIInterfaces/BlockListEditorWidget.h>
#include <Swift/Controllers/XMPPEvents/ErrorEvent.h>
#include <Swift/Controllers/XMPPEvents/EventController.h>
namespace Swift {
BlockListController::BlockListController(ClientBlockListManager* blockListManager, UIEventStream* uiEventStream, BlockListEditorWidgetFactory* blockListEditorWidgetFactory, EventController* eventController) : blockListManager_(blockListManager), blockListEditorWidgetFactory_(blockListEditorWidgetFactory), blockListEditorWidget_(nullptr), eventController_(eventController), remainingRequests_(0), uiEventStream_(uiEventStream) {
uiEventStream->onUIEvent.connect(boost::bind(&BlockListController::handleUIEvent, this, _1));
blockListManager_->getBlockList()->onItemAdded.connect(boost::bind(&BlockListController::handleBlockListChanged, this));
blockListManager_->getBlockList()->onItemRemoved.connect(boost::bind(&BlockListController::handleBlockListChanged, this));
}
BlockListController::~BlockListController() {
uiEventStream_->onUIEvent.disconnect(boost::bind(&BlockListController::handleUIEvent, this, _1));
blockListManager_->getBlockList()->onItemAdded.disconnect(boost::bind(&BlockListController::handleBlockListChanged, this));
blockListManager_->getBlockList()->onItemRemoved.disconnect(boost::bind(&BlockListController::handleBlockListChanged, this));
}
void BlockListController::blockListDifferences(const std::vector<JID> &newBlockList, std::vector<JID> &jidsToUnblock, std::vector<JID> &jidsToBlock) const {
- foreach (const JID& jid, blockListBeforeEdit) {
+ for (const auto& jid : blockListBeforeEdit) {
if (std::find(newBlockList.begin(), newBlockList.end(), jid) == newBlockList.end()) {
jidsToUnblock.push_back(jid);
}
}
- foreach (const JID& jid, newBlockList) {
+ for (const auto& jid : newBlockList) {
if (std::find(blockListBeforeEdit.begin(), blockListBeforeEdit.end(), jid) == blockListBeforeEdit.end()) {
jidsToBlock.push_back(jid);
}
}
}
void BlockListController::handleUIEvent(std::shared_ptr<UIEvent> rawEvent) {
// handle UI dialog
std::shared_ptr<RequestBlockListDialogUIEvent> requestDialogEvent = std::dynamic_pointer_cast<RequestBlockListDialogUIEvent>(rawEvent);
if (requestDialogEvent != nullptr) {
if (blockListEditorWidget_ == nullptr) {
blockListEditorWidget_ = blockListEditorWidgetFactory_->createBlockListEditorWidget();
blockListEditorWidget_->onSetNewBlockList.connect(boost::bind(&BlockListController::handleSetNewBlockList, this, _1));
}
blockListBeforeEdit = blockListManager_->getBlockList()->getItems();
blockListEditorWidget_->setCurrentBlockList(blockListBeforeEdit);
blockListEditorWidget_->setError("");
blockListEditorWidget_->show();
return;
}
// handle block state change
std::shared_ptr<RequestChangeBlockStateUIEvent> changeStateEvent = std::dynamic_pointer_cast<RequestChangeBlockStateUIEvent>(rawEvent);
if (changeStateEvent != nullptr) {
if (changeStateEvent->getBlockState() == RequestChangeBlockStateUIEvent::Blocked) {
GenericRequest<BlockPayload>::ref blockRequest = blockListManager_->createBlockJIDRequest(changeStateEvent->getContact());
blockRequest->onResponse.connect(boost::bind(&BlockListController::handleBlockResponse, this, blockRequest, _1, _2, std::vector<JID>(1, changeStateEvent->getContact()), false));
blockRequest->send();
} else if (changeStateEvent->getBlockState() == RequestChangeBlockStateUIEvent::Unblocked) {
GenericRequest<UnblockPayload>::ref unblockRequest = blockListManager_->createUnblockJIDRequest(changeStateEvent->getContact());
@@ -142,45 +141,45 @@ void BlockListController::handleSetNewBlockList(const std::vector<JID> &newBlock
if (!jidsToBlock.empty()) {
remainingRequests_++;
GenericRequest<BlockPayload>::ref blockRequest = blockListManager_->createBlockJIDsRequest(jidsToBlock);
blockRequest->onResponse.connect(boost::bind(&BlockListController::handleBlockResponse, this, blockRequest, _1, _2, jidsToBlock, true));
blockRequest->send();
}
if (!jidsToUnblock.empty()) {
remainingRequests_++;
GenericRequest<UnblockPayload>::ref unblockRequest = blockListManager_->createUnblockJIDsRequest(jidsToUnblock);
unblockRequest->onResponse.connect(boost::bind(&BlockListController::handleUnblockResponse, this, unblockRequest, _1, _2, jidsToUnblock, true));
unblockRequest->send();
}
if (!jidsToBlock.empty() || !jidsToUnblock.empty()) {
assert(blockListEditorWidget_);
blockListEditorWidget_->setBusy(true);
blockListEditorWidget_->setError("");
} else {
blockListEditorWidget_->hide();
}
}
void BlockListController::handleBlockListChanged() {
if (blockListEditorWidget_) {
std::vector<JID> jidsToBlock;
std::vector<JID> jidsToUnblock;
blockListDifferences(blockListEditorWidget_->getCurrentBlockList(), jidsToUnblock, jidsToBlock);
blockListBeforeEdit = blockListManager_->getBlockList()->getItems();
- foreach (const JID& jid, jidsToBlock) {
+ for (const auto& jid : jidsToBlock) {
if (std::find(blockListBeforeEdit.begin(), blockListBeforeEdit.end(), jid) == blockListBeforeEdit.end()) {
blockListBeforeEdit.push_back(jid);
}
}
- foreach (const JID& jid, jidsToUnblock) {
+ for (const auto& jid : jidsToUnblock) {
blockListBeforeEdit.erase(std::remove(blockListBeforeEdit.begin(), blockListBeforeEdit.end(), jid), blockListBeforeEdit.end());
}
blockListEditorWidget_->setCurrentBlockList(blockListBeforeEdit);
}
}
}
diff --git a/Swift/Controllers/Chat/MUCController.cpp b/Swift/Controllers/Chat/MUCController.cpp
index 9ae3845..349bf8a 100644
--- a/Swift/Controllers/Chat/MUCController.cpp
+++ b/Swift/Controllers/Chat/MUCController.cpp
@@ -1,47 +1,47 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/Controllers/Chat/MUCController.h>
#include <algorithm>
#include <boost/bind.hpp>
#include <boost/regex.hpp>
#include <boost/algorithm/string.hpp>
+#include <boost/range/adaptor/reversed.hpp>
#include <Swiften/Avatars/AvatarManager.h>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Base/format.h>
#include <Swiften/Base/Tristate.h>
#include <Swiften/Client/BlockList.h>
#include <Swiften/Client/ClientBlockListManager.h>
#include <Swiften/Client/StanzaChannel.h>
#include <Swiften/Disco/EntityCapsProvider.h>
#include <Swiften/Elements/Delay.h>
#include <Swiften/Elements/Thread.h>
#include <Swiften/MUC/MUC.h>
#include <Swiften/MUC/MUCBookmark.h>
#include <Swiften/MUC/MUCBookmarkManager.h>
#include <Swiften/Network/Timer.h>
#include <Swiften/Network/TimerFactory.h>
#include <Swiften/Roster/XMPPRoster.h>
#include <SwifTools/TabComplete.h>
#include <Swift/Controllers/Chat/ChatMessageParser.h>
#include <Swift/Controllers/Highlighter.h>
#include <Swift/Controllers/Intl.h>
#include <Swift/Controllers/Roster/ContactRosterItem.h>
#include <Swift/Controllers/Roster/GroupRosterItem.h>
#include <Swift/Controllers/Roster/ItemOperations/SetAvatar.h>
#include <Swift/Controllers/Roster/ItemOperations/SetMUC.h>
#include <Swift/Controllers/Roster/ItemOperations/SetPresence.h>
#include <Swift/Controllers/Roster/Roster.h>
#include <Swift/Controllers/Roster/RosterVCardProvider.h>
#include <Swift/Controllers/UIEvents/InviteToMUCUIEvent.h>
#include <Swift/Controllers/UIEvents/RequestAddUserDialogUIEvent.h>
#include <Swift/Controllers/UIEvents/RequestChangeBlockStateUIEvent.h>
@@ -211,129 +211,128 @@ void MUCController::handleWindowOccupantSelectionChanged(ContactRosterItem* item
// Add contact is available only if the real JID is also available
if (muc_->getOccupant(item->getJID().getResource()).getRealJID()) {
actions.push_back(ChatWindow::AddContact);
}
actions.push_back(ChatWindow::ShowProfile);
}
chatWindow_->setAvailableOccupantActions(actions);
}
void MUCController::handleActionRequestedOnOccupant(ChatWindow::OccupantAction action, ContactRosterItem* item) {
JID mucJID = item->getJID();
MUCOccupant occupant = muc_->getOccupant(mucJID.getResource());
JID realJID;
if (occupant.getRealJID()) {
realJID = occupant.getRealJID().get();
}
switch (action) {
case ChatWindow::Kick: muc_->kickOccupant(mucJID);break;
case ChatWindow::Ban: muc_->changeAffiliation(realJID, MUCOccupant::Outcast);break;
case ChatWindow::MakeModerator: muc_->changeOccupantRole(mucJID, MUCOccupant::Moderator);break;
case ChatWindow::MakeParticipant: muc_->changeOccupantRole(mucJID, MUCOccupant::Participant);break;
case ChatWindow::MakeVisitor: muc_->changeOccupantRole(mucJID, MUCOccupant::Visitor);break;
case ChatWindow::AddContact: if (occupant.getRealJID()) events_->send(std::make_shared<RequestAddUserDialogUIEvent>(realJID, occupant.getNick()));break;
case ChatWindow::ShowProfile: events_->send(std::make_shared<ShowProfileForRosterItemUIEvent>(mucJID));break;
}
}
void MUCController::handleBareJIDCapsChanged(const JID& /*jid*/) {
Tristate support = Yes;
bool any = false;
- foreach (const std::string& nick, currentOccupants_) {
+ for (const auto& nick : currentOccupants_) {
DiscoInfo::ref disco = entityCapsProvider_->getCaps(toJID_.toBare().toString() + "/" + nick);
if (disco && disco->hasFeature(DiscoInfo::MessageCorrectionFeature)) {
any = true;
} else {
support = Maybe;
}
}
if (!any) {
support = No;
}
chatWindow_->setCorrectionEnabled(support);
}
/**
* Join the MUC if not already in it.
*/
void MUCController::rejoin() {
if (parting_) {
joined_ = false;
parting_ = false;
if (password_) {
muc_->setPassword(*password_);
}
//FIXME: check for received activity
#ifdef SWIFT_EXPERIMENTAL_HISTORY
if (lastActivity_ == boost::posix_time::not_a_date_time && historyController_) {
lastActivity_ = historyController_->getLastTimeStampFromMUC(selfJID_, toJID_);
}
#endif
if (lastActivity_ == boost::posix_time::not_a_date_time) {
muc_->joinAs(nick_);
}
else {
muc_->joinWithContextSince(nick_, lastActivity_);
}
}
}
bool MUCController::isJoined() {
return joined_;
}
const std::string& MUCController::getNick() {
return nick_;
}
const boost::optional<std::string> MUCController::getPassword() const {
return password_;
}
bool MUCController::isImpromptu() const {
return isImpromptu_;
}
std::map<std::string, JID> MUCController::getParticipantJIDs() const {
std::map<std::string, JID> participants;
- typedef std::pair<std::string, MUCOccupant> MUCOccupantPair;
std::map<std::string, MUCOccupant> occupants = muc_->getOccupants();
- foreach(const MUCOccupantPair& occupant, occupants) {
+ for (const auto& occupant : occupants) {
if (occupant.first != nick_) {
participants[occupant.first] = occupant.second.getRealJID().is_initialized() ? occupant.second.getRealJID().get().toBare() : JID();
}
}
return participants;
}
void MUCController::sendInvites(const std::vector<JID>& jids, const std::string& reason) const {
- foreach (const JID& jid, jids) {
+ for (const auto& jid : jids) {
muc_->invitePerson(jid, reason, isImpromptu_);
}
}
void MUCController::handleJoinTimeoutTick() {
receivedActivity();
chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(str(format(QT_TRANSLATE_NOOP("", "Room %1% is not responding. This operation may never complete.")) % toJID_.toString())), ChatWindow::DefaultDirection);
}
void MUCController::receivedActivity() {
if (loginCheckTimer_) {
loginCheckTimer_->stop();
}
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wswitch-enum"
void MUCController::handleJoinFailed(std::shared_ptr<ErrorPayload> error) {
receivedActivity();
std::string errorMessage = QT_TRANSLATE_NOOP("", "Unable to enter this room");
std::string rejoinNick;
if (error) {
switch (error->getCondition()) {
case ErrorPayload::Conflict:
rejoinNick = nick_ + "_";
errorMessage = str(format(QT_TRANSLATE_NOOP("", "Unable to enter this room as %1%, retrying as %2%")) % nick_ % rejoinNick);
break;
case ErrorPayload::JIDMalformed:
errorMessage += ": ";
@@ -832,61 +831,61 @@ void MUCController::appendToJoinParts(std::vector<NickJoinPart>& joinParts, cons
case JoinThenPart: break;
}
(*it).type = type;
break;
}
}
if (!matched) {
joinParts.push_back(newEvent);
}
}
std::string MUCController::concatenateListOfNames(const std::vector<NickJoinPart>& joinParts) {
std::string result;
for (size_t i = 0; i < joinParts.size(); i++) {
if (i > 0) {
if (i < joinParts.size() - 1) {
result += ", ";
} else {
result += QT_TRANSLATE_NOOP("", " and ");
}
}
NickJoinPart event = joinParts[i];
result += event.nick;
}
return result;
}
std::string MUCController::generateJoinPartString(const std::vector<NickJoinPart>& joinParts, bool isImpromptu) {
std::vector<NickJoinPart> sorted[4];
std::string eventStrings[4];
- foreach (NickJoinPart event, joinParts) {
+ for (const auto& event : joinParts) {
sorted[event.type].push_back(event);
}
std::string result;
std::vector<JoinPart> populatedEvents;
for (size_t i = 0; i < 4; i++) {
std::string names = concatenateListOfNames(sorted[i]);
if (!names.empty()) {
std::string eventString;
switch (i) {
case Join:
if (sorted[i].size() > 1) {
eventString = (isImpromptu ? QT_TRANSLATE_NOOP("", "%1% have joined the chat") : QT_TRANSLATE_NOOP("", "%1% have entered the room"));
}
else {
eventString = (isImpromptu ? QT_TRANSLATE_NOOP("", "%1% has joined the chat") : QT_TRANSLATE_NOOP("", "%1% has entered the room"));
}
break;
case Part:
if (sorted[i].size() > 1) {
eventString = (isImpromptu ? QT_TRANSLATE_NOOP("", "%1% have left the chat") : QT_TRANSLATE_NOOP("", "%1% have left the room"));
}
else {
eventString = (isImpromptu ? QT_TRANSLATE_NOOP("", "%1% have left the chat") : QT_TRANSLATE_NOOP("", "%1% has left the room"));
}
break;
case JoinThenPart:
if (sorted[i].size() > 1) {
eventString = (isImpromptu ? QT_TRANSLATE_NOOP("", "%1% have joined then left the chat") : QT_TRANSLATE_NOOP("", "%1% have entered then left the room"));
}
else {
@@ -910,61 +909,61 @@ std::string MUCController::generateJoinPartString(const std::vector<NickJoinPart
if (i > 0) {
if (i < populatedEvents.size() - 1) {
result += ", ";
} else {
result += QT_TRANSLATE_NOOP("", " and ");
}
}
result += eventStrings[populatedEvents[i]];
}
return result;
}
std::string MUCController::generateNicknameChangeString(const std::string& oldNickname, const std::string& newNickname) {
return str(boost::format(QT_TRANSLATE_NOOP("", "%1% is now known as %2%.")) % oldNickname % newNickname);
}
void MUCController::handleChangeSubjectRequest(const std::string& subject) {
muc_->changeSubject(subject);
}
void MUCController::handleBookmarkRequest() {
const JID jid = muc_->getJID();
// Prepare new bookmark for this room.
MUCBookmark roomBookmark(jid, jid.toBare().toString());
roomBookmark.setPassword(password_);
roomBookmark.setNick(nick_);
// Check for existing bookmark for this room and, if it exists, use it instead.
std::vector<MUCBookmark> bookmarks = mucBookmarkManager_->getBookmarks();
- foreach (const MUCBookmark& bookmark, bookmarks) {
+ for (const auto& bookmark : bookmarks) {
if (bookmark.getRoom() == jid.toBare()) {
roomBookmark = bookmark;
break;
}
}
chatWindow_->showBookmarkWindow(roomBookmark);
}
void MUCController::handleConfigureRequest(Form::ref form) {
if (form) {
muc_->configureRoom(form);
}
else {
muc_->requestConfigurationForm();
}
}
void MUCController::handleConfigurationFailed(ErrorPayload::ref error) {
std::string errorMessage = getErrorMessage(error);
errorMessage = str(format(QT_TRANSLATE_NOOP("", "Room configuration failed: %1%.")) % errorMessage);
chatWindow_->addErrorMessage(chatMessageParser_->parseMessageBody(errorMessage));
}
void MUCController::handleOccupantRoleChangeFailed(ErrorPayload::ref error, const JID&, MUCOccupant::Role) {
std::string errorMessage = getErrorMessage(error);
errorMessage = str(format(QT_TRANSLATE_NOOP("", "Occupant role change failed: %1%.")) % errorMessage);
chatWindow_->addErrorMessage(chatMessageParser_->parseMessageBody(errorMessage));
}
@@ -974,216 +973,213 @@ void MUCController::configureAsImpromptuRoom(Form::ref form) {
onImpromptuConfigCompleted();
}
void MUCController::handleConfigurationFormReceived(Form::ref form) {
if (isImpromptu_) {
if (!isImpromptuAlreadyConfigured_) {
configureAsImpromptuRoom(form);
}
} else {
chatWindow_->showRoomConfigurationForm(form);
}
}
void MUCController::handleConfigurationCancelled() {
muc_->cancelConfigureRoom();
}
void MUCController::handleDestroyRoomRequest() {
muc_->destroyRoom();
}
void MUCController::handleInvitePersonToThisMUCRequest(const std::vector<JID>& jidsToInvite) {
RequestInviteToMUCUIEvent::ImpromptuMode mode = isImpromptu_ ? RequestInviteToMUCUIEvent::Impromptu : RequestInviteToMUCUIEvent::NotImpromptu;
std::shared_ptr<UIEvent> event(new RequestInviteToMUCUIEvent(muc_->getJID(), jidsToInvite, mode));
eventStream_->send(event);
}
void MUCController::handleUIEvent(std::shared_ptr<UIEvent> event) {
std::shared_ptr<InviteToMUCUIEvent> inviteEvent = std::dynamic_pointer_cast<InviteToMUCUIEvent>(event);
if (inviteEvent && inviteEvent->getRoom() == muc_->getJID()) {
- foreach (const JID& jid, inviteEvent->getInvites()) {
+ for (const auto& jid : inviteEvent->getInvites()) {
muc_->invitePerson(jid, inviteEvent->getReason(), isImpromptu_);
}
}
}
void MUCController::handleGetAffiliationsRequest() {
muc_->requestAffiliationList(MUCOccupant::Owner);
muc_->requestAffiliationList(MUCOccupant::Admin);
muc_->requestAffiliationList(MUCOccupant::Member);
muc_->requestAffiliationList(MUCOccupant::Outcast);
}
-typedef std::pair<MUCOccupant::Affiliation, JID> AffiliationChangePair;
-
void MUCController::handleChangeAffiliationsRequest(const std::vector<std::pair<MUCOccupant::Affiliation, JID> >& changes) {
std::set<JID> addedJIDs;
- foreach (const AffiliationChangePair& change, changes) {
+ for (const auto& change : changes) {
if (change.first != MUCOccupant::NoAffiliation) {
addedJIDs.insert(change.second);
}
}
- foreach (const AffiliationChangePair& change, changes) {
+ for (const auto& change : changes) {
if (change.first != MUCOccupant::NoAffiliation || addedJIDs.find(change.second) == addedJIDs.end()) {
muc_->changeAffiliation(change.second, change.first);
}
}
}
void MUCController::handleUnblockUserRequest() {
eventStream_->send(std::make_shared<RequestChangeBlockStateUIEvent>(RequestChangeBlockStateUIEvent::Unblocked, muc_->getJID()));
}
void MUCController::handleBlockingStateChanged() {
std::shared_ptr<BlockList> blockList = clientBlockListManager_->getBlockList();
if (blockList->getState() == BlockList::Available) {
if (blockList->isBlocked(toJID_)) {
if (!blockedContactAlert_) {
blockedContactAlert_ = chatWindow_->addAlert(QT_TRANSLATE_NOOP("", "You've blocked this room. To enter the room, first unblock it using the cog menu and try again"));
}
chatWindow_->setBlockingState(ChatWindow::IsBlocked);
} else {
if (blockedContactAlert_) {
chatWindow_->removeAlert(*blockedContactAlert_);
blockedContactAlert_.reset();
}
chatWindow_->setBlockingState(ChatWindow::IsUnblocked);
}
}
}
void MUCController::handleAffiliationListReceived(MUCOccupant::Affiliation affiliation, const std::vector<JID>& jids) {
chatWindow_->setAffiliations(affiliation, jids);
}
void MUCController::logMessage(const std::string& message, const JID& fromJID, const JID& toJID, const boost::posix_time::ptime& timeStamp, bool isIncoming) {
// log only incoming messages
if (isIncoming && historyController_) {
historyController_->addMessage(message, fromJID, toJID, HistoryMessage::Groupchat, timeStamp);
}
}
void MUCController::addRecentLogs() {
if (!historyController_) {
return;
}
joinContext_ = historyController_->getMUCContext(selfJID_, toJID_, lastActivity_);
- foreach (const HistoryMessage& message, joinContext_) {
+ for (const auto& message : joinContext_) {
bool senderIsSelf = nick_ == message.getFromJID().getResource();
// the chatWindow uses utc timestamps
addMessage(chatMessageParser_->parseMessageBody(message.getMessage()), senderDisplayNameFromMessage(message.getFromJID()), senderIsSelf, std::make_shared<SecurityLabel>(), avatarManager_->getAvatarPath(message.getFromJID()), message.getTime() - boost::posix_time::hours(message.getOffset()));
}
}
void MUCController::checkDuplicates(std::shared_ptr<Message> newMessage) {
std::string body = newMessage->getBody().get_value_or("");
JID jid = newMessage->getFrom();
boost::optional<boost::posix_time::ptime> time = newMessage->getTimestamp();
- reverse_foreach (const HistoryMessage& message, joinContext_) {
+ for (const auto& message : boost::adaptors::reverse(joinContext_)) {
boost::posix_time::ptime messageTime = message.getTime() - boost::posix_time::hours(message.getOffset());
if (time && time < messageTime) {
break;
}
if (time && time != messageTime) {
continue;
}
if (message.getFromJID() != jid) {
continue;
}
if (message.getMessage() != body) {
continue;
}
// Mark the message as unreadable
newMessage->setBody("");
}
}
void MUCController::setNick(const std::string& nick) {
nick_ = nick;
highlighter_->setNick(nick_);
}
Form::ref MUCController::buildImpromptuRoomConfiguration(Form::ref roomConfigurationForm) {
Form::ref result = std::make_shared<Form>(Form::SubmitType);
std::string impromptuConfigs[] = { "muc#roomconfig_enablelogging", "muc#roomconfig_persistentroom", "muc#roomconfig_publicroom", "muc#roomconfig_whois"};
std::set<std::string> impromptuConfigsMissing(impromptuConfigs, impromptuConfigs + 4);
- foreach (std::shared_ptr<FormField> field, roomConfigurationForm->getFields()) {
+ for (const auto& field : roomConfigurationForm->getFields()) {
std::shared_ptr<FormField> resultField;
if (field->getName() == "muc#roomconfig_enablelogging") {
resultField = std::make_shared<FormField>(FormField::BooleanType, "0");
}
if (field->getName() == "muc#roomconfig_persistentroom") {
resultField = std::make_shared<FormField>(FormField::BooleanType, "0");
}
if (field->getName() == "muc#roomconfig_publicroom") {
resultField = std::make_shared<FormField>(FormField::BooleanType, "0");
}
if (field->getName() == "muc#roomconfig_whois") {
resultField = std::make_shared<FormField>(FormField::ListSingleType, "anyone");
}
if (field->getName() == "FORM_TYPE") {
resultField = std::make_shared<FormField>(FormField::HiddenType, "http://jabber.org/protocol/muc#roomconfig");
}
if (resultField) {
impromptuConfigsMissing.erase(field->getName());
resultField->setName(field->getName());
result->addField(resultField);
}
}
- foreach (const std::string& config, impromptuConfigsMissing) {
+ for (const auto& config : impromptuConfigsMissing) {
if (config == "muc#roomconfig_publicroom") {
chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(QT_TRANSLATE_NOOP("", "This server doesn't support hiding your chat from other users.")), ChatWindow::DefaultDirection);
} else if (config == "muc#roomconfig_whois") {
chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(QT_TRANSLATE_NOOP("", "This server doesn't support sharing people's real identity in this chat.")), ChatWindow::DefaultDirection);
}
}
return result;
}
void MUCController::setImpromptuWindowTitle() {
std::string title;
- typedef std::pair<std::string, MUCOccupant> StringMUCOccupantPair;
std::map<std::string, MUCOccupant> occupants = muc_->getOccupants();
if (occupants.size() <= 1) {
title = QT_TRANSLATE_NOOP("", "Empty Chat");
} else {
- foreach (StringMUCOccupantPair pair, occupants) {
+ for (const auto& pair : occupants) {
if (pair.first != nick_) {
title += (title.empty() ? "" : ", ") + pair.first;
}
}
}
chatWindow_->setName(title);
}
void MUCController::handleRoomUnlocked() {
// Handle buggy MUC implementations where the joined room already exists and is unlocked.
// Configure the room again in this case.
if (!isImpromptuAlreadyConfigured_) {
if (isImpromptu_ && (muc_->getOccupant(nick_).getAffiliation() == MUCOccupant::Owner)) {
muc_->requestConfigurationForm();
} else if (isImpromptu_) {
onImpromptuConfigCompleted();
}
}
}
void MUCController::setAvailableServerFeatures(std::shared_ptr<DiscoInfo> info) {
ChatControllerBase::setAvailableServerFeatures(info);
if (iqRouter_->isAvailable() && info->hasFeature(DiscoInfo::BlockingCommandFeature)) {
std::shared_ptr<BlockList> blockList = clientBlockListManager_->getBlockList();
blockingOnStateChangedConnection_ = blockList->onStateChanged.connect(boost::bind(&MUCController::handleBlockingStateChanged, this));
blockingOnItemAddedConnection_ = blockList->onItemAdded.connect(boost::bind(&MUCController::handleBlockingStateChanged, this));
blockingOnItemRemovedConnection_ = blockList->onItemRemoved.connect(boost::bind(&MUCController::handleBlockingStateChanged, this));
handleBlockingStateChanged();
diff --git a/Swift/Controllers/Chat/UnitTest/ChatsManagerTest.cpp b/Swift/Controllers/Chat/UnitTest/ChatsManagerTest.cpp
index 31c9be9..a5e68cf 100644
--- a/Swift/Controllers/Chat/UnitTest/ChatsManagerTest.cpp
+++ b/Swift/Controllers/Chat/UnitTest/ChatsManagerTest.cpp
@@ -62,61 +62,61 @@
#include <Swift/Controllers/UnitTest/MockChatWindow.h>
#include <Swift/Controllers/WhiteboardManager.h>
#include <Swift/Controllers/XMPPEvents/EventController.h>
using namespace Swift;
class ChatsManagerTest : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE(ChatsManagerTest);
CPPUNIT_TEST(testFirstOpenWindowIncoming);
CPPUNIT_TEST(testSecondOpenWindowIncoming);
CPPUNIT_TEST(testFirstOpenWindowOutgoing);
CPPUNIT_TEST(testFirstOpenWindowBareToFull);
CPPUNIT_TEST(testSecondWindow);
CPPUNIT_TEST(testUnbindRebind);
CPPUNIT_TEST(testNoDuplicateUnbind);
CPPUNIT_TEST(testThreeMUCWindows);
CPPUNIT_TEST(testChatControllerPresenceAccessUpdatedOnRemoveFromRoster);
CPPUNIT_TEST(testChatControllerPresenceAccessUpdatedOnAddToRoster);
CPPUNIT_TEST(testChatControllerPresenceAccessUpdatedOnSubscriptionChangeToBoth);
CPPUNIT_TEST(testChatControllerPresenceAccessUpdatedOnSubscriptionChangeToFrom);
CPPUNIT_TEST(testChatControllerFullJIDBindingOnMessageAndNotReceipt);
CPPUNIT_TEST(testChatControllerFullJIDBindingOnTypingAndNotActive);
CPPUNIT_TEST(testChatControllerPMPresenceHandling);
CPPUNIT_TEST(testLocalMUCServiceDiscoveryResetOnDisconnect);
CPPUNIT_TEST(testPresenceChangeDoesNotReplaceMUCInvite);
// Highlighting tests
CPPUNIT_TEST(testChatControllerHighlightingNotificationTesting);
CPPUNIT_TEST(testChatControllerHighlightingNotificationDeduplicateSounds);
CPPUNIT_TEST(testChatControllerMeMessageHandling);
- CPPUNIT_TEST(testRestartingMUCComponentCrash);
+ CPPUNIT_TEST(testRestartingMUCComponentCrash);
CPPUNIT_TEST(testChatControllerMeMessageHandlingInMUC);
// Carbons tests
CPPUNIT_TEST(testCarbonsForwardedIncomingMessageToSecondResource);
CPPUNIT_TEST(testCarbonsForwardedOutgoingMessageFromSecondResource);
CPPUNIT_TEST_SUITE_END();
public:
void setUp() {
mocks_ = new MockRepository();
jid_ = JID("test@test.com/resource");
stanzaChannel_ = new DummyStanzaChannel();
iqRouter_ = new IQRouter(stanzaChannel_);
eventController_ = new EventController();
chatWindowFactory_ = mocks_->InterfaceMock<ChatWindowFactory>();
joinMUCWindowFactory_ = mocks_->InterfaceMock<JoinMUCWindowFactory>();
xmppRoster_ = new XMPPRosterImpl();
mucRegistry_ = new MUCRegistry();
nickResolver_ = new NickResolver(jid_.toBare(), xmppRoster_, nullptr, mucRegistry_);
presenceOracle_ = new PresenceOracle(stanzaChannel_, xmppRoster_);
serverDiscoInfo_ = std::make_shared<DiscoInfo>();
presenceSender_ = new StanzaChannelPresenceSender(stanzaChannel_);
directedPresenceSender_ = new DirectedPresenceSender(presenceSender_);
mucManager_ = new MUCManager(stanzaChannel_, iqRouter_, directedPresenceSender_, mucRegistry_);
uiEventStream_ = new UIEventStream();
entityCapsProvider_ = new DummyEntityCapsProvider();
chatListWindowFactory_ = mocks_->InterfaceMock<ChatListWindowFactory>();
mucSearchWindowFactory_ = mocks_->InterfaceMock<MUCSearchWindowFactory>();
settings_ = new DummySettingsProvider();
@@ -428,103 +428,103 @@ public:
/**
* Test that ChatController sends receipts if requested after change from subscription state To to subscription state Both.
*/
void testChatControllerPresenceAccessUpdatedOnSubscriptionChangeToBoth() {
testhelperChatControllerPresenceAccessUpdatedOnSubscriptionChangeReceiptsAllowed(RosterItemPayload::To, RosterItemPayload::Both);
}
/**
* Test that ChatController sends receipts if requested after change from subscription state To to subscription state From.
*/
void testChatControllerPresenceAccessUpdatedOnSubscriptionChangeToFrom() {
testhelperChatControllerPresenceAccessUpdatedOnSubscriptionChangeReceiptsAllowed(RosterItemPayload::To, RosterItemPayload::From);
}
void testChatControllerFullJIDBindingOnMessageAndNotReceipt() {
JID ownJID("test@test.com/resource");
JID sender("foo@test.com");
std::vector<JID> senderResource;
senderResource.push_back(sender.withResource("resourceA"));
senderResource.push_back(sender.withResource("resourceB"));
// We support delivery receipts.
settings_->storeSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS, true);
// Open chat window to a sender.
MockChatWindow* window = new MockChatWindow();
mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(sender, uiEventStream_).Return(window);
uiEventStream_->send(std::make_shared<RequestChatUIEvent>(sender));
- foreach(const JID& senderJID, senderResource) {
+ for (const auto& senderJID : senderResource) {
// The sender supports delivery receipts.
DiscoInfo::ref disco = std::make_shared<DiscoInfo>();
disco->addFeature(DiscoInfo::MessageDeliveryReceiptsFeature);
entityCapsProvider_->caps[senderJID] = disco;
// The sender is online.
Presence::ref senderPresence = std::make_shared<Presence>();
senderPresence->setFrom(senderJID);
senderPresence->setTo(ownJID);
stanzaChannel_->onPresenceReceived(senderPresence);
entityCapsProvider_->onCapsChanged(senderJID);
}
// Send first message.
window->onSendMessageRequest("hello there", false);
// A bare message is send because no resources is bound.
CPPUNIT_ASSERT_EQUAL(sender, stanzaChannel_->getStanzaAtIndex<Message>(1)->getTo());
CPPUNIT_ASSERT(stanzaChannel_->getStanzaAtIndex<Message>(1)->getPayload<DeliveryReceiptRequest>());
// Two resources respond with message receipts.
- foreach(const JID& senderJID, senderResource) {
+ for (const auto& senderJID : senderResource) {
Message::ref receiptReply = std::make_shared<Message>();
receiptReply->setFrom(senderJID);
receiptReply->setTo(ownJID);
std::shared_ptr<DeliveryReceipt> receipt = std::make_shared<DeliveryReceipt>();
receipt->setReceivedID(stanzaChannel_->getStanzaAtIndex<Message>(1)->getID());
receiptReply->addPayload(receipt);
manager_->handleIncomingMessage(receiptReply);
}
// Send second message.
window->onSendMessageRequest("how are you?", false);
// A bare message is send because no resources is bound.
CPPUNIT_ASSERT_EQUAL(sender, stanzaChannel_->getStanzaAtIndex<Message>(1)->getTo());
CPPUNIT_ASSERT(stanzaChannel_->getStanzaAtIndex<Message>(1)->getPayload<DeliveryReceiptRequest>());
// Two resources respond with message receipts.
- foreach(const JID& senderJID, senderResource) {
+ for (const auto& senderJID : senderResource) {
Message::ref receiptReply = std::make_shared<Message>();
receiptReply->setFrom(senderJID);
receiptReply->setTo(ownJID);
std::shared_ptr<DeliveryReceipt> receipt = std::make_shared<DeliveryReceipt>();
receipt->setReceivedID(stanzaChannel_->getStanzaAtIndex<Message>(1)->getID());
receiptReply->addPayload(receipt);
manager_->handleIncomingMessage(receiptReply);
}
// Reply with a message including a body text.
Message::ref reply = std::make_shared<Message>();
reply->setFrom(senderResource[0]);
reply->setTo(ownJID);
reply->setBody("fine.");
manager_->handleIncomingMessage(reply);
// Send third message.
window->onSendMessageRequest("great to hear.", false);
// The chat session is bound to the full JID of the first resource.
CPPUNIT_ASSERT_EQUAL(senderResource[0], stanzaChannel_->getStanzaAtIndex<Message>(3)->getTo());
CPPUNIT_ASSERT(stanzaChannel_->getStanzaAtIndex<Message>(2)->getPayload<DeliveryReceiptRequest>());
// Receive random receipt from second sender resource.
reply = std::make_shared<Message>();
reply->setFrom(senderResource[1]);
reply->setTo(ownJID);
std::shared_ptr<DeliveryReceipt> receipt = std::make_shared<DeliveryReceipt>();
@@ -543,103 +543,103 @@ public:
reply = std::make_shared<Message>();
reply->setFrom(senderResource[1]);
reply->setTo(ownJID);
reply->setBody("nothing.");
manager_->handleIncomingMessage(reply);
// Send fifth message.
window->onSendMessageRequest("okay", false);
// The chat session is now bound to the full JID of the second resource.
CPPUNIT_ASSERT_EQUAL(senderResource[1], stanzaChannel_->getStanzaAtIndex<Message>(5)->getTo());
CPPUNIT_ASSERT(stanzaChannel_->getStanzaAtIndex<Message>(5)->getPayload<DeliveryReceiptRequest>());
}
void testChatControllerFullJIDBindingOnTypingAndNotActive() {
JID ownJID("test@test.com/resource");
JID sender("foo@test.com");
std::vector<JID> senderResource;
senderResource.push_back(sender.withResource("resourceA"));
senderResource.push_back(sender.withResource("resourceB"));
// We support delivery receipts.
settings_->storeSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS, true);
// Open chat window to a sender.
MockChatWindow* window = new MockChatWindow();
mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(sender, uiEventStream_).Return(window);
uiEventStream_->send(std::make_shared<RequestChatUIEvent>(sender));
- foreach(const JID& senderJID, senderResource) {
+ for (const auto& senderJID : senderResource) {
// The sender supports delivery receipts.
DiscoInfo::ref disco = std::make_shared<DiscoInfo>();
disco->addFeature(DiscoInfo::MessageDeliveryReceiptsFeature);
entityCapsProvider_->caps[senderJID] = disco;
// The sender is online.
Presence::ref senderPresence = std::make_shared<Presence>();
senderPresence->setFrom(senderJID);
senderPresence->setTo(ownJID);
stanzaChannel_->onPresenceReceived(senderPresence);
entityCapsProvider_->onCapsChanged(senderJID);
}
// Send first message.
window->onSendMessageRequest("hello there", false);
// A bare message is send because no resources is bound.
CPPUNIT_ASSERT_EQUAL(sender, stanzaChannel_->getStanzaAtIndex<Message>(1)->getTo());
CPPUNIT_ASSERT(stanzaChannel_->getStanzaAtIndex<Message>(1)->getPayload<DeliveryReceiptRequest>());
// Two resources respond with message receipts.
- foreach(const JID& senderJID, senderResource) {
+ for (const auto& senderJID : senderResource) {
Message::ref reply = std::make_shared<Message>();
reply->setFrom(senderJID);
reply->setTo(ownJID);
std::shared_ptr<ChatState> csn = std::make_shared<ChatState>();
csn->setChatState(ChatState::Active);
reply->addPayload(csn);
manager_->handleIncomingMessage(reply);
}
// Send second message.
window->onSendMessageRequest("how are you?", false);
// A bare message is send because no resources is bound.
CPPUNIT_ASSERT_EQUAL(sender, stanzaChannel_->getStanzaAtIndex<Message>(1)->getTo());
CPPUNIT_ASSERT(stanzaChannel_->getStanzaAtIndex<Message>(1)->getPayload<DeliveryReceiptRequest>());
// Two resources respond with message receipts.
- foreach(const JID& senderJID, senderResource) {
+ for (const auto& senderJID : senderResource) {
Message::ref receiptReply = std::make_shared<Message>();
receiptReply->setFrom(senderJID);
receiptReply->setTo(ownJID);
std::shared_ptr<DeliveryReceipt> receipt = std::make_shared<DeliveryReceipt>();
receipt->setReceivedID(stanzaChannel_->getStanzaAtIndex<Message>(1)->getID());
receiptReply->addPayload(receipt);
manager_->handleIncomingMessage(receiptReply);
}
// Reply with a message including a CSN.
Message::ref reply = std::make_shared<Message>();
reply->setFrom(senderResource[0]);
reply->setTo(ownJID);
std::shared_ptr<ChatState> csn = std::make_shared<ChatState>();
csn->setChatState(ChatState::Composing);
reply->addPayload(csn);
manager_->handleIncomingMessage(reply);
// Send third message.
window->onSendMessageRequest("great to hear.", false);
// The chat session is now bound to the full JID of the first resource due to its recent composing message.
CPPUNIT_ASSERT_EQUAL(senderResource[0], stanzaChannel_->getStanzaAtIndex<Message>(3)->getTo());
CPPUNIT_ASSERT(stanzaChannel_->getStanzaAtIndex<Message>(3)->getPayload<DeliveryReceiptRequest>());
// Reply with a message including a CSN from the other resource.
reply = std::make_shared<Message>();
reply->setFrom(senderResource[1]);
diff --git a/Swift/Controllers/Chat/UnitTest/MUCControllerTest.cpp b/Swift/Controllers/Chat/UnitTest/MUCControllerTest.cpp
index 1142c98..32639f6 100644
--- a/Swift/Controllers/Chat/UnitTest/MUCControllerTest.cpp
+++ b/Swift/Controllers/Chat/UnitTest/MUCControllerTest.cpp
@@ -1,44 +1,43 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <boost/algorithm/string.hpp>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <hippomocks.h>
#include <Swiften/Avatars/NullAvatarManager.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Client/ClientBlockListManager.h>
#include <Swiften/Client/DummyStanzaChannel.h>
#include <Swiften/Client/NickResolver.h>
#include <Swiften/Crypto/CryptoProvider.h>
#include <Swiften/Crypto/PlatformCryptoProvider.h>
#include <Swiften/Disco/DummyEntityCapsProvider.h>
#include <Swiften/Elements/MUCUserPayload.h>
#include <Swiften/Elements/Thread.h>
#include <Swiften/MUC/MUCBookmarkManager.h>
#include <Swiften/MUC/UnitTest/MockMUC.h>
#include <Swiften/Network/TimerFactory.h>
#include <Swiften/Presence/DirectedPresenceSender.h>
#include <Swiften/Presence/PresenceOracle.h>
#include <Swiften/Presence/StanzaChannelPresenceSender.h>
#include <Swiften/Queries/DummyIQChannel.h>
#include <Swiften/Roster/XMPPRoster.h>
#include <Swiften/Roster/XMPPRosterImpl.h>
#include <Swiften/VCards/VCardManager.h>
#include <Swiften/VCards/VCardMemoryStorage.h>
#include <Swift/Controllers/Chat/ChatMessageParser.h>
#include <Swift/Controllers/Chat/MUCController.h>
#include <Swift/Controllers/Chat/UserSearchController.h>
#include <Swift/Controllers/Roster/GroupRosterItem.h>
#include <Swift/Controllers/Roster/Roster.h>
#include <Swift/Controllers/Settings/DummySettingsProvider.h>
#include <Swift/Controllers/UIEvents/UIEventStream.h>
#include <Swift/Controllers/UIInterfaces/ChatWindow.h>
#include <Swift/Controllers/UIInterfaces/ChatWindowFactory.h>
#include <Swift/Controllers/UIInterfaces/UserSearchWindowFactory.h>
@@ -344,77 +343,76 @@ public:
list.push_back(NickJoinPart("Ernie", Join));
CPPUNIT_ASSERT_EQUAL(std::string("Kev, Bert and Ernie have entered the room and Remko has left the room"), MUCController::generateJoinPartString(list, false));
}
void testJoinPartStringContructionMixed() {
std::vector<NickJoinPart> list;
list.push_back(NickJoinPart("Kev", JoinThenPart));
CPPUNIT_ASSERT_EQUAL(std::string("Kev has entered then left the room"), MUCController::generateJoinPartString(list, false));
list.push_back(NickJoinPart("Remko", Part));
CPPUNIT_ASSERT_EQUAL(std::string("Remko has left the room and Kev has entered then left the room"), MUCController::generateJoinPartString(list, false));
list.push_back(NickJoinPart("Bert", PartThenJoin));
CPPUNIT_ASSERT_EQUAL(std::string("Remko has left the room, Kev has entered then left the room and Bert has left then returned to the room"), MUCController::generateJoinPartString(list, false));
list.push_back(NickJoinPart("Ernie", JoinThenPart));
CPPUNIT_ASSERT_EQUAL(std::string("Remko has left the room, Kev and Ernie have entered then left the room and Bert has left then returned to the room"), MUCController::generateJoinPartString(list, false));
}
JID jidFromOccupant(const MUCOccupant& occupant) {
return JID(mucJID_.toString()+"/"+occupant.getNick());
}
void testRoleAffiliationStates() {
typedef std::map<std::string, MUCOccupant> occupant_map;
occupant_map occupants;
occupants.insert(occupant_map::value_type("Kev", MUCOccupant("Kev", MUCOccupant::Participant, MUCOccupant::Owner)));
occupants.insert(occupant_map::value_type("Remko", MUCOccupant("Remko", MUCOccupant::Participant, MUCOccupant::Owner)));
occupants.insert(occupant_map::value_type("Bert", MUCOccupant("Bert", MUCOccupant::Participant, MUCOccupant::Owner)));
occupants.insert(occupant_map::value_type("Ernie", MUCOccupant("Ernie", MUCOccupant::Participant, MUCOccupant::Owner)));
/* populate the MUC with fake users */
- typedef const std::pair<std::string,MUCOccupant> occupantIterator;
- foreach(occupantIterator &occupant, occupants) {
+ for (auto&& occupant : occupants) {
muc_->insertOccupant(occupant.second);
}
std::vector<MUCOccupant> alterations;
alterations.push_back(MUCOccupant("Kev", MUCOccupant::Visitor, MUCOccupant::Admin));
alterations.push_back(MUCOccupant("Remko", MUCOccupant::Moderator, MUCOccupant::Member));
alterations.push_back(MUCOccupant("Bert", MUCOccupant::Visitor, MUCOccupant::Outcast));
alterations.push_back(MUCOccupant("Ernie", MUCOccupant::NoRole, MUCOccupant::Member));
alterations.push_back(MUCOccupant("Bert", MUCOccupant::Moderator, MUCOccupant::Owner));
alterations.push_back(MUCOccupant("Kev", MUCOccupant::Participant, MUCOccupant::Outcast));
alterations.push_back(MUCOccupant("Bert", MUCOccupant::Visitor, MUCOccupant::NoAffiliation));
alterations.push_back(MUCOccupant("Remko", MUCOccupant::NoRole, MUCOccupant::NoAffiliation));
alterations.push_back(MUCOccupant("Ernie", MUCOccupant::Visitor, MUCOccupant::Outcast));
- foreach(const MUCOccupant& alteration, alterations) {
+ for (const auto& alteration : alterations) {
/* perform an alteration to a user's role and affiliation */
occupant_map::iterator occupant = occupants.find(alteration.getNick());
CPPUNIT_ASSERT(occupant != occupants.end());
const JID jid = jidFromOccupant(occupant->second);
/* change the affiliation, leave the role in place */
muc_->changeAffiliation(jid, alteration.getAffiliation());
occupant->second = MUCOccupant(occupant->first, occupant->second.getRole(), alteration.getAffiliation());
testRoleAffiliationStatesVerify(occupants);
/* change the role, leave the affiliation in place */
muc_->changeOccupantRole(jid, alteration.getRole());
occupant->second = MUCOccupant(occupant->first, alteration.getRole(), occupant->second.getAffiliation());
testRoleAffiliationStatesVerify(occupants);
}
}
void testSubjectChangeCorrect() {
std::string messageBody("test message");
window_->onSendMessageRequest(messageBody, false);
std::shared_ptr<Stanza> rawStanza = stanzaChannel_->sentStanzas[stanzaChannel_->sentStanzas.size() - 1];
Message::ref message = std::dynamic_pointer_cast<Message>(rawStanza);
CPPUNIT_ASSERT(stanzaChannel_->isAvailable()); /* Otherwise will prevent sends. */
CPPUNIT_ASSERT(message);
CPPUNIT_ASSERT_EQUAL(messageBody, message->getBody().get_value_or(""));
{
Message::ref message = std::make_shared<Message>();
message->setType(Message::Groupchat);
message->setTo(self_);
message->setFrom(mucJID_.withResource("SomeNickname"));
message->setID(iqChannel_->getNewIQID());
@@ -479,64 +477,64 @@ public:
/*
* Test that message stanzas with subject element and empty body element do not cause a subject change.
*/
void testSubjectChangeIncorrectC() {
std::string messageBody("test message");
window_->onSendMessageRequest(messageBody, false);
std::shared_ptr<Stanza> rawStanza = stanzaChannel_->sentStanzas[stanzaChannel_->sentStanzas.size() - 1];
Message::ref message = std::dynamic_pointer_cast<Message>(rawStanza);
CPPUNIT_ASSERT(stanzaChannel_->isAvailable()); /* Otherwise will prevent sends. */
CPPUNIT_ASSERT(message);
CPPUNIT_ASSERT_EQUAL(messageBody, message->getBody().get_value_or(""));
{
Message::ref message = std::make_shared<Message>();
message->setType(Message::Groupchat);
message->setTo(self_);
message->setFrom(mucJID_.withResource("SomeNickname"));
message->setID(iqChannel_->getNewIQID());
message->setSubject("New Room Subject");
message->setBody("");
controller_->handleIncomingMessage(std::make_shared<MessageEvent>(message));
CPPUNIT_ASSERT_EQUAL(std::string("Trying to enter room teaparty@rooms.wonderland.lit"), std::dynamic_pointer_cast<ChatWindow::ChatTextMessagePart>(window_->lastAddedSystemMessage_.getParts()[0])->text);
}
}
void testRoleAffiliationStatesVerify(const std::map<std::string, MUCOccupant> &occupants) {
/* verify that the roster is in sync */
GroupRosterItem* group = window_->getRosterModel()->getRoot();
- foreach(RosterItem* rosterItem, group->getChildren()) {
+ for (auto rosterItem : group->getChildren()) {
GroupRosterItem* child = dynamic_cast<GroupRosterItem*>(rosterItem);
CPPUNIT_ASSERT(child);
- foreach(RosterItem* childItem, child->getChildren()) {
+ for (auto childItem : child->getChildren()) {
ContactRosterItem* item = dynamic_cast<ContactRosterItem*>(childItem);
CPPUNIT_ASSERT(item);
std::map<std::string, MUCOccupant>::const_iterator occupant = occupants.find(item->getJID().getResource());
CPPUNIT_ASSERT(occupant != occupants.end());
CPPUNIT_ASSERT(item->getMUCRole() == occupant->second.getRole());
CPPUNIT_ASSERT(item->getMUCAffiliation() == occupant->second.getAffiliation());
}
}
}
private:
JID self_;
JID mucJID_;
MockMUC::ref muc_;
std::string nick_;
DummyStanzaChannel* stanzaChannel_;
DummyIQChannel* iqChannel_;
IQRouter* iqRouter_;
EventController* eventController_;
ChatWindowFactory* chatWindowFactory_;
UserSearchWindowFactory* userSearchWindowFactory_;
MUCController* controller_;
// NickResolver* nickResolver_;
PresenceOracle* presenceOracle_;
AvatarManager* avatarManager_;
StanzaChannelPresenceSender* presenceSender_;
DirectedPresenceSender* directedPresenceSender_;
MockRepository* mocks_;
UIEventStream* uiEventStream_;
MockChatWindow* window_;
diff --git a/Swift/Controllers/Chat/UserSearchController.cpp b/Swift/Controllers/Chat/UserSearchController.cpp
index 305049f..91e0dea 100644
--- a/Swift/Controllers/Chat/UserSearchController.cpp
+++ b/Swift/Controllers/Chat/UserSearchController.cpp
@@ -1,45 +1,44 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/Controllers/Chat/UserSearchController.h>
#include <memory>
#include <boost/bind.hpp>
#include <Swiften/Avatars/AvatarManager.h>
#include <Swiften/Base/String.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Disco/DiscoServiceWalker.h>
#include <Swiften/Disco/GetDiscoInfoRequest.h>
#include <Swiften/Disco/GetDiscoItemsRequest.h>
#include <Swiften/Presence/PresenceOracle.h>
#include <Swiften/VCards/VCardManager.h>
#include <Swift/Controllers/ContactEditController.h>
#include <Swift/Controllers/ContactSuggester.h>
#include <Swift/Controllers/Intl.h>
#include <Swift/Controllers/ProfileSettingsProvider.h>
#include <Swift/Controllers/Roster/RosterController.h>
#include <Swift/Controllers/UIEvents/RequestAddUserDialogUIEvent.h>
#include <Swift/Controllers/UIEvents/RequestChatWithUserDialogUIEvent.h>
#include <Swift/Controllers/UIEvents/RequestInviteToMUCUIEvent.h>
#include <Swift/Controllers/UIEvents/UIEventStream.h>
#include <Swift/Controllers/UIInterfaces/UserSearchWindow.h>
#include <Swift/Controllers/UIInterfaces/UserSearchWindowFactory.h>
namespace Swift {
static const std::string SEARCHED_DIRECTORIES = "searchedDirectories";
UserSearchController::UserSearchController(Type type, const JID& jid, UIEventStream* uiEventStream, VCardManager* vcardManager, UserSearchWindowFactory* factory, IQRouter* iqRouter, RosterController* rosterController, ContactSuggester* contactSuggester, AvatarManager* avatarManager, PresenceOracle* presenceOracle, ProfileSettingsProvider* settings) : type_(type), jid_(jid), uiEventStream_(uiEventStream), vcardManager_(vcardManager), factory_(factory), iqRouter_(iqRouter), rosterController_(rosterController), contactSuggester_(contactSuggester), avatarManager_(avatarManager), presenceOracle_(presenceOracle), settings_(settings) {
uiEventStream_->onUIEvent.connect(boost::bind(&UserSearchController::handleUIEvent, this, _1));
vcardManager_->onVCardChanged.connect(boost::bind(&UserSearchController::handleVCardChanged, this, _1, _2));
avatarManager_->onAvatarChanged.connect(boost::bind(&UserSearchController::handleAvatarChanged, this, _1));
presenceOracle_->onPresenceChange.connect(boost::bind(&UserSearchController::handlePresenceChanged, this, _1));
window_ = nullptr;
discoWalker_ = nullptr;
loadSavedDirectories();
@@ -116,201 +115,202 @@ void UserSearchController::handleUIEvent(std::shared_ptr<UIEvent> event) {
window_->setRoomJID(inviteToMUCRequest->getRoom());
}
return;
}
}
void UserSearchController::handleFormRequested(const JID& service) {
window_->setSearchError(false);
window_->setServerSupportsSearch(true);
//Abort a previous search if is active
endDiscoWalker();
delete discoWalker_;
discoWalker_ = new DiscoServiceWalker(service, iqRouter_);
discoWalker_->onServiceFound.connect(boost::bind(&UserSearchController::handleDiscoServiceFound, this, _1, _2));
discoWalker_->onWalkComplete.connect(boost::bind(&UserSearchController::handleDiscoWalkFinished, this));
discoWalker_->beginWalk();
}
void UserSearchController::endDiscoWalker() {
if (discoWalker_) {
discoWalker_->endWalk();
discoWalker_->onServiceFound.disconnect(boost::bind(&UserSearchController::handleDiscoServiceFound, this, _1, _2));
discoWalker_->onWalkComplete.disconnect(boost::bind(&UserSearchController::handleDiscoWalkFinished, this));
}
}
void UserSearchController::handleDiscoServiceFound(const JID& jid, std::shared_ptr<DiscoInfo> info) {
//bool isUserDirectory = false;
bool supports55 = false;
- foreach (DiscoInfo::Identity identity, info->getIdentities()) {
+ // TODO: Cleanup code
+ for (const auto& identity : info->getIdentities()) {
if ((identity.getCategory() == "directory"
&& identity.getType() == "user")) {
//isUserDirectory = true;
}
}
std::vector<std::string> features = info->getFeatures();
supports55 = std::find(features.begin(), features.end(), DiscoInfo::JabberSearchFeature) != features.end();
if (/*isUserDirectory && */supports55) { //FIXME: once M-Link correctly advertises directoryness.
/* Abort further searches.*/
endDiscoWalker();
std::shared_ptr<GenericRequest<SearchPayload> > searchRequest(new GenericRequest<SearchPayload>(IQ::Get, jid, std::make_shared<SearchPayload>(), iqRouter_));
searchRequest->onResponse.connect(boost::bind(&UserSearchController::handleFormResponse, this, _1, _2));
searchRequest->send();
}
}
void UserSearchController::handleFormResponse(std::shared_ptr<SearchPayload> fields, ErrorPayload::ref error) {
if (error || !fields) {
window_->setServerSupportsSearch(false);
return;
}
window_->setSearchFields(fields);
}
void UserSearchController::handleSearch(std::shared_ptr<SearchPayload> fields, const JID& jid) {
addToSavedDirectories(jid);
std::shared_ptr<GenericRequest<SearchPayload> > searchRequest(new GenericRequest<SearchPayload>(IQ::Set, jid, fields, iqRouter_));
searchRequest->onResponse.connect(boost::bind(&UserSearchController::handleSearchResponse, this, _1, _2));
searchRequest->send();
}
void UserSearchController::handleSearchResponse(std::shared_ptr<SearchPayload> resultsPayload, ErrorPayload::ref error) {
if (error || !resultsPayload) {
window_->setSearchError(true);
return;
}
std::vector<UserSearchResult> results;
if (resultsPayload->getForm()) {
window_->setResultsForm(resultsPayload->getForm());
} else {
- foreach (SearchPayload::Item item, resultsPayload->getItems()) {
+ for (auto&& item : resultsPayload->getItems()) {
JID jid(item.jid);
std::map<std::string, std::string> fields;
fields["first"] = item.first;
fields["last"] = item.last;
fields["nick"] = item.nick;
fields["email"] = item.email;
UserSearchResult result(jid, fields);
results.push_back(result);
}
window_->setResults(results);
}
}
void UserSearchController::handleNameSuggestionRequest(const JID &jid) {
suggestionsJID_= jid;
VCard::ref vcard = vcardManager_->getVCardAndRequestWhenNeeded(jid);
if (vcard) {
handleVCardChanged(jid, vcard);
}
}
void UserSearchController::handleJIDEditingFinished(const JID& jid) {
if (jid.isValid()) {
if (rosterController_->getItem(jid)) {
window_->setWarning(QT_TRANSLATE_NOOP("", "This contact is already on your contact list."));
}
else if (jid.getNode().empty()) {
window_->setWarning(QT_TRANSLATE_NOOP("", "Part of the address you have entered is missing. An address has a structure of 'user@example.com'."));
}
else {
window_->setWarning(boost::optional<std::string>());
}
}
else {
window_->setWarning(QT_TRANSLATE_NOOP("", "The address you have entered is invalid."));
}
}
void UserSearchController::handleContactSuggestionsRequested(std::string text) {
const std::vector<JID> existingJIDs = window_->getJIDs();
std::vector<Contact::ref> suggestions = contactSuggester_->getSuggestions(text, false);
/* do not suggest contacts that have already been added to the chat list */
std::vector<Contact::ref>::iterator i = suggestions.begin();
while (i != suggestions.end()) {
bool found = false;
- foreach (const JID& jid, existingJIDs) {
+ for (const auto& jid : existingJIDs) {
if ((*i)->jid == jid) {
found = true;
break;
}
}
// remove contact suggestions which are already on the contact list in add-contact-mode
if (type_ == AddContact) {
if (!found && !!rosterController_->getItem((*i)->jid)) {
found = true;
}
}
if (found) {
i = suggestions.erase(i);
} else {
i++;
}
}
window_->setContactSuggestions(suggestions);
}
void UserSearchController::handleVCardChanged(const JID& jid, VCard::ref vcard) {
if (jid == suggestionsJID_) {
window_->setNameSuggestions(ContactEditController::nameSuggestionsFromVCard(vcard));
suggestionsJID_ = JID();
}
handleJIDUpdateRequested(std::vector<JID>(1, jid));
}
void UserSearchController::handleAvatarChanged(const JID& jid) {
handleJIDUpdateRequested(std::vector<JID>(1, jid));
}
void UserSearchController::handlePresenceChanged(Presence::ref presence) {
handleJIDUpdateRequested(std::vector<JID>(1, presence->getFrom().toBare()));
}
void UserSearchController::handleJIDUpdateRequested(const std::vector<JID>& jids) {
if (window_) {
std::vector<Contact::ref> updates;
- foreach(const JID& jid, jids) {
+ for (const auto& jid : jids) {
updates.push_back(convertJIDtoContact(jid));
}
window_->updateContacts(updates);
}
}
void UserSearchController::handleJIDAddRequested(const std::vector<JID>& jids) {
std::vector<Contact::ref> contacts;
- foreach(const JID& jid, jids) {
+ for (const auto& jid : jids) {
contacts.push_back(convertJIDtoContact(jid));
}
window_->addContacts(contacts);
}
Contact::ref UserSearchController::convertJIDtoContact(const JID& jid) {
Contact::ref contact = std::make_shared<Contact>();
contact->jid = jid;
// name lookup
boost::optional<XMPPRosterItem> rosterItem = rosterController_->getItem(jid);
if (rosterItem && !rosterItem->getName().empty()) {
contact->name = rosterItem->getName();
} else {
VCard::ref vcard = vcardManager_->getVCard(jid);
if (vcard && !vcard->getFullName().empty()) {
contact->name = vcard->getFullName();
} else {
contact->name = jid.toString();
}
}
// presence lookup
Presence::ref presence = presenceOracle_->getAccountPresence(jid);
if (presence) {
contact->statusType = presence->getShow();
} else {
contact->statusType = StatusShow::None;
}
@@ -331,62 +331,62 @@ void UserSearchController::initializeUserWindow() {
case AddContact:
windowType = UserSearchWindow::AddContact;
break;
case StartChat:
windowType = UserSearchWindow::ChatToContact;
break;
case InviteToChat:
windowType = UserSearchWindow::InviteToChat;
break;
}
window_ = factory_->createUserSearchWindow(windowType, uiEventStream_, rosterController_->getGroups());
if (!window_) {
// UI Doesn't support user search
return;
}
window_->onNameSuggestionRequested.connect(boost::bind(&UserSearchController::handleNameSuggestionRequest, this, _1));
window_->onFormRequested.connect(boost::bind(&UserSearchController::handleFormRequested, this, _1));
window_->onSearchRequested.connect(boost::bind(&UserSearchController::handleSearch, this, _1, _2));
window_->onContactSuggestionsRequested.connect(boost::bind(&UserSearchController::handleContactSuggestionsRequested, this, _1));
window_->onJIDUpdateRequested.connect(boost::bind(&UserSearchController::handleJIDUpdateRequested, this, _1));
window_->onJIDAddRequested.connect(boost::bind(&UserSearchController::handleJIDAddRequested, this, _1));
window_->onJIDEditFieldChanged.connect(boost::bind(&UserSearchController::handleJIDEditingFinished, this, _1));
window_->setSelectedService(JID(jid_.getDomain()));
window_->clear();
}
}
void UserSearchController::loadSavedDirectories() {
savedDirectories_.clear();
- foreach (std::string stringItem, String::split(settings_->getStringSetting(SEARCHED_DIRECTORIES), '\n')) {
+ for (auto&& stringItem : String::split(settings_->getStringSetting(SEARCHED_DIRECTORIES), '\n')) {
if(!stringItem.empty()) {
savedDirectories_.push_back(JID(stringItem));
}
}
}
void UserSearchController::addToSavedDirectories(const JID& jid) {
if (!jid.isValid()) {
return;
}
savedDirectories_.erase(std::remove(savedDirectories_.begin(), savedDirectories_.end(), jid), savedDirectories_.end());
savedDirectories_.insert(savedDirectories_.begin(), jid);
std::string collapsed;
int i = 0;
- foreach (JID jidItem, savedDirectories_) {
+ for (const auto& jidItem : savedDirectories_) {
if (i >= 15) {
break;
}
if (!collapsed.empty()) {
collapsed += "\n";
}
collapsed += jidItem.toString();
++i;
}
settings_->storeString(SEARCHED_DIRECTORIES, collapsed);
window_->addSavedServices(savedDirectories_);
}
}
diff --git a/Swift/Controllers/ChatMessageSummarizer.cpp b/Swift/Controllers/ChatMessageSummarizer.cpp
index 6b630e7..ac3d896 100644
--- a/Swift/Controllers/ChatMessageSummarizer.cpp
+++ b/Swift/Controllers/ChatMessageSummarizer.cpp
@@ -1,46 +1,45 @@
/*
* Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/Controllers/ChatMessageSummarizer.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Base/format.h>
#include <Swift/Controllers/Intl.h>
using namespace Swift;
using namespace std;
string ChatMessageSummarizer::getSummary(const string& current, const vector<UnreadPair>& unreads) {
vector<UnreadPair> others;
int currentUnread = 0;
int otherCount = 0;
- foreach (UnreadPair unread, unreads) {
+ for (const auto& unread : unreads) {
if (unread.first == current) {
currentUnread += unread.second;
} else {
if (unread.second > 0) {
otherCount += unread.second;
others.push_back(unread);
}
}
}
string myString(current);
if (currentUnread > 0) {
string result(QT_TRANSLATE_NOOP("", "%1% (%2%)"));
myString = str(format(result) % current % currentUnread);
}
if (others.size() > 1) {
string result(QT_TRANSLATE_NOOP("", "%1% and %2% others (%3%)"));
myString = str(format(result) % myString % others.size() % otherCount);
} else if (!others.empty()) {
string result(QT_TRANSLATE_NOOP("", "%1%; %2% (%3%)"));
myString = str(format(result) % myString % others[0].first % otherCount);
}
return myString;
}
diff --git a/Swift/Controllers/ContactSuggester.cpp b/Swift/Controllers/ContactSuggester.cpp
index 8a3a6fa..eb27ed4 100644
--- a/Swift/Controllers/ContactSuggester.cpp
+++ b/Swift/Controllers/ContactSuggester.cpp
@@ -1,87 +1,86 @@
/*
* Copyright (c) 2013 Tobias Markmann
* Licensed under the simplified BSD license.
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
/*
* Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/Controllers/ContactSuggester.h>
#include <algorithm>
#include <set>
#include <vector>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/find.hpp>
#include <boost/bind.hpp>
#include <boost/lambda/bind.hpp>
#include <boost/lambda/lambda.hpp>
#include <Swiften/Base/Algorithm.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/JID/JID.h>
#include <Swift/Controllers/ContactProvider.h>
namespace lambda = boost::lambda;
namespace Swift {
ContactSuggester::ContactSuggester() {
}
ContactSuggester::~ContactSuggester() {
}
void ContactSuggester::addContactProvider(ContactProvider* provider) {
contactProviders_.push_back(provider);
}
bool ContactSuggester::matchContact(const std::string& search, const Contact::ref& c) {
if (fuzzyMatch(c->name, search)) {
return true;
}
else if (c->jid.isValid()) {
return fuzzyMatch(c->jid.toString(), search);
}
return false;
}
std::vector<Contact::ref> ContactSuggester::getSuggestions(const std::string& search, bool withMUCNicks) const {
std::vector<Contact::ref> results;
- foreach(ContactProvider* provider, contactProviders_) {
+ for (auto provider : contactProviders_) {
append(results, provider->getContacts(withMUCNicks));
}
std::sort(results.begin(), results.end(), Contact::lexicographicalSortPredicate);
results.erase(std::unique(results.begin(), results.end(), Contact::equalityPredicate), results.end());
results.erase(std::remove_if(results.begin(), results.end(), !lambda::bind(&matchContact, search, lambda::_1)),
results.end());
std::sort(results.begin(), results.end(), boost::bind(&Contact::sortPredicate, _1, _2, search));
return results;
}
bool ContactSuggester::fuzzyMatch(std::string text, std::string match) {
std::string lowerText = text;
boost::algorithm::to_lower(lowerText);
std::string lowerMatch = match;
boost::algorithm::to_lower(lowerMatch);
size_t lastMatch = 0;
for (char i : lowerMatch) {
size_t where = lowerText.find_first_of(i, lastMatch);
if (where == std::string::npos) {
return false;
}
lastMatch = where + 1;
}
return true;
}
}
diff --git a/Swift/Controllers/ContactsFromXMPPRoster.cpp b/Swift/Controllers/ContactsFromXMPPRoster.cpp
index e3c5d97..1d1ccd4 100644
--- a/Swift/Controllers/ContactsFromXMPPRoster.cpp
+++ b/Swift/Controllers/ContactsFromXMPPRoster.cpp
@@ -1,41 +1,40 @@
/*
* Copyright (c) 2013 Tobias Markmann
* Licensed under the simplified BSD license.
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
/*
* Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/Controllers/ContactsFromXMPPRoster.h>
#include <Swiften/Avatars/AvatarManager.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Presence/PresenceOracle.h>
#include <Swiften/Roster/XMPPRoster.h>
#include <Swiften/Roster/XMPPRosterItem.h>
namespace Swift {
ContactsFromXMPPRoster::ContactsFromXMPPRoster(XMPPRoster* roster, AvatarManager* avatarManager, PresenceOracle* presenceOracle) : roster_(roster), avatarManager_(avatarManager), presenceOracle_(presenceOracle) {
}
ContactsFromXMPPRoster::~ContactsFromXMPPRoster() {
}
std::vector<Contact::ref> ContactsFromXMPPRoster::getContacts(bool /*withMUCNicks*/) {
std::vector<Contact::ref> results;
std::vector<XMPPRosterItem> rosterItems = roster_->getItems();
- foreach(const XMPPRosterItem& rosterItem, rosterItems) {
+ for (const auto& rosterItem : rosterItems) {
Contact::ref contact = std::make_shared<Contact>(rosterItem.getName().empty() ? rosterItem.getJID().toString() : rosterItem.getName(), rosterItem.getJID(), StatusShow::None,"");
contact->statusType = presenceOracle_->getAccountPresence(contact->jid) ? presenceOracle_->getAccountPresence(contact->jid)->getShow() : StatusShow::None;
contact->avatarPath = avatarManager_->getAvatarPath(contact->jid);
results.push_back(contact);
}
return results;
}
}
diff --git a/Swift/Controllers/FileTransfer/FileTransferOverview.cpp b/Swift/Controllers/FileTransfer/FileTransferOverview.cpp
index af2831c..fcc35e4 100644
--- a/Swift/Controllers/FileTransfer/FileTransferOverview.cpp
+++ b/Swift/Controllers/FileTransfer/FileTransferOverview.cpp
@@ -1,92 +1,91 @@
/*
* Copyright (c) 2011 Tobias Markmann
* Licensed under the simplified BSD license.
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
/*
* Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/Controllers/FileTransfer/FileTransferOverview.h>
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
#include <boost/signals2.hpp>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/FileTransfer/FileTransferManager.h>
namespace Swift {
FileTransferOverview::FileTransferOverview(FileTransferManager* ftm) : fileTransferManager(ftm) {
fileTransferManager->onIncomingFileTransfer.connect(boost::bind(&FileTransferOverview::handleIncomingFileTransfer, this, _1));
onNewFileTransferController.connect(boost::bind(&FileTransferOverview::handleNewFileTransferController, this, _1));
}
FileTransferOverview::~FileTransferOverview() {
onNewFileTransferController.disconnect(boost::bind(&FileTransferOverview::handleNewFileTransferController, this, _1));
fileTransferManager->onIncomingFileTransfer.disconnect(boost::bind(&FileTransferOverview::handleIncomingFileTransfer, this, _1));
- foreach(FileTransferController* controller, fileTransfers) {
+ for (auto controller : fileTransfers) {
controller->onStateChanged.disconnect(boost::bind(&FileTransferOverview::handleFileTransferStateChanged, this));
}
}
void FileTransferOverview::sendFile(const JID& jid, const std::string& filename) {
if (boost::filesystem::exists(filename) && boost::filesystem::file_size(filename) > 0) {
FileTransferController* controller = new FileTransferController(jid, filename, fileTransferManager);
onNewFileTransferController(controller);
}
}
void FileTransferOverview::handleIncomingFileTransfer(IncomingFileTransfer::ref transfer) {
FileTransferController* controller = new FileTransferController(transfer);
onNewFileTransferController(controller);
}
void FileTransferOverview::handleNewFileTransferController(FileTransferController* controller) {
fileTransfers.push_back(controller);
controller->onStateChanged.connect(boost::bind(&FileTransferOverview::handleFileTransferStateChanged, this));
}
void FileTransferOverview::handleFileTransferStateChanged() {
onFileTransferListChanged();
}
const std::vector<FileTransferController*>& FileTransferOverview::getFileTransfers() const {
return fileTransfers;
}
void FileTransferOverview::clearFinished() {
for (std::vector<FileTransferController*>::iterator it = fileTransfers.begin(); it != fileTransfers.end(); ) {
if((*it)->getState().type == FileTransfer::State::Finished
|| (*it)->getState().type == FileTransfer::State::Failed
|| (*it)->getState().type == FileTransfer::State::Canceled) {
FileTransferController* controller = *it;
it = fileTransfers.erase(it);
controller->onStateChanged.disconnect(boost::bind(&FileTransferOverview::handleFileTransferStateChanged, this));
delete controller;
} else {
++it;
}
}
onFileTransferListChanged();
}
bool FileTransferOverview::isClearable() const {
bool isClearable = false;
- foreach (FileTransferController* controller, fileTransfers) {
+ for (auto controller : fileTransfers) {
if(controller->getState().type == FileTransfer::State::Finished
|| controller->getState().type == FileTransfer::State::Failed
|| controller->getState().type == FileTransfer::State::Canceled) {
isClearable = true;
break;
}
}
return isClearable;
}
}
diff --git a/Swift/Controllers/HighlightManager.cpp b/Swift/Controllers/HighlightManager.cpp
index 2afaf49..9176301 100644
--- a/Swift/Controllers/HighlightManager.cpp
+++ b/Swift/Controllers/HighlightManager.cpp
@@ -1,57 +1,55 @@
/*
* Copyright (c) 2012 Maciej Niedzielski
* Licensed under the simplified BSD license.
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
/*
* Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/Controllers/HighlightManager.h>
#include <cassert>
#include <sstream>
#include <boost/algorithm/string.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/bind.hpp>
#include <boost/numeric/conversion/cast.hpp>
#include <boost/regex.hpp>
#include <boost/serialization/vector.hpp>
-#include <Swiften/Base/foreach.h>
-
#include <Swift/Controllers/Highlighter.h>
#include <Swift/Controllers/SettingConstants.h>
#include <Swift/Controllers/Settings/SettingsProvider.h>
/* How does highlighting work?
*
* HighlightManager manages a list of if-then rules used to highlight messages.
* Rule is represented by HighlightRule. Action ("then" part) is HighlightAction.
*
*
* HighlightManager is also used as a factory for Highlighter objects.
* Each ChatControllerBase has its own Highlighter.
* Highligher may be customized by using setNick(), etc.
*
* ChatControllerBase passes incoming messages to Highlighter and gets HighlightAction in return
* (first matching rule is returned).
* If needed, HighlightAction is then passed back to Highlighter for further handling.
* This results in HighlightManager emiting onHighlight event,
* which is handled by SoundController to play sound notification
*/
namespace Swift {
HighlightManager::HighlightManager(SettingsProvider* settings)
: settings_(settings)
, storingSettings_(false) {
rules_ = std::make_shared<HighlightRulesList>();
loadSettings();
handleSettingChangedConnection_ = settings_->onSettingChanged.connect(boost::bind(&HighlightManager::handleSettingChanged, this, _1));
}
diff --git a/Swift/Controllers/HighlightRule.cpp b/Swift/Controllers/HighlightRule.cpp
index 86ac5f7..a8cb7e4 100644
--- a/Swift/Controllers/HighlightRule.cpp
+++ b/Swift/Controllers/HighlightRule.cpp
@@ -1,121 +1,120 @@
/*
* Copyright (c) 2012 Maciej Niedzielski
* Licensed under the simplified BSD license.
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
/*
- * Copyright (c) 2014-2015 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/Controllers/HighlightRule.h>
#include <algorithm>
#include <boost/algorithm/string.hpp>
#include <boost/lambda/lambda.hpp>
#include <Swiften/Base/Regex.h>
-#include <Swiften/Base/foreach.h>
namespace Swift {
HighlightRule::HighlightRule()
: nickIsKeyword_(false)
, matchCase_(false)
, matchWholeWords_(false)
, matchChat_(false)
, matchMUC_(false)
{
}
boost::regex HighlightRule::regexFromString(const std::string & s) const
{
std::string escaped = Regex::escape(s);
std::string word = matchWholeWords_ ? "\\b" : "";
boost::regex::flag_type flags = boost::regex::normal;
if (!matchCase_) {
flags |= boost::regex::icase;
}
return boost::regex(word + escaped + word, flags);
}
void HighlightRule::updateRegex() const
{
keywordRegex_.clear();
- foreach (const std::string & k, keywords_) {
+ for (const auto& k : keywords_) {
keywordRegex_.push_back(regexFromString(k));
}
senderRegex_.clear();
- foreach (const std::string & s, senders_) {
+ for (const auto& s : senders_) {
senderRegex_.push_back(regexFromString(s));
}
}
std::string HighlightRule::boolToString(bool b)
{
return b ? "1" : "0";
}
bool HighlightRule::boolFromString(const std::string& s)
{
return s == "1";
}
bool HighlightRule::isMatch(const std::string& body, const std::string& sender, const std::string& nick, MessageType messageType) const
{
if ((messageType == HighlightRule::ChatMessage && matchChat_) || (messageType == HighlightRule::MUCMessage && matchMUC_)) {
bool matchesKeyword = keywords_.empty() && (nick.empty() || !nickIsKeyword_);
bool matchesSender = senders_.empty();
if (!matchesKeyword) {
// check if the nickname matches
if (nickIsKeyword_ && !nick.empty() && boost::regex_search(body, regexFromString(nick))) {
matchesKeyword = true;
}
// check if a keyword matches
if (!matchesKeyword && !keywords_.empty()) {
- foreach (const boost::regex &keyword, keywordRegex_) {
+ for (const auto& keyword : keywordRegex_) {
if (boost::regex_search(body, keyword)) {
matchesKeyword = true;
break;
}
}
}
}
- foreach (const boost::regex & rx, senderRegex_) {
+ for (const auto& rx : senderRegex_) {
if (boost::regex_search(sender, rx)) {
matchesSender = true;
break;
}
}
if (matchesKeyword && matchesSender) {
return true;
}
}
return false;
}
void HighlightRule::setSenders(const std::vector<std::string>& senders)
{
senders_ = senders;
updateRegex();
}
void HighlightRule::setKeywords(const std::vector<std::string>& keywords)
{
keywords_ = keywords;
updateRegex();
}
std::vector<boost::regex> HighlightRule::getKeywordRegex(const std::string& nick) const {
if (nickIsKeyword_) {
std::vector<boost::regex> regex;
if (!nick.empty()) {
diff --git a/Swift/Controllers/Highlighter.cpp b/Swift/Controllers/Highlighter.cpp
index 3499217..cea077e 100644
--- a/Swift/Controllers/Highlighter.cpp
+++ b/Swift/Controllers/Highlighter.cpp
@@ -1,46 +1,44 @@
/*
* Copyright (c) 2012 Maciej Niedzielski
* Licensed under the simplified BSD license.
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
/*
* Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/Controllers/Highlighter.h>
-#include <Swiften/Base/foreach.h>
-
#include <Swift/Controllers/HighlightManager.h>
namespace Swift {
Highlighter::Highlighter(HighlightManager* manager)
: manager_(manager)
{
setMode(ChatMode);
}
void Highlighter::setMode(Mode mode)
{
mode_ = mode;
messageType_ = mode_ == ChatMode ? HighlightRule::ChatMessage : HighlightRule::MUCMessage;
}
HighlightAction Highlighter::findFirstFullMessageMatchAction(const std::string& body, const std::string& sender) const
{
HighlightAction match;
HighlightRulesListPtr rules = manager_->getRules();
for (size_t i = 0; i < rules->getSize(); ++i) {
const HighlightRule& rule = rules->getRule(i);
if (rule.isMatch(body, sender, nick_, messageType_) && rule.getAction().highlightWholeMessage()) {
match = rule.getAction();
break;
}
}
return match;
}
diff --git a/Swift/Controllers/HistoryViewController.cpp b/Swift/Controllers/HistoryViewController.cpp
index d66b2b2..669b002 100644
--- a/Swift/Controllers/HistoryViewController.cpp
+++ b/Swift/Controllers/HistoryViewController.cpp
@@ -1,47 +1,48 @@
/*
* Copyright (c) 2012 Catalin Badea
* Licensed under the simplified BSD license.
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
/*
* Copyright (c) 2013-2016 Isode Limited.
* Licensed under the GNU General Public License.
* See the COPYING file for more information.
*/
#include <Swift/Controllers/HistoryViewController.h>
+#include <boost/range/adaptor/reversed.hpp>
+
#include <Swiften/Avatars/AvatarManager.h>
#include <Swiften/Base/Path.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Client/NickResolver.h>
#include <Swiften/History/HistoryMessage.h>
#include <Swift/Controllers/HistoryController.h>
#include <Swift/Controllers/Roster/ItemOperations/SetAvatar.h>
#include <Swift/Controllers/Roster/ItemOperations/SetPresence.h>
#include <Swift/Controllers/UIEvents/RequestHistoryUIEvent.h>
#include <Swift/Controllers/UIInterfaces/HistoryWindowFactory.h>
namespace Swift {
static const std::string category[] = { "Contacts", "MUC", "Contacts" };
HistoryViewController::HistoryViewController(
const JID& selfJID,
UIEventStream* uiEventStream,
HistoryController* historyController,
NickResolver* nickResolver,
AvatarManager* avatarManager,
PresenceOracle* presenceOracle,
HistoryWindowFactory* historyWindowFactory) :
selfJID_(selfJID),
uiEventStream_(uiEventStream),
historyController_(historyController),
nickResolver_(nickResolver),
avatarManager_(avatarManager),
presenceOracle_(presenceOracle),
historyWindowFactory_(historyWindowFactory),
historyWindow_(nullptr),
selectedItem_(nullptr),
currentResultDate_(boost::gregorian::not_a_date_time) {
@@ -97,61 +98,61 @@ void HistoryViewController::handleUIEvent(std::shared_ptr<UIEvent> rawEvent) {
}
}
void HistoryViewController::handleSelectedContactChanged(RosterItem* newContact) {
// FIXME: signal is triggerd twice.
ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(newContact);
if (contact && selectedItem_ != contact) {
selectedItem_ = contact;
historyWindow_->resetConversationView();
}
else {
return;
}
JID contactJID = contact->getJID();
std::vector<HistoryMessage> messages;
for (int it = HistoryMessage::Chat; it <= HistoryMessage::PrivateMessage; it++) {
HistoryMessage::Type type = static_cast<HistoryMessage::Type>(it);
if (contacts_[type].count(contactJID)) {
currentResultDate_ = *contacts_[type][contactJID].rbegin();
selectedItemType_ = type;
messages = historyController_->getMessagesFromDate(selfJID_, contactJID, type, currentResultDate_);
}
}
historyWindow_->setDate(currentResultDate_);
- foreach (const HistoryMessage& message, messages) {
+ for (const auto& message : messages) {
addNewMessage(message, false);
}
}
void HistoryViewController::handleNewMessage(const HistoryMessage& message) {
JID contactJID = message.getFromJID().toBare() == selfJID_ ? message.getToJID() : message.getFromJID();
JID displayJID;
if (message.getType() == HistoryMessage::PrivateMessage) {
displayJID = contactJID;
}
else {
displayJID = contactJID.toBare();
}
// check current conversation
if (selectedItem_ && selectedItem_->getJID() == displayJID) {
if (historyWindow_->getLastVisibleDate() == message.getTime().date()) {
addNewMessage(message, false);
}
}
// check if the new message matches the query
if (message.getMessage().find(historyWindow_->getSearchBoxText()) == std::string::npos) {
return;
}
// update contacts
if (!contacts_[message.getType()].count(displayJID)) {
roster_->addContact(displayJID, displayJID, nickResolver_->jidToNick(displayJID), category[message.getType()], avatarManager_->getAvatarPath(displayJID));
@@ -176,184 +177,184 @@ void HistoryViewController::handleReturnPressed(const std::string& keyword) {
contacts_[type] = historyController_->getContacts(selfJID_, type, keyword);
for (ContactsMap::const_iterator contact = contacts_[type].begin(); contact != contacts_[type].end(); contact++) {
const JID& jid = contact->first;
std::string nick;
if (type == HistoryMessage::PrivateMessage) {
nick = jid.toString();
}
else {
nick = nickResolver_->jidToNick(jid);
}
roster_->addContact(jid, jid, nick, category[type], avatarManager_->getAvatarPath(jid));
Presence::ref presence = getPresence(jid, type == HistoryMessage::Groupchat);
if (presence.get()) {
roster_->applyOnItem(SetPresence(presence, JID::WithoutResource), jid);
}
}
}
}
void HistoryViewController::handleScrollReachedTop(const boost::gregorian::date& date) {
if (!selectedItem_) {
return;
}
std::vector<HistoryMessage> messages = historyController_->getMessagesFromPreviousDate(selfJID_, selectedItem_->getJID(), selectedItemType_, date);
- foreach (const HistoryMessage& message, messages) {
+ for (const auto& message : messages) {
addNewMessage(message, true);
}
historyWindow_->resetConversationViewTopInsertPoint();
}
void HistoryViewController::handleScrollReachedBottom(const boost::gregorian::date& date) {
if (!selectedItem_) {
return;
}
std::vector<HistoryMessage> messages = historyController_->getMessagesFromNextDate(selfJID_, selectedItem_->getJID(), selectedItemType_, date);
- foreach (const HistoryMessage& message, messages) {
+ for (const auto& message : messages) {
addNewMessage(message, false);
}
}
void HistoryViewController::handleNextButtonClicked() {
if (!selectedItem_) {
return;
}
std::set<boost::gregorian::date>::iterator date = contacts_[selectedItemType_][selectedItem_->getJID()].find(currentResultDate_);
if (*date == *contacts_[selectedItemType_][selectedItem_->getJID()].rbegin()) {
return;
}
historyWindow_->resetConversationView();
currentResultDate_ = *(++date);
std::vector<HistoryMessage> messages = historyController_->getMessagesFromDate(selfJID_, selectedItem_->getJID(), selectedItemType_, currentResultDate_);
historyWindow_->setDate(currentResultDate_);
- foreach (const HistoryMessage& message, messages) {
+ for (const auto& message : messages) {
addNewMessage(message, false);
}
}
void HistoryViewController::handlePreviousButtonClicked() {
if (!selectedItem_) {
return;
}
std::set<boost::gregorian::date>::iterator date = contacts_[selectedItemType_][selectedItem_->getJID()].find(currentResultDate_);
if (date == contacts_[selectedItemType_][selectedItem_->getJID()].begin()) {
return;
}
historyWindow_->resetConversationView();
currentResultDate_ = *(--date);
std::vector<HistoryMessage> messages = historyController_->getMessagesFromDate(selfJID_, selectedItem_->getJID(), selectedItemType_, currentResultDate_);
historyWindow_->setDate(currentResultDate_);
- foreach (const HistoryMessage& message, messages) {
+ for (const auto& message : messages) {
addNewMessage(message, false);
}
}
void HistoryViewController::reset() {
roster_->removeAll();
contacts_.clear();
selectedItem_ = nullptr;
historyWindow_->resetConversationView();
}
void HistoryViewController::handleCalendarClicked(const boost::gregorian::date& date) {
if (!selectedItem_) {
return;
}
boost::gregorian::date newDate;
if (contacts_[selectedItemType_][selectedItem_->getJID()].count(date)) {
newDate = date;
}
else if (date < currentResultDate_) {
- foreach(const boost::gregorian::date& current, contacts_[selectedItemType_][selectedItem_->getJID()]) {
+ for (const auto& current : contacts_[selectedItemType_][selectedItem_->getJID()]) {
if (current > date) {
newDate = current;
break;
}
}
}
else {
- reverse_foreach(const boost::gregorian::date& current, contacts_[selectedItemType_][selectedItem_->getJID()]) {
+ for (const auto& current : boost::adaptors::reverse(contacts_[selectedItemType_][selectedItem_->getJID()])) {
if (current < date) {
newDate = current;
break;
}
}
}
historyWindow_->setDate(newDate);
if (newDate == currentResultDate_) {
return;
}
currentResultDate_ = newDate;
historyWindow_->resetConversationView();
std::vector<HistoryMessage> messages = historyController_->getMessagesFromDate(selfJID_, selectedItem_->getJID(), selectedItemType_, currentResultDate_);
historyWindow_->setDate(currentResultDate_);
- foreach (const HistoryMessage& message, messages) {
+ for (const auto& message : messages) {
addNewMessage(message, false);
}
}
void HistoryViewController::handlePresenceChanged(Presence::ref presence) {
JID jid = presence->getFrom();
if (contacts_[HistoryMessage::Chat].count(jid.toBare())) {
roster_->applyOnItems(SetPresence(presence, JID::WithoutResource));
return;
}
if (contacts_[HistoryMessage::Groupchat].count(jid.toBare())) {
Presence::ref availablePresence = std::make_shared<Presence>(Presence());
availablePresence->setFrom(jid.toBare());
roster_->applyOnItems(SetPresence(availablePresence, JID::WithResource));
}
if (contacts_[HistoryMessage::PrivateMessage].count(jid)) {
roster_->applyOnItems(SetPresence(presence, JID::WithResource));
}
}
void HistoryViewController::handleAvatarChanged(const JID& jid) {
roster_->applyOnItems(SetAvatar(jid, avatarManager_->getAvatarPath(jid)));
}
Presence::ref HistoryViewController::getPresence(const JID& jid, bool isMUC) {
if (jid.isBare() && !isMUC) {
return presenceOracle_->getHighestPriorityPresence(jid);
}
std::vector<Presence::ref> mucPresence = presenceOracle_->getAllPresence(jid.toBare());
if (isMUC && !mucPresence.empty()) {
Presence::ref presence = std::make_shared<Presence>(Presence());
presence->setFrom(jid);
return presence;
}
- foreach (Presence::ref presence, mucPresence) {
+ for (auto&& presence : mucPresence) {
if (presence.get() && presence->getFrom() == jid) {
return presence;
}
}
return Presence::create();
}
}
diff --git a/Swift/Controllers/PreviousStatusStore.cpp b/Swift/Controllers/PreviousStatusStore.cpp
index 4806f9c..0b2d437 100644
--- a/Swift/Controllers/PreviousStatusStore.cpp
+++ b/Swift/Controllers/PreviousStatusStore.cpp
@@ -1,53 +1,51 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/Controllers/PreviousStatusStore.h>
-#include <Swiften/Base/foreach.h>
-
namespace Swift {
PreviousStatusStore::PreviousStatusStore() {
}
PreviousStatusStore::~PreviousStatusStore() {
}
void PreviousStatusStore::addStatus(StatusShow::Type status, const std::string& message) {
//FIXME: remove old entries
store_.push_back(TypeStringPair(status, message));
}
std::vector<TypeStringPair> PreviousStatusStore::exactMatchSuggestions(StatusShow::Type status, const std::string& message) {
std::vector<TypeStringPair> suggestions;
suggestions.push_back(TypeStringPair(status, message));
return suggestions;
}
std::vector<TypeStringPair> PreviousStatusStore::getSuggestions(const std::string& message) {
std::vector<TypeStringPair> suggestions;
- foreach (TypeStringPair status, store_) {
+ for (auto&& status : store_) {
if (status.second == message) {
suggestions.clear();
suggestions.push_back(status);
break;
} else if (status.second.find(message) != std::string::npos) {
suggestions.push_back(status);
}
}
if (suggestions.empty()) {
TypeStringPair suggestion(StatusShow::Online, message);
suggestions.push_back(suggestion);
}
if (suggestions.size() == 1) {
suggestions = exactMatchSuggestions(suggestions[0].first, suggestions[0].second);
}
return suggestions;
}
}
diff --git a/Swift/Controllers/PreviousStatusStore.h b/Swift/Controllers/PreviousStatusStore.h
index eb1fb59..b106445 100644
--- a/Swift/Controllers/PreviousStatusStore.h
+++ b/Swift/Controllers/PreviousStatusStore.h
@@ -1,28 +1,29 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
#include <string>
#include <utility> /* std::pair */
#include <vector>
#include <Swiften/Elements/StatusShow.h>
namespace Swift {
typedef std::pair<StatusShow::Type, std::string> TypeStringPair;
+
class PreviousStatusStore {
public:
PreviousStatusStore();
~PreviousStatusStore();
void addStatus(StatusShow::Type status, const std::string& message);
std::vector<TypeStringPair> getSuggestions(const std::string& message);
private:
std::vector<TypeStringPair> exactMatchSuggestions(StatusShow::Type status, const std::string& message);
std::vector<TypeStringPair> store_;
};
}
diff --git a/Swift/Controllers/ProfileSettingsProvider.cpp b/Swift/Controllers/ProfileSettingsProvider.cpp
index bb186fc..b979555 100644
--- a/Swift/Controllers/ProfileSettingsProvider.cpp
+++ b/Swift/Controllers/ProfileSettingsProvider.cpp
@@ -1,45 +1,47 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/Controllers/ProfileSettingsProvider.h>
+#include <Swift/Controllers/Settings/SettingsProvider.h>
+
namespace Swift {
ProfileSettingsProvider::ProfileSettingsProvider(const std::string& profile, SettingsProvider* provider) :
profile_(profile) {
provider_ = provider;
bool found = false;
- foreach (std::string existingProfile, provider->getAvailableProfiles()) {
+ for (const auto& existingProfile : provider->getAvailableProfiles()) {
if (existingProfile == profile) {
found = true;
}
}
if (!found) {
provider_->createProfile(profile);
}
}
ProfileSettingsProvider::~ProfileSettingsProvider() {
}
std::string ProfileSettingsProvider::getStringSetting(const std::string &settingPath) {
//FIXME: Remove shim
SettingsProvider::Setting<std::string> setting(profileSettingPath(settingPath), "");
return provider_->getSetting(setting);
}
void ProfileSettingsProvider::storeString(const std::string &settingPath, const std::string &settingValue) {
//FIXME: Remove shim
if (!getIsSettingFinal(settingPath)) {
SettingsProvider::Setting<std::string> setting(profileSettingPath(settingPath), "");
provider_->storeSetting(setting, settingValue);
}
}
int ProfileSettingsProvider::getIntSetting(const std::string& settingPath, int defaultValue) {
//FIXME: Remove shim
SettingsProvider::Setting<int> setting(profileSettingPath(settingPath), defaultValue);
return provider_->getSetting(setting);
diff --git a/Swift/Controllers/ProfileSettingsProvider.h b/Swift/Controllers/ProfileSettingsProvider.h
index f3c3156..e309c11 100644
--- a/Swift/Controllers/ProfileSettingsProvider.h
+++ b/Swift/Controllers/ProfileSettingsProvider.h
@@ -1,34 +1,36 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/foreach.h>
-
-#include <Swift/Controllers/Settings/SettingsProvider.h>
+#include <string>
namespace Swift {
+class SettingsProvider;
+
class ProfileSettingsProvider {
public:
ProfileSettingsProvider(const std::string& profile, SettingsProvider* provider);
virtual ~ProfileSettingsProvider();
virtual std::string getStringSetting(const std::string &settingPath);
virtual void storeString(const std::string &settingPath, const std::string &settingValue);
virtual int getIntSetting(const std::string& settingPath, int defaultValue);
virtual void storeInt(const std::string& settingPath, int settingValue);
/** See \ref SettingsProvider::getIsSettingFinal for discussion of what this means.*/
virtual bool getIsSettingFinal(const std::string& settingPath);
private:
std::string profileSettingPath(const std::string &settingPath);
+
+ private:
SettingsProvider* provider_;
std::string profile_;
};
}
diff --git a/Swift/Controllers/Roster/ContactRosterItem.cpp b/Swift/Controllers/Roster/ContactRosterItem.cpp
index 71c5f8e..8fdf183 100644
--- a/Swift/Controllers/Roster/ContactRosterItem.cpp
+++ b/Swift/Controllers/Roster/ContactRosterItem.cpp
@@ -1,42 +1,41 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/Controllers/Roster/ContactRosterItem.h>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <Swiften/Base/DateTime.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Elements/Idle.h>
#include <Swiften/Elements/Presence.h>
#include <Swift/Controllers/Intl.h>
#include <Swift/Controllers/Roster/GroupRosterItem.h>
namespace Swift {
ContactRosterItem::ContactRosterItem(const JID& jid, const JID& displayJID, const std::string& name, GroupRosterItem* parent)
: RosterItem(name, parent), jid_(jid), displayJID_(displayJID.toBare()), mucRole_(MUCOccupant::NoRole), mucAffiliation_(MUCOccupant::NoAffiliation), blockState_(BlockingNotSupported)
{
}
ContactRosterItem::~ContactRosterItem() {
}
StatusShow::Type ContactRosterItem::getStatusShow() const {
return presence_ ? presence_->getShow() : StatusShow::None;
}
StatusShow::Type ContactRosterItem::getSimplifiedStatusShow() const {
switch (presence_ ? presence_->getShow() : StatusShow::None) {
case StatusShow::Online: return StatusShow::Online;
case StatusShow::Away: return StatusShow::Away;
case StatusShow::XA: return StatusShow::Away;
case StatusShow::FFC: return StatusShow::Online;
case StatusShow::DND: return StatusShow::DND;
case StatusShow::None: return StatusShow::None;
}
diff --git a/Swift/Controllers/Roster/RosterGroupExpandinessPersister.cpp b/Swift/Controllers/Roster/RosterGroupExpandinessPersister.cpp
index af89b54..0f07c0b 100644
--- a/Swift/Controllers/Roster/RosterGroupExpandinessPersister.cpp
+++ b/Swift/Controllers/Roster/RosterGroupExpandinessPersister.cpp
@@ -1,65 +1,64 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/Controllers/Roster/RosterGroupExpandinessPersister.h>
#include <vector>
#include <boost/bind.hpp>
#include <Swiften/Base/String.h>
-#include <Swiften/Base/foreach.h>
#include <Swift/Controllers/Roster/GroupRosterItem.h>
#include <Swift/Controllers/SettingConstants.h>
namespace Swift {
RosterGroupExpandinessPersister::RosterGroupExpandinessPersister(Roster* roster, SettingsProvider* settings) : roster_(roster), settings_(settings) {
load();
roster_->onGroupAdded.connect(boost::bind(&RosterGroupExpandinessPersister::handleGroupAdded, this, _1));
}
void RosterGroupExpandinessPersister::handleGroupAdded(GroupRosterItem* group) {
if (collapsed_.find(group->getDisplayName()) != collapsed_.end()) {
group->setExpanded(false);
} else {
group->setExpanded(true);
}
group->onExpandedChanged.connect(boost::bind(&RosterGroupExpandinessPersister::handleExpandedChanged, this, group, _1));
}
void RosterGroupExpandinessPersister::handleExpandedChanged(GroupRosterItem* group, bool expanded) {
if (expanded) {
std::string displayName = group->getDisplayName();
//collapsed_.erase(std::remove(collapsed_.begin(), collapsed_.end(), displayName), collapsed_.end());
collapsed_.erase(displayName);
} else {
collapsed_.insert(group->getDisplayName());
}
save();
}
void RosterGroupExpandinessPersister::save() {
std::string setting;
- foreach (const std::string& group, collapsed_) {
+ for (const auto& group : collapsed_) {
if (!setting.empty()) {
setting += "\n";
}
setting += group;
}
settings_->storeSetting(SettingConstants::EXPANDED_ROSTER_GROUPS, setting);
}
void RosterGroupExpandinessPersister::load() {
std::string saved = settings_->getSetting(SettingConstants::EXPANDED_ROSTER_GROUPS);
std::vector<std::string> collapsed = String::split(saved, '\n');
collapsed_.insert(collapsed.begin(), collapsed.end());
}
}
diff --git a/Swift/Controllers/Roster/TableRoster.cpp b/Swift/Controllers/Roster/TableRoster.cpp
index f164a4d..713f390 100644
--- a/Swift/Controllers/Roster/TableRoster.cpp
+++ b/Swift/Controllers/Roster/TableRoster.cpp
@@ -1,45 +1,44 @@
/*
* Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/Controllers/Roster/TableRoster.h>
#include <algorithm>
#include <cassert>
#include <boost/cast.hpp>
#include <boost/numeric/conversion/cast.hpp>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Network/Timer.h>
#include <Swiften/Network/TimerFactory.h>
#include <Swift/Controllers/Roster/GroupRosterItem.h>
#include <Swift/Controllers/Roster/LeastCommonSubsequence.h>
#include <Swift/Controllers/Roster/Roster.h>
namespace Swift {
struct SectionNameEquals {
bool operator()(const TableRoster::Section& s1, const TableRoster::Section& s2) const {
return s1.name == s2.name;
}
};
template<typename T>
struct True {
bool operator()(const T&, const T&) const {
return true;
}
};
struct ItemEquals {
bool operator()(const TableRoster::Item& i1, const TableRoster::Item& i2) const {
return i1.jid == i2.jid;
}
};
struct ItemNeedsUpdate {
bool operator()(const TableRoster::Item& i1, const TableRoster::Item& i2) const {
@@ -77,65 +76,65 @@ TableRoster::~TableRoster() {
if (model) {
model->onDataChanged.disconnect(boost::bind(&TableRoster::scheduleUpdate, this));
model->onGroupAdded.disconnect(boost::bind(&TableRoster::scheduleUpdate, this));
model->onChildrenChanged.disconnect(boost::bind(&TableRoster::scheduleUpdate, this));
}
}
size_t TableRoster::getNumberOfSections() const {
return sections.size();
}
const std::string& TableRoster::getSectionTitle(size_t section) {
return sections[section].name;
}
size_t TableRoster::getNumberOfRowsInSection(size_t section) const {
return sections[section].items.size();
}
const TableRoster::Item& TableRoster::getItem(const Index& index) const {
return sections[index.section].items[index.row];
}
void TableRoster::handleUpdateTimerTick() {
updateTimer->stop();
updatePending = false;
// Get a model for the new roster
std::vector<Section> newSections;
if (model) {
- foreach(RosterItem* item, model->getRoot()->getDisplayedChildren()) {
+ for (auto item : model->getRoot()->getDisplayedChildren()) {
if (GroupRosterItem* groupItem = boost::polymorphic_downcast<GroupRosterItem*>(item)) {
//std::cerr << "* " << groupItem->getDisplayName() << std::endl;
Section section(groupItem->getDisplayName());
- foreach(RosterItem* groupChildItem, groupItem->getDisplayedChildren()) {
+ for (auto groupChildItem : groupItem->getDisplayedChildren()) {
if (ContactRosterItem* contact = boost::polymorphic_downcast<ContactRosterItem*>(groupChildItem)) {
//std::cerr << " - " << contact->getDisplayJID() << std::endl;
section.items.push_back(Item(contact->getDisplayName(), contact->getStatusText(), contact->getDisplayJID(), contact->getStatusShow(), contact->getAvatarPath()));
}
}
newSections.push_back(section);
}
}
}
// Do a diff with the previous roster
Update update;
std::vector<size_t> sectionUpdates;
std::vector<size_t> sectionPostUpdates;
computeIndexDiff<Section,SectionNameEquals,True<Section> >(sections, newSections, sectionUpdates, sectionPostUpdates, update.deletedSections, update.insertedSections);
assert(sectionUpdates.size() == sectionPostUpdates.size());
for (size_t i = 0; i < sectionUpdates.size(); ++i) {
assert(sectionUpdates[i] < sections.size());
assert(sectionPostUpdates[i] < newSections.size());
std::vector<size_t> itemUpdates;
std::vector<size_t> itemPostUpdates;
std::vector<size_t> itemRemoves;
std::vector<size_t> itemInserts;
computeIndexDiff<Item, ItemEquals, ItemNeedsUpdate >(sections[sectionUpdates[i]].items, newSections[sectionPostUpdates[i]].items, itemUpdates, itemPostUpdates, itemRemoves, itemInserts);
size_t end = update.insertedRows.size();
update.insertedRows.resize(update.insertedRows.size() + itemInserts.size());
std::transform(itemInserts.begin(), itemInserts.end(), update.insertedRows.begin() + boost::numeric_cast<long long>(end), CreateIndexForSection(sectionPostUpdates[i]));
end = update.deletedRows.size();
update.deletedRows.resize(update.deletedRows.size() + itemRemoves.size());
std::transform(itemRemoves.begin(), itemRemoves.end(), update.deletedRows.begin() + boost::numeric_cast<long long>(end), CreateIndexForSection(sectionUpdates[i]));
diff --git a/Swift/Controllers/Settings/SettingsProviderHierachy.cpp b/Swift/Controllers/Settings/SettingsProviderHierachy.cpp
index 5156d14..a05fabc 100644
--- a/Swift/Controllers/Settings/SettingsProviderHierachy.cpp
+++ b/Swift/Controllers/Settings/SettingsProviderHierachy.cpp
@@ -1,116 +1,116 @@
/*
- * Copyright (c) 2012 Isode Limited.
+ * Copyright (c) 2012-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/Controllers/Settings/SettingsProviderHierachy.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Base/Log.h>
+
namespace Swift {
SettingsProviderHierachy::~SettingsProviderHierachy() {
}
bool SettingsProviderHierachy::hasSetting(const std::string& key) {
- foreach (SettingsProvider* provider, providers_) {
+ for (auto provider : providers_) {
if (provider->hasSetting(key)) {
return true;
}
}
return false;
}
std::string SettingsProviderHierachy::getSetting(const Setting<std::string>& setting) {
std::string value = setting.getDefaultValue();
- foreach (SettingsProvider* provider, providers_) {
+ for (auto provider : providers_) {
std::string providerSetting = provider->getSetting(setting);
if (provider->hasSetting(setting.getKey())) {
value = providerSetting;
}
if (provider->getIsSettingFinal(setting.getKey())) {
return value;
}
}
return value;
}
void SettingsProviderHierachy::storeSetting(const Setting<std::string>& setting, const std::string& settingValue) {
if (!getIsSettingFinal(setting.getKey())) {
getWritableProvider()->storeSetting(setting, settingValue);
}
}
bool SettingsProviderHierachy::getSetting(const Setting<bool>& setting) {
bool value = setting.getDefaultValue();
- foreach (SettingsProvider* provider, providers_) {
+ for (auto provider : providers_) {
bool providerSetting = provider->getSetting(setting);
if (provider->hasSetting(setting.getKey())) {
value = providerSetting;
if (provider->getIsSettingFinal(setting.getKey())) {
return providerSetting;
}
}
}
return value;
}
void SettingsProviderHierachy::storeSetting(const Setting<bool>& setting, const bool& settingValue) {
if (!getIsSettingFinal(setting.getKey())) {
getWritableProvider()->storeSetting(setting, settingValue);
}
}
int SettingsProviderHierachy::getSetting(const Setting<int>& setting) {
int value = setting.getDefaultValue();
- foreach (SettingsProvider* provider, providers_) {
+ for (auto provider : providers_) {
int providerSetting = provider->getSetting(setting);
if (provider->hasSetting(setting.getKey())) {
value = providerSetting;
if (provider->getIsSettingFinal(setting.getKey())) {
return providerSetting;
}
}
}
return value;
}
void SettingsProviderHierachy::storeSetting(const Setting<int>& setting, const int& settingValue) {
if (!getIsSettingFinal(setting.getKey())) {
getWritableProvider()->storeSetting(setting, settingValue);
}
}
std::vector<std::string> SettingsProviderHierachy::getAvailableProfiles() {
/* Always pull profiles from the topmost */
return getWritableProvider()->getAvailableProfiles();
}
void SettingsProviderHierachy::createProfile(const std::string& profile) {
return getWritableProvider()->createProfile(profile);
}
void SettingsProviderHierachy::removeProfile(const std::string& profile) {
return getWritableProvider()->removeProfile(profile);
}
bool SettingsProviderHierachy::getIsSettingFinal(const std::string& settingPath) {
bool isFinal = false;
- foreach (SettingsProvider* provider, providers_) {
+ for (auto provider : providers_) {
isFinal |= provider->getIsSettingFinal(settingPath);
}
return isFinal;
}
SettingsProvider* SettingsProviderHierachy::getWritableProvider() {
return providers_.back();
}
void SettingsProviderHierachy::addProviderToTopOfStack(SettingsProvider* provider) {
providers_.push_back(provider);
provider->onSettingChanged.connect(onSettingChanged);
}
}
diff --git a/Swift/Controllers/ShowProfileController.cpp b/Swift/Controllers/ShowProfileController.cpp
index add6e73..b379141 100644
--- a/Swift/Controllers/ShowProfileController.cpp
+++ b/Swift/Controllers/ShowProfileController.cpp
@@ -1,64 +1,62 @@
/*
* Copyright (c) 2012 Tobias Markmann
* Licensed under the simplified BSD license.
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
/*
* Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/Controllers/ShowProfileController.h>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
-#include <Swiften/Base/foreach.h>
#include <Swiften/VCards/VCardManager.h>
#include <Swift/Controllers/UIEvents/ShowProfileForRosterItemUIEvent.h>
#include <Swift/Controllers/UIEvents/UIEventStream.h>
#include <Swift/Controllers/UIInterfaces/ProfileWindowFactory.h>
namespace Swift {
ShowProfileController::ShowProfileController(VCardManager* vcardManager, ProfileWindowFactory* profileWindowFactory, UIEventStream* uiEventStream) : vcardManager(vcardManager), profileWindowFactory(profileWindowFactory), uiEventStream(uiEventStream) {
uiEventStream->onUIEvent.connect(boost::bind(&ShowProfileController::handleUIEvent, this, _1));
vcardManager->onVCardChanged.connect(boost::bind(&ShowProfileController::handleVCardChanged, this, _1, _2));
}
ShowProfileController::~ShowProfileController() {
- typedef std::pair<JID, ProfileWindow*> JIDProfileWindowPair;
- foreach(const JIDProfileWindowPair& jidWndPair, openedProfileWindows) {
+ for (const auto& jidWndPair : openedProfileWindows) {
jidWndPair.second->onWindowAboutToBeClosed.disconnect(boost::bind(&ShowProfileController::handleProfileWindowAboutToBeClosed, this, _1));
delete jidWndPair.second;
}
vcardManager->onVCardChanged.disconnect(boost::bind(&ShowProfileController::handleVCardChanged, this, _1, _2));
uiEventStream->onUIEvent.disconnect(boost::bind(&ShowProfileController::handleUIEvent, this, _1));
}
void ShowProfileController::handleUIEvent(UIEvent::ref event) {
ShowProfileForRosterItemUIEvent::ref showProfileEvent = std::dynamic_pointer_cast<ShowProfileForRosterItemUIEvent>(event);
if (!showProfileEvent) {
return;
}
if (openedProfileWindows.find(showProfileEvent->getJID()) == openedProfileWindows.end()) {
ProfileWindow* newProfileWindow = profileWindowFactory->createProfileWindow();
newProfileWindow->setJID(showProfileEvent->getJID());
newProfileWindow->onWindowAboutToBeClosed.connect(boost::bind(&ShowProfileController::handleProfileWindowAboutToBeClosed, this, _1));
openedProfileWindows[showProfileEvent->getJID()] = newProfileWindow;
VCard::ref vcard = vcardManager->getVCardAndRequestWhenNeeded(showProfileEvent->getJID(), boost::posix_time::minutes(5));
if (vcard) {
newProfileWindow->setVCard(vcard);
} else {
newProfileWindow->setProcessing(true);
}
newProfileWindow->show();
} else {
openedProfileWindows[showProfileEvent->getJID()]->show();
}
}
diff --git a/Swift/Controllers/Storages/AvatarFileStorage.cpp b/Swift/Controllers/Storages/AvatarFileStorage.cpp
index cded945..a103920 100644
--- a/Swift/Controllers/Storages/AvatarFileStorage.cpp
+++ b/Swift/Controllers/Storages/AvatarFileStorage.cpp
@@ -1,45 +1,44 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/Controllers/Storages/AvatarFileStorage.h>
#include <iostream>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <Swiften/Base/String.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Crypto/CryptoProvider.h>
#include <Swiften/StringCodecs/Hexify.h>
namespace Swift {
AvatarFileStorage::AvatarFileStorage(const boost::filesystem::path& avatarsDir, const boost::filesystem::path& avatarsFile, CryptoProvider* crypto) : avatarsDir(avatarsDir), avatarsFile(avatarsFile), crypto(crypto) {
if (boost::filesystem::exists(avatarsFile)) {
try {
boost::filesystem::ifstream file(avatarsFile);
std::string line;
if (file.is_open()) {
while (!file.eof()) {
getline(file, line);
std::pair<std::string, std::string> r = String::getSplittedAtFirst(line, ' ');
JID jid(r.second);
if (jid.isValid()) {
jidAvatars.insert(std::make_pair(jid, r.first));
}
else if (!r.first.empty() || !r.second.empty()) {
std::cerr << "Invalid entry in avatars file: " << r.second << std::endl;
}
}
}
}
catch (...) {
std::cerr << "Error reading avatars file" << std::endl;
}
}
}
diff --git a/Swift/Controllers/Storages/CertificateMemoryStorage.cpp b/Swift/Controllers/Storages/CertificateMemoryStorage.cpp
index 08c6ee7..545ca65 100644
--- a/Swift/Controllers/Storages/CertificateMemoryStorage.cpp
+++ b/Swift/Controllers/Storages/CertificateMemoryStorage.cpp
@@ -1,27 +1,25 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/Controllers/Storages/CertificateMemoryStorage.h>
-#include <Swiften/Base/foreach.h>
-
using namespace Swift;
CertificateMemoryStorage::CertificateMemoryStorage() {
}
bool CertificateMemoryStorage::hasCertificate(Certificate::ref certificate) const {
- foreach(Certificate::ref storedCert, certificates) {
+ for (auto&& storedCert : certificates) {
if (storedCert->toDER() == certificate->toDER()) {
return true;
}
}
return false;
}
void CertificateMemoryStorage::addCertificate(Certificate::ref certificate) {
certificates.push_back(certificate);
}
diff --git a/Swift/Controllers/Storages/VCardFileStorage.cpp b/Swift/Controllers/Storages/VCardFileStorage.cpp
index dbb6799..2fdadf6 100644
--- a/Swift/Controllers/Storages/VCardFileStorage.cpp
+++ b/Swift/Controllers/Storages/VCardFileStorage.cpp
@@ -1,46 +1,45 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/Controllers/Storages/VCardFileStorage.h>
#include <iostream>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <Swiften/Base/Path.h>
#include <Swiften/Base/String.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Crypto/CryptoProvider.h>
#include <Swiften/Elements/VCard.h>
#include <Swiften/Entity/GenericPayloadPersister.h>
#include <Swiften/JID/JID.h>
#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadParserTester.h>
#include <Swiften/Parser/PayloadParsers/VCardParser.h>
#include <Swiften/Serializer/PayloadSerializers/VCardSerializer.h>
#include <Swiften/StringCodecs/Hexify.h>
using namespace Swift;
typedef GenericPayloadPersister<VCard, VCardParser, VCardSerializer> VCardPersister;
VCardFileStorage::VCardFileStorage(boost::filesystem::path dir, CryptoProvider* crypto) : VCardStorage(crypto), vcardsPath(dir), crypto(crypto) {
cacheFile = vcardsPath / "phashes";
if (boost::filesystem::exists(cacheFile)) {
try {
boost::filesystem::ifstream file(cacheFile);
std::string line;
if (file.is_open()) {
while (!file.eof()) {
getline(file, line);
std::pair<std::string, std::string> r = String::getSplittedAtFirst(line, ' ');
JID jid(r.second);
if (jid.isValid()) {
photoHashes.insert(std::make_pair(jid, r.first));
}
else if (!r.first.empty() || !r.second.empty()) {
std::cerr << "Invalid entry in phashes file" << std::endl;
}
diff --git a/Swift/Controllers/UIInterfaces/ChatListWindow.h b/Swift/Controllers/UIInterfaces/ChatListWindow.h
index c84d130..dde596e 100644
--- a/Swift/Controllers/UIInterfaces/ChatListWindow.h
+++ b/Swift/Controllers/UIInterfaces/ChatListWindow.h
@@ -1,93 +1,91 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
#include <list>
#include <map>
#include <memory>
#include <set>
#include <boost/filesystem/path.hpp>
#include <boost/signals2.hpp>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Elements/StatusShow.h>
#include <Swiften/MUC/MUCBookmark.h>
namespace Swift {
class ChatListWindow {
public:
class Chat {
public:
Chat() : statusType(StatusShow::None), isMUC(false), unreadCount(0), isPrivateMessage(false) {}
Chat(const JID& jid, const std::string& chatName, const std::string& activity, int unreadCount, StatusShow::Type statusType, const boost::filesystem::path& avatarPath, bool isMUC, bool isPrivateMessage = false, const std::string& nick = "", const boost::optional<std::string> password = boost::optional<std::string>())
: jid(jid), chatName(chatName), activity(activity), statusType(statusType), isMUC(isMUC), nick(nick), password(password), unreadCount(unreadCount), avatarPath(avatarPath), isPrivateMessage(isPrivateMessage) {}
/** Assume that nicks and other transient features aren't important for equality */
bool operator==(const Chat& other) const {
if (impromptuJIDs.empty()) {
return jid.toBare() == other.jid.toBare()
&& isMUC == other.isMUC;
- } else { /* compare the chat occupant lists */
- typedef std::map<std::string, JID> JIDMap;
- foreach (const JIDMap::value_type& jid, impromptuJIDs) {
+ }
+ else { /* compare the chat occupant lists */
+ for (const auto& jid : impromptuJIDs) {
bool found = false;
- foreach (const JIDMap::value_type& otherJID, other.impromptuJIDs) {
+ for (const auto& otherJID : other.impromptuJIDs) {
if (jid.second.toBare() == otherJID.second.toBare()) {
found = true;
break;
}
}
if (!found) {
return false;
}
}
return true;
}
}
void setUnreadCount(int unread) {
unreadCount = unread;
}
void setStatusType(StatusShow::Type type) {
statusType = type;
}
void setAvatarPath(const boost::filesystem::path& path) {
avatarPath = path;
}
std::string getImpromptuTitle() const {
- typedef std::pair<std::string, JID> StringJIDPair;
std::string title;
- foreach(StringJIDPair pair, impromptuJIDs) {
+ for (auto& pair : impromptuJIDs) {
if (title.empty()) {
title += pair.first;
} else {
title += ", " + pair.first;
}
}
return title;
}
JID jid;
std::string chatName;
std::string activity;
StatusShow::Type statusType;
bool isMUC;
std::string nick;
boost::optional<std::string> password;
int unreadCount;
boost::filesystem::path avatarPath;
std::map<std::string, JID> impromptuJIDs;
bool isPrivateMessage;
};
virtual ~ChatListWindow();
virtual void setBookmarksEnabled(bool enabled) = 0;
virtual void addMUCBookmark(const MUCBookmark& bookmark) = 0;
virtual void addWhiteboardSession(const ChatListWindow::Chat& chat) = 0;
virtual void removeWhiteboardSession(const JID& jid) = 0;
virtual void removeMUCBookmark(const MUCBookmark& bookmark) = 0;
virtual void setRecents(const std::list<Chat>& recents) = 0;
virtual void setUnreadCount(int unread) = 0;
virtual void clearBookmarks() = 0;
diff --git a/Swift/Controllers/UnitTest/ContactSuggesterTest.cpp b/Swift/Controllers/UnitTest/ContactSuggesterTest.cpp
index 217a2f0..6ac51b2 100644
--- a/Swift/Controllers/UnitTest/ContactSuggesterTest.cpp
+++ b/Swift/Controllers/UnitTest/ContactSuggesterTest.cpp
@@ -1,130 +1,128 @@
/*
* Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <memory>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swiften/Base/foreach.h>
-
#include <Swift/Controllers/ContactSuggester.h>
using namespace Swift;
class ContactSuggesterTest : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE(ContactSuggesterTest);
CPPUNIT_TEST(equalityTest);
CPPUNIT_TEST(lexicographicalSortTest);
CPPUNIT_TEST(sortTest);
CPPUNIT_TEST_SUITE_END();
public:
std::vector<std::string> wordList() {
const std::string words[] = {
"abc",
"ab",
"bc",
"d"
};
return std::vector<std::string>(words, words+sizeof(words)/sizeof(*words));
}
std::vector<StatusShow::Type> statusList() {
StatusShow::Type types[] = {
StatusShow::Online,
StatusShow::Away,
StatusShow::FFC,
StatusShow::XA,
StatusShow::DND,
StatusShow::None
};
return std::vector<StatusShow::Type>(types, types+sizeof(types)/sizeof(*types));
}
std::vector<Contact::ref> contactList() {
std::vector<Contact::ref> contacts;
std::vector<std::string> words = wordList();
std::vector<StatusShow::Type> statuses = statusList();
- foreach (const std::string& name, words) {
- foreach (const std::string& jid, words) {
- foreach (const StatusShow::Type& status, statuses) {
+ for (const auto& name : words) {
+ for (const auto& jid : words) {
+ for (const auto& status : statuses) {
contacts.push_back(std::make_shared<Contact>(name, jid, status, ""));
}
}
}
return contacts;
}
/* a = a */
bool isReflexive(const boost::function<bool (const Contact::ref&, const Contact::ref&)>& comparitor) {
std::vector<Contact::ref> contacts = contactList();
- foreach (const Contact::ref& a, contacts) {
+ for (const auto& a : contacts) {
if (!comparitor(a, a)) {
return false;
}
}
return true;
}
/* a = b -> b = a */
bool isSymmetric(const boost::function<bool (const Contact::ref&, const Contact::ref&)>& comparitor) {
std::vector<Contact::ref> contacts = contactList();
- foreach (const Contact::ref& a, contacts) {
- foreach (const Contact::ref& b, contacts) {
+ for (const auto& a : contacts) {
+ for (const auto& b : contacts) {
if (comparitor(a, b)) {
if (!comparitor(b, a)) {
return false;
}
}
}
}
return true;
}
/* a = b && b = c -> a = c */
bool isTransitive(const boost::function<bool (const Contact::ref&, const Contact::ref&)>& comparitor) {
std::vector<Contact::ref> contacts = contactList();
- foreach (const Contact::ref& a, contacts) {
- foreach (const Contact::ref& b, contacts) {
- foreach (const Contact::ref& c, contacts) {
+ for (const auto& a : contacts) {
+ for (const auto& b : contacts) {
+ for (const auto& c : contacts) {
if (comparitor(a, b) && comparitor(b, c)) {
if (!comparitor(a, c)) {
return false;
}
}
}
}
}
return true;
}
void equalityTest() {
CPPUNIT_ASSERT(isReflexive(Contact::equalityPredicate));
CPPUNIT_ASSERT(isSymmetric(Contact::equalityPredicate));
CPPUNIT_ASSERT(isTransitive(Contact::equalityPredicate));
}
void lexicographicalSortTest() {
CPPUNIT_ASSERT(isTransitive(Contact::lexicographicalSortPredicate));
}
void sortTest() {
std::vector<std::string> words = wordList();
- foreach (const std::string& word, words) {
+ for (const auto& word : words) {
CPPUNIT_ASSERT(isTransitive(boost::bind(Contact::sortPredicate, _1, _2, word)));
}
}
};
CPPUNIT_TEST_SUITE_REGISTRATION(ContactSuggesterTest);
diff --git a/Swift/Controllers/WhiteboardManager.cpp b/Swift/Controllers/WhiteboardManager.cpp
index fab5380..37fe8e3 100644
--- a/Swift/Controllers/WhiteboardManager.cpp
+++ b/Swift/Controllers/WhiteboardManager.cpp
@@ -1,69 +1,66 @@
/*
* Copyright (c) 2012 Mateusz Piękos
* Licensed under the simplified BSD license.
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
/*
* Copyright (c) 2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/Controllers/WhiteboardManager.h>
#include <boost/bind.hpp>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Client/NickResolver.h>
#include <Swiften/Client/StanzaChannel.h>
#include <Swiften/Whiteboard/WhiteboardSessionManager.h>
#include <Swift/Controllers/UIEvents/AcceptWhiteboardSessionUIEvent.h>
#include <Swift/Controllers/UIEvents/CancelWhiteboardSessionUIEvent.h>
#include <Swift/Controllers/UIEvents/RequestWhiteboardUIEvent.h>
#include <Swift/Controllers/UIEvents/ShowWhiteboardUIEvent.h>
namespace Swift {
- typedef std::pair<JID, WhiteboardWindow*> JIDWhiteboardWindowPair;
-
WhiteboardManager::WhiteboardManager(WhiteboardWindowFactory* whiteboardWindowFactory, UIEventStream* uiEventStream, NickResolver* nickResolver, WhiteboardSessionManager* whiteboardSessionManager) : whiteboardWindowFactory_(whiteboardWindowFactory), uiEventStream_(uiEventStream), nickResolver_(nickResolver), whiteboardSessionManager_(whiteboardSessionManager) {
#ifdef SWIFT_EXPERIMENTAL_WB
whiteboardSessionManager_->onSessionRequest.connect(boost::bind(&WhiteboardManager::handleIncomingSession, this, _1));
#endif
uiEventConnection_ = uiEventStream_->onUIEvent.connect(boost::bind(&WhiteboardManager::handleUIEvent, this, _1));
}
WhiteboardManager::~WhiteboardManager() {
- foreach (JIDWhiteboardWindowPair whiteboardWindowPair, whiteboardWindows_) {
+ for (auto&& whiteboardWindowPair : whiteboardWindows_) {
delete whiteboardWindowPair.second;
}
}
WhiteboardWindow* WhiteboardManager::createNewWhiteboardWindow(const JID& contact, WhiteboardSession::ref session) {
WhiteboardWindow *window = whiteboardWindowFactory_->createWhiteboardWindow(session);
window->setName(nickResolver_->jidToNick(contact));
whiteboardWindows_[contact.toBare()] = window;
return window;
}
WhiteboardWindow* WhiteboardManager::findWhiteboardWindow(const JID& contact) {
if (whiteboardWindows_.find(contact.toBare()) == whiteboardWindows_.end()) {
return nullptr;
}
return whiteboardWindows_[contact.toBare()];
}
void WhiteboardManager::handleUIEvent(std::shared_ptr<UIEvent> event) {
std::shared_ptr<RequestWhiteboardUIEvent> requestWhiteboardEvent = std::dynamic_pointer_cast<RequestWhiteboardUIEvent>(event);
if (requestWhiteboardEvent) {
requestSession(requestWhiteboardEvent->getContact());
}
std::shared_ptr<AcceptWhiteboardSessionUIEvent> sessionAcceptEvent = std::dynamic_pointer_cast<AcceptWhiteboardSessionUIEvent>(event);
if (sessionAcceptEvent) {
acceptSession(sessionAcceptEvent->getContact());
}
std::shared_ptr<CancelWhiteboardSessionUIEvent> sessionCancelEvent = std::dynamic_pointer_cast<CancelWhiteboardSessionUIEvent>(event);
if (sessionCancelEvent) {
cancelSession(sessionCancelEvent->getContact());
diff --git a/Swift/Controllers/XMPPEvents/EventController.cpp b/Swift/Controllers/XMPPEvents/EventController.cpp
index f0debb9..f8fb192 100644
--- a/Swift/Controllers/XMPPEvents/EventController.cpp
+++ b/Swift/Controllers/XMPPEvents/EventController.cpp
@@ -1,73 +1,71 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/Controllers/XMPPEvents/EventController.h>
#include <algorithm>
#include <boost/bind.hpp>
#include <boost/numeric/conversion/cast.hpp>
-#include <Swiften/Base/foreach.h>
-
#include <Swift/Controllers/XMPPEvents/ErrorEvent.h>
#include <Swift/Controllers/XMPPEvents/IncomingFileTransferEvent.h>
#include <Swift/Controllers/XMPPEvents/MUCInviteEvent.h>
#include <Swift/Controllers/XMPPEvents/MessageEvent.h>
#include <Swift/Controllers/XMPPEvents/SubscriptionRequestEvent.h>
namespace Swift {
EventController::EventController() {
}
EventController::~EventController() {
- foreach(std::shared_ptr<StanzaEvent> event, events_) {
+ for (auto&& event : events_) {
event->onConclusion.disconnect(boost::bind(&EventController::handleEventConcluded, this, event));
}
}
void EventController::handleIncomingEvent(std::shared_ptr<StanzaEvent> sourceEvent) {
std::shared_ptr<MessageEvent> messageEvent = std::dynamic_pointer_cast<MessageEvent>(sourceEvent);
std::shared_ptr<SubscriptionRequestEvent> subscriptionEvent = std::dynamic_pointer_cast<SubscriptionRequestEvent>(sourceEvent);
std::shared_ptr<ErrorEvent> errorEvent = std::dynamic_pointer_cast<ErrorEvent>(sourceEvent);
std::shared_ptr<MUCInviteEvent> mucInviteEvent = std::dynamic_pointer_cast<MUCInviteEvent>(sourceEvent);
std::shared_ptr<IncomingFileTransferEvent> incomingFileTransferEvent = std::dynamic_pointer_cast<IncomingFileTransferEvent>(sourceEvent);
/* If it's a duplicate subscription request, remove the previous request first */
if (subscriptionEvent) {
EventList existingEvents(events_);
- foreach(std::shared_ptr<StanzaEvent> existingEvent, existingEvents) {
+ for (auto&& existingEvent : existingEvents) {
std::shared_ptr<SubscriptionRequestEvent> existingSubscriptionEvent = std::dynamic_pointer_cast<SubscriptionRequestEvent>(existingEvent);
if (existingSubscriptionEvent) {
if (existingSubscriptionEvent->getJID() == subscriptionEvent->getJID()) {
existingEvent->conclude();
}
}
}
}
if ((messageEvent && messageEvent->isReadable()) || subscriptionEvent || errorEvent || mucInviteEvent || incomingFileTransferEvent) {
events_.push_back(sourceEvent);
sourceEvent->onConclusion.connect(boost::bind(&EventController::handleEventConcluded, this, sourceEvent));
onEventQueueLengthChange(boost::numeric_cast<int>(events_.size()));
onEventQueueEventAdded(sourceEvent);
if (sourceEvent->getConcluded()) {
handleEventConcluded(sourceEvent);
}
}
}
void EventController::handleEventConcluded(std::shared_ptr<StanzaEvent> event) {
event->onConclusion.disconnect(boost::bind(&EventController::handleEventConcluded, this, event));
events_.erase(std::remove(events_.begin(), events_.end(), event), events_.end());
onEventQueueLengthChange(boost::numeric_cast<int>(events_.size()));
}
void EventController::disconnectAll() {
onEventQueueLengthChange.disconnect_all_slots();
onEventQueueEventAdded.disconnect_all_slots();
}
diff --git a/Swift/QtUI/ChatList/ChatListGroupItem.h b/Swift/QtUI/ChatList/ChatListGroupItem.h
index 427f00b..a9bb9b1 100644
--- a/Swift/QtUI/ChatList/ChatListGroupItem.h
+++ b/Swift/QtUI/ChatList/ChatListGroupItem.h
@@ -1,45 +1,42 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
#include <QList>
-#include <Swiften/Base/foreach.h>
-
#include <Swift/QtUI/ChatList/ChatListItem.h>
namespace Swift {
class ChatListGroupItem : public ChatListItem {
public:
ChatListGroupItem(const QString& name, ChatListGroupItem* parent, bool sorted = true) : ChatListItem(parent), name_(name), sorted_(sorted) {}
virtual ~ChatListGroupItem() {clear();}
void addItem(ChatListItem* item) {items_.push_back(item); if (sorted_) {qStableSort(items_.begin(), items_.end(), pointerItemLessThan);}}
void remove(int index) {items_.removeAt(index);}
int rowCount() {return items_.size();}
ChatListItem* item(int i) {return items_[i];}
int row(ChatListItem* item) {return items_.indexOf(item);}
QVariant data(int role) const {return (role == Qt::DisplayRole) ? name_ : QVariant();}
void clear() {
- foreach (ChatListItem* item, items_) {
+ for (auto item : items_) {
delete item;
}
items_.clear();
}
-
private:
static bool pointerItemLessThan(const ChatListItem* first, const ChatListItem* second) {
QString myName = first->data(Qt::DisplayRole).toString().toLower();
QString theirName = second->data(Qt::DisplayRole).toString().toLower();
return myName < theirName;
}
QString name_;
QList<ChatListItem*> items_;
bool sorted_;
};
}
diff --git a/Swift/QtUI/ChatList/ChatListModel.cpp b/Swift/QtUI/ChatList/ChatListModel.cpp
index e5e8963..416b786 100644
--- a/Swift/QtUI/ChatList/ChatListModel.cpp
+++ b/Swift/QtUI/ChatList/ChatListModel.cpp
@@ -69,87 +69,86 @@ void ChatListModel::removeMUCBookmark(const Swift::MUCBookmark& bookmark) {
mucBookmarks_->remove(i);
endRemoveRows();
break;
}
}
}
void ChatListModel::addWhiteboardSession(const ChatListWindow::Chat& chat) {
beginInsertRows(whiteboardsIndex_, 0, whiteboards_->rowCount());
whiteboards_->addItem(new ChatListWhiteboardItem(chat, whiteboards_));
endInsertRows();
}
void ChatListModel::removeWhiteboardSession(const JID& jid) {
for (int i = 0; i < whiteboards_->rowCount(); i++) {
ChatListWhiteboardItem* item = dynamic_cast<ChatListWhiteboardItem*>(whiteboards_->item(i));
if (item->getChat().jid == jid) {
beginRemoveRows(whiteboardsIndex_, i, i+1);
whiteboards_->remove(i);
endRemoveRows();
break;
}
}
}
void ChatListModel::setRecents(const std::list<ChatListWindow::Chat>& recents) {
beginRemoveRows(recentsIndex_, 0, recents_->rowCount());
recents_->clear();
endRemoveRows();
beginInsertRows(recentsIndex_, 0, recents.size());
- foreach (const ChatListWindow::Chat chat, recents) {
+ for (const auto& chat : recents) {
recents_->addItem(new ChatListRecentItem(chat, recents_));
//whiteboards_->addItem(new ChatListRecentItem(chat, whiteboards_));
}
endInsertRows();
}
QMimeData* ChatListModel::mimeData(const QModelIndexList& indexes) const {
QMimeData* data = QAbstractItemModel::mimeData(indexes);
ChatListRecentItem *item = dynamic_cast<ChatListRecentItem*>(getItemForIndex(indexes.first()));
if (item == nullptr) {
return data;
}
QByteArray itemData;
QDataStream dataStream(&itemData, QIODevice::WriteOnly);
const ChatListWindow::Chat& chat = item->getChat();
QString mimeType = "application/vnd.swift.contact-jid-list";
if (!chat.impromptuJIDs.size()) {
if (chat.isMUC) {
mimeType = "application/vnd.swift.contact-jid-muc";
}
dataStream << P2QSTRING(chat.jid.toString());
} else {
- typedef std::map<std::string, JID> JIDMap;
- foreach (const JIDMap::value_type& jid, chat.impromptuJIDs) {
+ for (const auto& jid : chat.impromptuJIDs) {
dataStream << P2QSTRING(jid.second.toString());
}
}
data->setData(mimeType, itemData);
return data;
}
const ChatListMUCItem* ChatListModel::getChatListMUCItem(const JID& roomJID) const {
const ChatListMUCItem* mucItem = nullptr;
for (int i = 0; i < mucBookmarks_->rowCount(); i++) {
ChatListMUCItem* item = dynamic_cast<ChatListMUCItem*>(mucBookmarks_->item(i));
if (item->getBookmark().getRoom() == roomJID) {
mucItem = item;
break;
}
}
return mucItem;
}
int ChatListModel::columnCount(const QModelIndex& /*parent*/) const {
return 1;
}
ChatListItem* ChatListModel::getItemForIndex(const QModelIndex& index) const {
return index.isValid() ? static_cast<ChatListItem*>(index.internalPointer()) : nullptr;
}
QVariant ChatListModel::data(const QModelIndex& index, int role) const {
ChatListItem* item = getItemForIndex(index);
diff --git a/Swift/QtUI/ChatList/QtChatListWindow.cpp b/Swift/QtUI/ChatList/QtChatListWindow.cpp
index 3fe462a..3caed57 100644
--- a/Swift/QtUI/ChatList/QtChatListWindow.cpp
+++ b/Swift/QtUI/ChatList/QtChatListWindow.cpp
@@ -153,61 +153,61 @@ void QtChatListWindow::handleAddBookmarkFromRecents() {
MUCBookmark bookmark(chat.jid, chat.jid.toBare().toString());
bookmark.setNick(chat.nick);
bookmark.setPassword(chat.password);
eventStream_->send(std::make_shared<AddMUCBookmarkUIEvent>(bookmark));
}
}
void QtChatListWindow::handleAddBookmark() {
(new QtAddBookmarkWindow(eventStream_))->show();
}
void QtChatListWindow::handleEditBookmark() {
const ChatListMUCItem* mucItem = dynamic_cast<const ChatListMUCItem*>(contextMenuItem_);
if (!mucItem) return;
QtEditBookmarkWindow* window = new QtEditBookmarkWindow(eventStream_, mucItem->getBookmark());
window->show();
}
void QtChatListWindow::dragEnterEvent(QDragEnterEvent *event) {
if (event->mimeData()->hasUrls() && event->mimeData()->urls().size() == 1) {
event->acceptProposedAction();
}
}
void QtChatListWindow::contextMenuEvent(QContextMenuEvent* event) {
QModelIndex index = indexAt(event->pos());
ChatListItem* baseItem = index.isValid() ? static_cast<ChatListItem*>(index.internalPointer()) : nullptr;
contextMenuItem_ = baseItem;
- foreach(QAction* action, onlineOnlyActions_) {
+ for (auto action : onlineOnlyActions_) {
action->setEnabled(isOnline_);
}
if (!baseItem) {
emptyMenu_->exec(QCursor::pos());
return;
}
ChatListMUCItem* mucItem = dynamic_cast<ChatListMUCItem*>(baseItem);
if (mucItem) {
if (!bookmarksEnabled_) {
return;
}
mucMenu_->exec(QCursor::pos());
return;
}
ChatListRecentItem* recentItem = dynamic_cast<ChatListRecentItem*>(baseItem);
if (recentItem) {
const ChatListWindow::Chat& chat = recentItem->getChat();
if (chat.isMUC) {
QMenu mucRecentsMenu;
QAction* bookmarkAction = nullptr;
const ChatListMUCItem* mucItem = model_->getChatListMUCItem(chat.jid);
if (mucItem) {
contextMenuItem_ = mucItem;
bookmarkAction = mucRecentsMenu.addAction(tr("Edit Bookmark"), this, SLOT(handleEditBookmark()));
}
else {
bookmarkAction = mucRecentsMenu.addAction(tr("Add to Bookmarks"), this, SLOT(handleAddBookmarkFromRecents()));
diff --git a/Swift/QtUI/ChatSnippet.cpp b/Swift/QtUI/ChatSnippet.cpp
index 0369d0a..87dfac2 100644
--- a/Swift/QtUI/ChatSnippet.cpp
+++ b/Swift/QtUI/ChatSnippet.cpp
@@ -21,61 +21,61 @@ ChatSnippet::~ChatSnippet() {
QString ChatSnippet::timeToEscapedString(const QDateTime& time) {
QDate now(QDate::currentDate());
QString date = "";
if (time.date().daysTo(now) > 0) {
date = "ddd ";
}
if (time.date().month() != now.month()) {
date = date + "MMMM ";
}
if (time.date().daysTo(now) > 6) {
date = date + "d ";
}
if (time.date().year() != now.year()) {
date = date + "yy ";
}
date += "h:mm";
return escape(time.toString(date));
}
QString ChatSnippet::wrapResizable(const QString& text) {
return "<span class='swift_resizable'>" + text + "</span>";
}
QString ChatSnippet::directionToCSS(Direction direction) {
return direction == RTL ? QString("rtl") : QString("ltr");
}
ChatSnippet::Direction ChatSnippet::getDirection(const ChatWindow::ChatMessage& message) {
std::shared_ptr<ChatWindow::ChatTextMessagePart> textPart;
std::string text = "";
- foreach (std::shared_ptr<ChatWindow::ChatMessagePart> part, message.getParts()) {
+ for (auto&& part : message.getParts()) {
if ((textPart = std::dynamic_pointer_cast<ChatWindow::ChatTextMessagePart>(part))) {
text = textPart->text;
break;
}
}
return getDirection(text);
}
ChatSnippet::Direction ChatSnippet::getDirection(const std::string& message) {
return getDirection(P2QSTRING(message));
}
ChatSnippet::Direction ChatSnippet::getDirection(const QString& message) {
/*
for (int i = 0; i < message.size(); ++i) {
switch (message.at(i).direction()) {
case QChar::DirL:
case QChar::DirLRE:
case QChar::DirLRO:
return ChatSnippet::LTR;
case QChar::DirR:
case QChar::DirAL:
case QChar::DirRLE:
case QChar::DirRLO:
return ChatSnippet::RTL;
case QChar::DirEN:
case QChar::DirES:
case QChar::DirET:
case QChar::DirAN:
case QChar::DirCS:
diff --git a/Swift/QtUI/ChatSnippet.h b/Swift/QtUI/ChatSnippet.h
index f715cbf..d8bc209 100644
--- a/Swift/QtUI/ChatSnippet.h
+++ b/Swift/QtUI/ChatSnippet.h
@@ -1,45 +1,43 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
#include <memory>
#include <QDateTime>
#include <QString>
-#include <Swiften/Base/foreach.h>
-
#include <Swift/Controllers/UIInterfaces/ChatWindow.h>
#include <Swift/QtUI/QtChatTheme.h>
namespace Swift {
class ChatSnippet {
public:
enum Direction {
RTL,
LTR
};
ChatSnippet(bool appendToPrevious);
virtual ~ChatSnippet();
virtual const QString& getContent() const = 0;
virtual QString getContinuationElementID() const { return ""; }
std::shared_ptr<ChatSnippet> getContinuationFallbackSnippet() const {return continuationFallback_;}
bool getAppendToPrevious() const {
return appendToPrevious_;
}
static QString escape(const QString& original) {
QString result(original);
result.replace("%message%", "&#37;message&#37;");
result.replace("%sender%", "&#37;sender&#37;");
result.replace("%wrapped_sender%", "&#37;wrapped_sender&#37;");
result.replace("%time%", "%&#37;time&#37;");
diff --git a/Swift/QtUI/CocoaUIHelpers.mm b/Swift/QtUI/CocoaUIHelpers.mm
index 3ffa72c..1f4ffc1 100644
--- a/Swift/QtUI/CocoaUIHelpers.mm
+++ b/Swift/QtUI/CocoaUIHelpers.mm
@@ -1,53 +1,51 @@
/*
* Copyright (c) 2012 Tobias Markmann
* Licensed under the simplified BSD license.
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
/*
* Copyright (c) 2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include "CocoaUIHelpers.h"
#include <memory>
+
#include <boost/type_traits.hpp>
#include <Cocoa/Cocoa.h>
#include <Security/Security.h>
#include <SecurityInterface/SFCertificatePanel.h>
-#include <Swiften/Base/foreach.h>
-
#pragma GCC diagnostic ignored "-Wold-style-cast"
namespace Swift {
void CocoaUIHelpers::displayCertificateChainAsSheet(QWidget* parent, const std::vector<Certificate::ref>& chain) {
NSWindow* parentWindow = [((NSView*)parent->winId()) window];
NSMutableArray* certificates = [[NSMutableArray alloc] init];
- foreach(Certificate::ref cert, chain) {
+ for (auto&& cert : chain) {
// convert chain to SecCertificateRef
ByteArray certAsDER = cert->toDER();
std::shared_ptr<boost::remove_pointer<CFDataRef>::type> certData(CFDataCreate(nullptr, certAsDER.data(), certAsDER.size()), CFRelease);
std::shared_ptr<OpaqueSecCertificateRef> macCert(SecCertificateCreateWithData(nullptr, certData.get()), CFRelease);
// add to NSMutable array
[certificates addObject: (id)macCert.get()];
}
-
SFCertificatePanel* panel = [[SFCertificatePanel alloc] init];
//[panel setPolicies:(id)policies.get()];
[panel beginSheetForWindow:parentWindow modalDelegate:nil didEndSelector:nullptr contextInfo:nullptr certificates:certificates showGroup:YES];
[certificates release];
}
void CocoaUIHelpers::sendCocoaApplicationWillTerminateNotification() {
[[NSNotificationCenter defaultCenter] postNotificationName:@"NSApplicationWillTerminateNotification" object:nil];
}
}
diff --git a/Swift/QtUI/EventViewer/EventModel.cpp b/Swift/QtUI/EventViewer/EventModel.cpp
index e242003..5b97b3e 100644
--- a/Swift/QtUI/EventViewer/EventModel.cpp
+++ b/Swift/QtUI/EventViewer/EventModel.cpp
@@ -1,55 +1,55 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/QtUI/EventViewer/EventModel.h>
#include <Swiften/Base/Log.h>
namespace Swift {
namespace {
const int inactiveEventsLimit = 50;
}
EventModel::EventModel() {
}
EventModel::~EventModel() {
- foreach (QtEvent* event, activeEvents_) {
+ for (auto event : activeEvents_) {
delete event;
}
- foreach (QtEvent* event, inactiveEvents_) {
+ for (auto event : inactiveEvents_) {
delete event;
}
}
QtEvent* EventModel::getItem(int row) const {
QtEvent* event = nullptr;
if (row < activeEvents_.size()) {
event = activeEvents_[row];
}
else {
int inactiveRow = row - activeEvents_.size();
if (inactiveRow < inactiveEvents_.size()) {
event = inactiveEvents_[inactiveRow];
}
else {
SWIFT_LOG(error) << "Misbehaving EventModel requests row index outside of range";
}
}
return event;
}
int EventModel::getNewEventCount() {
return activeEvents_.size();
}
QVariant EventModel::data(const QModelIndex& index, int role) const {
if (!index.isValid()) {
return QVariant();
}
QtEvent* item = getItem(index.row());
diff --git a/Swift/QtUI/QtAdHocCommandWindow.cpp b/Swift/QtUI/QtAdHocCommandWindow.cpp
index 6b982b1..65dac91 100644
--- a/Swift/QtUI/QtAdHocCommandWindow.cpp
+++ b/Swift/QtUI/QtAdHocCommandWindow.cpp
@@ -77,98 +77,98 @@ void QtAdHocCommandWindow::setOnline(bool online) {
nextButton_->setEnabled(false);
backButton_->setEnabled(false);
completeButton_->setEnabled(false);
errorLabel_->setVisible(true);
}
}
void QtAdHocCommandWindow::closeEvent(QCloseEvent*) {
onClosing();
}
void QtAdHocCommandWindow::handleCancelClicked() {
command_->cancel();
close();
}
void QtAdHocCommandWindow::handlePrevClicked() {
command_->goBack();
}
void QtAdHocCommandWindow::handleNextClicked() {
command_->goNext(formWidget_ ? formWidget_->getCompletedForm() : Form::ref());
}
void QtAdHocCommandWindow::handleCompleteClicked() {
command_->complete(formWidget_ ? formWidget_->getCompletedForm() : Form::ref());
}
void QtAdHocCommandWindow::handleNextStageReceived(Command::ref command) {
QString notes;
- foreach (Command::Note note, command->getNotes()) {
+ for (const auto& note : command->getNotes()) {
if (!notes.isEmpty()) {
notes += "\n";
}
QString qNote(P2QSTRING(note.note));
switch (note.type) {
case Command::Note::Error: notes += tr("Error: %1").arg(qNote); break;
case Command::Note::Warn: notes += tr("Warning: %1").arg(qNote); break;
case Command::Note::Info: notes += qNote; break;
}
}
label_->setText(notes);
if (command->getForm()) {
setForm(command->getForm());
} else {
setNoForm(notes.isEmpty());
}
setAvailableActions(command);
}
void QtAdHocCommandWindow::handleError(ErrorPayload::ref /*error*/) {
nextButton_->setEnabled(false);
backButton_->setEnabled(false);
completeButton_->setEnabled(false);
label_->setText(tr("Error executing command"));
}
void QtAdHocCommandWindow::setForm(Form::ref form) {
form_ = form;
delete formWidget_;
formWidget_ = new QtFormWidget(form, this);
layout_->insertWidget(FormLayoutIndex, formWidget_);
show();
}
void QtAdHocCommandWindow::setNoForm(bool andHide) {
form_.reset();
delete formWidget_;
formWidget_ = nullptr;
resize(minimumSize());
setVisible(!andHide);
}
typedef std::pair<Command::Action, QPushButton*> ActionButton;
void QtAdHocCommandWindow::setAvailableActions(Command::ref /*commandResult*/) {
okButton_->show();
okButton_->setEnabled(true);
- foreach (ActionButton pair, actions_) {
+ for (auto&& pair : actions_) {
OutgoingAdHocCommandSession::ActionState state = command_->getActionState(pair.first);
if (state & OutgoingAdHocCommandSession::Present) {
okButton_->hide();
okButton_->setEnabled(false);
pair.second->show();
}
else {
pair.second->hide();
}
if (state & OutgoingAdHocCommandSession::Enabled) {
pair.second->setEnabled(true);
}
else {
pair.second->setEnabled(false);
}
}
}
}
diff --git a/Swift/QtUI/QtAffiliationEditor.cpp b/Swift/QtUI/QtAffiliationEditor.cpp
index 980b26a..92b6aff 100644
--- a/Swift/QtUI/QtAffiliationEditor.cpp
+++ b/Swift/QtUI/QtAffiliationEditor.cpp
@@ -10,61 +10,61 @@
#include <QListWidgetItem>
#include <Swift/QtUI/QtSwiftUtil.h>
namespace Swift {
QtAffiliationEditor::QtAffiliationEditor(QWidget* parent) : QDialog(parent){
ui_.setupUi(this);
setAttribute(Qt::WA_DeleteOnClose);
connect(ui_.affiliation, SIGNAL(currentIndexChanged(int)), this, SLOT(handleCurrentIndexChanged(int)));
connect(ui_.addJID, SIGNAL(clicked()), this, SLOT(handleAddClicked()));
connect(ui_.removeJID, SIGNAL(clicked()), this, SLOT(handleRemoveClicked()));
}
QtAffiliationEditor::~QtAffiliationEditor() {
}
void QtAffiliationEditor::setAffiliations(MUCOccupant::Affiliation affiliation, const std::vector<JID>& jids) {
affiliations_[affiliation] = jids;
if (affiliationFromIndex(ui_.affiliation->currentIndex()) == affiliation) {
handleCurrentIndexChanged(ui_.affiliation->currentIndex());
}
}
const std::vector<std::pair<MUCOccupant::Affiliation, JID> >& QtAffiliationEditor::getChanges() const {
return changes_;
}
void QtAffiliationEditor::handleCurrentIndexChanged(int index) {
ui_.list->clear();
- foreach (const JID& jid, affiliations_[affiliationFromIndex(index)]) {
+ for (const auto& jid : affiliations_[affiliationFromIndex(index)]) {
ui_.list->addItem(P2QSTRING(jid.toString()));
}
}
void QtAffiliationEditor::handleAddClicked() {
bool ok = false;
JID jid = JID(Q2PSTRING(QInputDialog::getText(this, tr("Add User"), tr("Added User's Address:"), QLineEdit::Normal, "", &ok)));
if (ok && jid.isValid()) {
//FIXME: validation
MUCOccupant::Affiliation affiliation = affiliationFromIndex(ui_.affiliation->currentIndex());
changes_.push_back(ChangePair(affiliation, jid));
ui_.list->addItem(P2QSTRING(jid.toString()));
affiliations_[affiliation].push_back(jid);
}
}
void QtAffiliationEditor::handleRemoveClicked() {
QListWidgetItem* item = ui_.list->currentItem();
if (item) {
JID jid(Q2PSTRING(item->text()));
changes_.push_back(ChangePair(MUCOccupant::NoAffiliation, jid));
std::vector<JID>& jids = affiliations_[affiliationFromIndex(ui_.affiliation->currentIndex())];
jids.erase(std::remove(jids.begin(), jids.end(), jid), jids.end());
handleCurrentIndexChanged(ui_.affiliation->currentIndex());
}
}
MUCOccupant::Affiliation QtAffiliationEditor::affiliationFromIndex(int affiliation) {
switch (affiliation) {
case 0: return MUCOccupant::Owner;
diff --git a/Swift/QtUI/QtBlockListEditorWindow.cpp b/Swift/QtUI/QtBlockListEditorWindow.cpp
index 9e13943..30c939f 100644
--- a/Swift/QtUI/QtBlockListEditorWindow.cpp
+++ b/Swift/QtUI/QtBlockListEditorWindow.cpp
@@ -1,53 +1,52 @@
/*
* Copyright (c) 2013 Tobias Markmann
* Licensed under the simplified BSD license.
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
/*
* Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/QtUI/QtBlockListEditorWindow.h>
#include <boost/bind.hpp>
#include <QLineEdit>
#include <QMovie>
#include <QShortcut>
#include <QStyledItemDelegate>
#include <QValidator>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Client/ClientBlockListManager.h>
#include <Swiften/JID/JID.h>
#include <Swift/QtUI/QtSwiftUtil.h>
#include <Swift/QtUI/QtUtilities.h>
#include <Swift/QtUI/ui_QtBlockListEditorWindow.h>
namespace Swift {
class QtJIDValidator : public QValidator {
public:
QtJIDValidator(QObject* parent) : QValidator(parent) {}
virtual ~QtJIDValidator() {}
virtual QValidator::State validate(QString& input, int&) const {
return JID(Q2PSTRING(input)).isValid() ? Acceptable : Intermediate;
}
};
class QtJIDValidatedItemDelegate : public QItemDelegate {
public:
QtJIDValidatedItemDelegate(QObject* parent) : QItemDelegate(parent) {}
virtual ~QtJIDValidatedItemDelegate() {}
virtual QWidget* createEditor(QWidget* parent, const QStyleOptionViewItem&, const QModelIndex&) const {
QLineEdit *editor = new QLineEdit(parent);
editor->setValidator(new QtJIDValidator(editor));
return editor;
}
void setEditorData(QWidget *editor, const QModelIndex &index) const {
@@ -131,61 +130,61 @@ void QtBlockListEditorWindow::handleItemChanged(QTreeWidgetItem *item, int) {
// check for empty rows and add an empty one so the user can add items
bool hasEmptyRow = false;
for( int i = 0; i < ui->blockListTreeWidget->topLevelItemCount(); ++i ) {
QTreeWidgetItem* row = ui->blockListTreeWidget->topLevelItem(i);
if (row->text(0) == freshBlockListTemplate) {
hasEmptyRow = true;
}
else if (row->text(0).isEmpty()) {
ui->blockListTreeWidget->removeItemWidget(row, 0);
}
}
if (!hasEmptyRow) {
QTreeWidgetItem* item = new QTreeWidgetItem(QStringList(freshBlockListTemplate) << "x");
item->setFlags(item->flags() | Qt::ItemIsEditable);
ui->blockListTreeWidget->addTopLevelItem(item);
}
if (!item) {
ui->blockListTreeWidget->setCurrentItem(ui->blockListTreeWidget->topLevelItem(0));
}
}
void QtBlockListEditorWindow::applyChanges() {
onSetNewBlockList(getCurrentBlockList());
}
void QtBlockListEditorWindow::setCurrentBlockList(const std::vector<JID> &blockedJIDs) {
ui->blockListTreeWidget->clear();
- foreach(const JID& jid, blockedJIDs) {
+ for (const auto& jid : blockedJIDs) {
QTreeWidgetItem* item = new QTreeWidgetItem(QStringList(P2QSTRING(jid.toString())) << "");
item->setFlags(item->flags() | Qt::ItemIsEditable);
ui->blockListTreeWidget->addTopLevelItem(item);
}
handleItemChanged(nullptr,0);
}
void QtBlockListEditorWindow::setBusy(bool isBusy) {
if (isBusy) {
ui->throbberLabel->movie()->start();
ui->throbberLabel->show();
ui->blockListTreeWidget->setEnabled(false);
ui->savePushButton->setEnabled(false);
} else {
ui->throbberLabel->movie()->stop();
ui->throbberLabel->hide();
ui->blockListTreeWidget->setEnabled(true);
ui->savePushButton->setEnabled(true);
}
}
void QtBlockListEditorWindow::setError(const std::string& error) {
if (!error.empty()) {
ui->errorLabel->setText("<font color='red'>" + QtUtilities::htmlEscape(P2QSTRING(error)) + "</font>");
}
else {
ui->errorLabel->setText("");
}
}
diff --git a/Swift/QtUI/QtCertificateViewerDialog.cpp b/Swift/QtUI/QtCertificateViewerDialog.cpp
index a99c29a..6454d82 100644
--- a/Swift/QtUI/QtCertificateViewerDialog.cpp
+++ b/Swift/QtUI/QtCertificateViewerDialog.cpp
@@ -1,76 +1,74 @@
/*
* Copyright (c) 2012 Tobias Markmann
* Licensed under the simplified BSD license.
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
/*
* Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/QtUI/QtCertificateViewerDialog.h>
#include <QDateTime>
#include <QLabel>
#include <QString>
#include <QStringList>
#include <QTreeWidgetItem>
-#include <Swiften/Base/foreach.h>
-
#include <Swift/QtUI/ui_QtCertificateViewerDialog.h>
namespace Swift {
QtCertificateViewerDialog::QtCertificateViewerDialog(QWidget* parent) : QDialog(parent), ui(new Ui::QtCertificateViewerDialog) {
ui->setupUi(this);
connect(ui->certChainTreeWidget, SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)), SLOT(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)));
setAttribute(Qt::WA_DeleteOnClose);
}
QtCertificateViewerDialog::~QtCertificateViewerDialog() {
delete ui;
}
void QtCertificateViewerDialog::setCertificateChain(const std::vector<Certificate::ref>& chain) {
// clean widgets
ui->certChainTreeWidget->clear();
if (chain.empty()) return;
// convert Swift certificate chain to qt certificate chain (root goes first)
currentChain.clear();
- foreach(Certificate::ref cert, chain) {
+ for (auto&& cert : chain) {
ByteArray certAsDer = cert->toDER();
QByteArray dataArray(reinterpret_cast<const char*>(certAsDer.data()), certAsDer.size());
currentChain.push_front(QSslCertificate(dataArray, QSsl::Der));
}
// fill treeWidget
QTreeWidgetItem* root = new QTreeWidgetItem(ui->certChainTreeWidget, QStringList(currentChain.at(0).subjectInfo(QSslCertificate::CommonName)));
root->setData(0, Qt::UserRole, QVariant(0));
root->setExpanded(true);
ui->certChainTreeWidget->addTopLevelItem(root);
if (currentChain.size() > 1) {
QTreeWidgetItem* parent = root;
for (int n = 1; n < currentChain.size(); n++) {
QTreeWidgetItem* link = new QTreeWidgetItem(parent, QStringList(QString("↳ ") + (QStringList(currentChain.at(n).subjectInfo(QSslCertificate::CommonName)).join(", "))));
link->setExpanded(true);
link->setData(0, Qt::UserRole, QVariant(n));
parent = link;
}
ui->certChainTreeWidget->setCurrentItem(parent);
} else {
ui->certChainTreeWidget->setCurrentItem(root);
}
}
void QtCertificateViewerDialog::displayCertificateChainAsSheet(QWidget* parent, const std::vector<Certificate::ref>& chain) {
QtCertificateViewerDialog* dialog = new QtCertificateViewerDialog(parent);
dialog->setCertificateChain(chain);
dialog->show();
}
@@ -98,53 +96,53 @@ void QtCertificateViewerDialog::setCertificateDetails(const QSslCertificate& cer
int rowCount = 0;
ui->certGridLayout->setColumnStretch(2, 1);
QLabel* valueLabel = 0;
ADD_SECTION(tr("General"));
ADD_FIELD(tr("Valid From"), cert.effectiveDate().toString(Qt::TextDate));
ADD_FIELD(tr("Valid To"), cert.expiryDate().toString(Qt::TextDate));
ADD_FIELD(tr("Serial Number"), QString(cert.serialNumber().toHex()));
ADD_FIELD(tr("Version"), QString(cert.version()));
ADD_SECTION(tr("Subject"));
ADD_FIELD(tr("Organization"), cert.subjectInfo(QSslCertificate::Organization));
ADD_FIELD(tr("Common Name"), cert.subjectInfo(QSslCertificate::CommonName));
ADD_FIELD(tr("Locality"), cert.subjectInfo(QSslCertificate::LocalityName));
ADD_FIELD(tr("Organizational Unit"), cert.subjectInfo(QSslCertificate::OrganizationalUnitName));
ADD_FIELD(tr("Country"), cert.subjectInfo(QSslCertificate::CountryName));
ADD_FIELD(tr("State"), cert.subjectInfo(QSslCertificate::StateOrProvinceName));
#if QT_VERSION < 0x050000
QMultiMap<QSsl::AlternateNameEntryType, QString> altNames = cert.alternateSubjectNames();
#define SANTYPE QSsl::AlternateNameEntryType
#else
QMultiMap<QSsl::AlternativeNameEntryType, QString> altNames = cert.subjectAlternativeNames();
#define SANTYPE QSsl::AlternativeNameEntryType
#endif
if (!altNames.empty()) {
ADD_SECTION(tr("Alternate Subject Names"));
- foreach (const SANTYPE &type, altNames.uniqueKeys()) {
- foreach (QString name, altNames.values(type)) {
+ for (const auto& type : altNames.uniqueKeys()) {
+ for (auto&& name : altNames.values(type)) {
if (type == QSsl::EmailEntry) {
ADD_FIELD(tr("E-mail Address"), name);
} else {
ADD_FIELD(tr("DNS Name"), name);
}
}
}
}
ADD_SECTION(tr("Issuer"));
ADD_FIELD(tr("Organization"), cert.issuerInfo(QSslCertificate::Organization));
ADD_FIELD(tr("Common Name"), cert.issuerInfo(QSslCertificate::CommonName));
ADD_FIELD(tr("Locality"), cert.issuerInfo(QSslCertificate::LocalityName));
ADD_FIELD(tr("Organizational Unit"), cert.issuerInfo(QSslCertificate::OrganizationalUnitName));
ADD_FIELD(tr("Country"), cert.issuerInfo(QSslCertificate::CountryName));
ADD_FIELD(tr("State"), cert.issuerInfo(QSslCertificate::StateOrProvinceName));
ui->certGridLayout->setRowStretch(rowCount + 1, 1);
}
}
diff --git a/Swift/QtUI/QtChatTabs.cpp b/Swift/QtUI/QtChatTabs.cpp
index bb9c005..3241858 100644
--- a/Swift/QtUI/QtChatTabs.cpp
+++ b/Swift/QtUI/QtChatTabs.cpp
@@ -53,61 +53,61 @@ QtChatTabs::QtChatTabs(bool singleWindow, SettingsProvider* settingsProvider, bo
std::string gridSizeString = settingsProvider->getSetting(QtUISettingConstants::TRELLIS_GRID_SIZE);
if (!gridSizeString.empty()) {
QByteArray gridSizeData = QByteArray::fromBase64(P2QSTRING(gridSizeString).toUtf8());
QDataStream dataStreamGridSize(&gridSizeData, QIODevice::ReadWrite);
QSize gridSize(1,1);
dataStreamGridSize >> gridSize;
dynamicGrid_->setDimensions(gridSize);
}
// restore positions
std::string tabPositionsString = settingsProvider->getSetting(QtUISettingConstants::TRELLIS_GRID_POSITIONS);
if (!tabPositionsString.empty()) {
QByteArray tabPositionsData = QByteArray::fromBase64(P2QSTRING(tabPositionsString).toUtf8());
QDataStream inTabPositions(&tabPositionsData, QIODevice::ReadWrite);
QHash<QString, QPoint> tabPositions;
inTabPositions >> tabPositions;
dynamicGrid_->setTabPositions(tabPositions);
}
}
gridSelectionDialog_ = new QtGridSelectionDialog();
// setup shortcuts
shortcuts_ << new QShortcut(QKeySequence(tr("CTRL+W", "Close chat tab.")), window(), SLOT(handleCloseTabShortcut()));
shortcuts_ << new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_PageUp), window(), SLOT(handleRequestedPreviousTab()));
shortcuts_ << new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_PageDown), window(), SLOT(handleRequestedNextTab()));
shortcuts_ << new QShortcut(QKeySequence(Qt::ALT + Qt::Key_A), window(), SLOT(handleRequestedActiveTab()));
}
QtChatTabs::~QtChatTabs() {
- foreach (QShortcut* shortcut, shortcuts_) {
+ for (auto shortcut : shortcuts_) {
delete shortcut;
}
if (trellisMode_) {
storeTabPositions();
}
delete gridSelectionDialog_;
}
void QtChatTabs::closeEvent(QCloseEvent* event) {
//Hide first to prevent flickering as each tab is removed.
hide();
if (trellisMode_) {
storeTabPositions();
}
for (int i = dynamicGrid_->count() - 1; i >= 0; i--) {
dynamicGrid_->widget(i)->close();
}
event->accept();
}
QtTabbable* QtChatTabs::getCurrentTab() {
return qobject_cast<QtTabbable*>(dynamicGrid_->currentWidget());
}
void QtChatTabs::setViewMenu(QMenu* viewMenu) {
if (trellisMode_) {
viewMenu->addSeparator();
QAction* action = new QAction(tr("Change &layout"), this);
diff --git a/Swift/QtUI/QtChatTabsShortcutOnlySubstitute.cpp b/Swift/QtUI/QtChatTabsShortcutOnlySubstitute.cpp
index fb41446..40ab17f 100644
--- a/Swift/QtUI/QtChatTabsShortcutOnlySubstitute.cpp
+++ b/Swift/QtUI/QtChatTabsShortcutOnlySubstitute.cpp
@@ -1,45 +1,44 @@
/*
* Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/QtUI/QtChatTabsShortcutOnlySubstitute.h>
#include <cassert>
#include <QApplication>
#include <QShortcut>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
#include <Swift/QtUI/QtTabbable.h>
namespace Swift {
QtChatTabsShortcutOnlySubstitute::QtChatTabsShortcutOnlySubstitute() : QWidget() {
}
QtChatTabsShortcutOnlySubstitute::~QtChatTabsShortcutOnlySubstitute() {
}
void QtChatTabsShortcutOnlySubstitute::addTab(QtTabbable* tab) {
connect(tab, SIGNAL(requestNextTab()), this, SLOT(handleRequestedNextTab()), Qt::UniqueConnection);
connect(tab, SIGNAL(requestActiveTab()), this, SLOT(handleRequestedActiveTab()), Qt::UniqueConnection);
connect(tab, SIGNAL(requestPreviousTab()), this, SLOT(handleRequestedPreviousTab()), Qt::UniqueConnection);
connect(new QShortcut(QKeySequence(tr("CTRL+W", "Close chat tab.")), tab), SIGNAL(activated()), this, SLOT(handleCloseTabShortcut()));
connect(new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_PageUp), tab), SIGNAL(activated()), tab, SIGNAL(requestPreviousTab()));
connect(new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_PageDown), tab), SIGNAL(activated()), tab, SIGNAL(requestNextTab()));
connect(new QShortcut(QKeySequence(Qt::ALT + Qt::Key_A), tab), SIGNAL(activated()), tab, SIGNAL(requestActiveTab()));
}
void QtChatTabsShortcutOnlySubstitute::handleCloseTabShortcut() {
QtTabbable* senderTab = dynamic_cast<QtTabbable*>(sender()->parent());
SWIFT_LOG_ASSERT(senderTab, debug) << "No window to close." << std::endl;
if (senderTab) {
senderTab->close();
}
@@ -68,42 +67,42 @@ void QtChatTabsShortcutOnlySubstitute::handleRequestedActiveTab() {
int startIndex = tabs.indexOf(senderTab);
int currentIndex = startIndex;
do {
currentIndex = (currentIndex + 1) % tabs.size();
QtTabbable* currentTab = tabs.at(currentIndex);
if (currentTab->getWidgetAlertState() == type) {
currentTab->activateWindow();
return;
}
} while (startIndex != currentIndex);
}
}
void QtChatTabsShortcutOnlySubstitute::handleRequestedPreviousTab() {
QtTabbable* senderTab = dynamic_cast<QtTabbable*>(sender());
QList<QtTabbable*> tabs = tabbableWindows();
int currentIndex = tabs.indexOf(senderTab);
assert(currentIndex >= 0);
QtTabbable* previousTab = tabs.at((currentIndex + tabs.size() - 1) % tabs.size());
previousTab->activateWindow();
}
QList<QtTabbable*> QtChatTabsShortcutOnlySubstitute::tabbableWindows() const {
QList<QWidget*> windows = qApp->topLevelWidgets();
QList<QtTabbable*> tabbables;
- foreach(QWidget* topLevelWidget, windows) {
+ for (auto topLevelWidget : windows) {
QtTabbable* tabbable = dynamic_cast<QtTabbable*>(topLevelWidget);
if (tabbable) {
tabbables << tabbable;
}
}
return tabbables;
}
}
diff --git a/Swift/QtUI/QtChatWindow.cpp b/Swift/QtUI/QtChatWindow.cpp
index bda6b3e..d799e19 100644
--- a/Swift/QtUI/QtChatWindow.cpp
+++ b/Swift/QtUI/QtChatWindow.cpp
@@ -359,61 +359,61 @@ void QtChatWindow::tabComplete() {
return;
}
QString suggestion = P2QSTRING(completer_->completeWord(Q2PSTRING(root)));
if (root == suggestion) {
return;
}
tabCompletion_ = true;
cursor.beginEditBlock();
cursor.removeSelectedText();
int oldPosition = cursor.position();
cursor.insertText(suggestion);
tabCompleteCursor_ = cursor;
tabCompleteCursor_.setPosition(oldPosition, QTextCursor::KeepAnchor);
cursor.endEditBlock();
tabCompletion_ = false;
}
void QtChatWindow::setRosterModel(Roster* roster) {
treeWidget_->setRosterModel(roster);
}
void QtChatWindow::setAvailableSecurityLabels(const std::vector<SecurityLabelsCatalog::Item>& labels) {
delete labelModel_;
labelModel_ = new LabelModel();
labelModel_->availableLabels_ = labels;
int i = 0;
int defaultIndex = 0;
labelsWidget_->setModel(labelModel_);
- foreach (SecurityLabelsCatalog::Item label, labels) {
+ for (const auto& label : labels) {
if (label.getIsDefault()) {
defaultIndex = i;
break;
}
i++;
}
labelsWidget_->setCurrentIndex(defaultIndex);
}
void QtChatWindow::handleCurrentLabelChanged(int index) {
if (static_cast<size_t>(index) >= labelModel_->availableLabels_.size()) {
SWIFT_LOG(debug) << "User selected a label that doesn't exist";
return;
}
const SecurityLabelsCatalog::Item& label = labelModel_->availableLabels_[index];
if (label.getLabel()) {
QPalette palette = labelsWidget_->palette();
//palette.setColor(QPalette::Base, P2QSTRING(label.getLabel()->getBackgroundColor()));
palette.setColor(labelsWidget_->backgroundRole(), P2QSTRING(label.getLabel()->getBackgroundColor()));
palette.setColor(labelsWidget_->foregroundRole(), P2QSTRING(label.getLabel()->getForegroundColor()));
labelsWidget_->setPalette(palette);
midBar_->setPalette(palette);
labelsWidget_->setAutoFillBackground(true);
}
else {
labelsWidget_->setAutoFillBackground(false);
labelsWidget_->setPalette(defaultLabelsPalette_);
midBar_->setPalette(defaultLabelsPalette_);
}
}
@@ -685,62 +685,61 @@ void QtChatWindow::handleTextInputLostFocus() {
}
void QtChatWindow::handleActionButtonClicked() {
QMenu contextMenu;
QAction* changeSubject = nullptr;
QAction* configure = nullptr;
QAction* affiliations = nullptr;
QAction* destroy = nullptr;
QAction* invite = nullptr;
QAction* block = nullptr;
QAction* unblock = nullptr;
if (availableRoomActions_.empty()) {
if (blockingState_ == IsBlocked) {
unblock = contextMenu.addAction(tr("Unblock"));
unblock->setEnabled(isOnline_);
}
else if (!isMUC_ && blockingState_ == IsUnblocked) {
block = contextMenu.addAction(tr("Block"));
block->setEnabled(isOnline_);
}
if (supportsImpromptuChat_) {
invite = contextMenu.addAction(tr("Invite person to this chat…"));
invite->setEnabled(isOnline_ && (blockingState_ != IsBlocked));
}
}
else {
- foreach(ChatWindow::RoomAction availableAction, availableRoomActions_)
- {
+ for (auto&& availableAction : availableRoomActions_) {
if (impromptu_) {
// hide options we don't need in impromptu chats
if (availableAction == ChatWindow::ChangeSubject ||
availableAction == ChatWindow::Configure ||
availableAction == ChatWindow::Affiliations ||
availableAction == ChatWindow::Destroy) {
continue;
}
}
switch(availableAction)
{
case ChatWindow::ChangeSubject:
changeSubject = contextMenu.addAction(tr("Change subject…"));
changeSubject->setEnabled(isOnline_);
break;
case ChatWindow::Configure:
configure = contextMenu.addAction(tr("Configure room…"));
configure->setEnabled(isOnline_);
break;
case ChatWindow::Affiliations:
affiliations = contextMenu.addAction(tr("Edit affiliations…"));
affiliations->setEnabled(isOnline_);
break;
case ChatWindow::Destroy:
destroy = contextMenu.addAction(tr("Destroy room"));
destroy->setEnabled(isOnline_);
break;
case ChatWindow::Invite:
invite = contextMenu.addAction(tr("Invite person to this room…"));
invite->setEnabled(isOnline_);
diff --git a/Swift/QtUI/QtContactEditWidget.cpp b/Swift/QtUI/QtContactEditWidget.cpp
index 4e9a7fe..17f5ccf 100644
--- a/Swift/QtUI/QtContactEditWidget.cpp
+++ b/Swift/QtUI/QtContactEditWidget.cpp
@@ -24,143 +24,143 @@ QtContactEditWidget::QtContactEditWidget(const std::set<std::string>& allGroups,
QBoxLayout* layout = new QVBoxLayout(this);
setContentsMargins(0,0,0,0);
layout->setContentsMargins(0,0,0,0);
nameLayout_ = new QHBoxLayout();
suggestionsLayout_ = new QHBoxLayout();
nameLayout_->addLayout(suggestionsLayout_);
name_ = new QLineEdit(this);
nameLayout_->addWidget(name_);
throbberLabel_ = new QLabel(this);
throbberLabel_->setMovie(new QMovie(":/icons/throbber.gif", QByteArray(), this));
throbberLabel_->movie()->start();
nameLayout_->addWidget(throbberLabel_);
layout->addLayout(nameLayout_);
layout->addWidget(new QLabel(tr("Groups:"), this));
QScrollArea* groupsArea = new QScrollArea(this);
layout->addWidget(groupsArea);
groupsArea->setWidgetResizable(true);
groupsArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
groupsArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
QWidget* groups = new QWidget(groupsArea);
groupsArea->setWidget(groups);
QVBoxLayout* scrollLayout = new QVBoxLayout(groups);
- foreach (std::string group, allGroups) {
+ for (const auto& group : allGroups) {
QString groupName = doubleAmpersand(group);
QCheckBox* check = new QCheckBox(groups);
check->setText(groupName);
check->setCheckState(Qt::Unchecked);
checkBoxes_[group] = check;
scrollLayout->addWidget(check);
}
QHBoxLayout* newGroupLayout = new QHBoxLayout();
newGroup_ = new QCheckBox(groups);
newGroup_->setText(tr("New Group:"));
newGroup_->setCheckState(Qt::Unchecked);
newGroupLayout->addWidget(newGroup_);
newGroupName_ = new QLineEdit(groups);
newGroupLayout->addWidget(newGroupName_);
scrollLayout->addLayout(newGroupLayout);
scrollLayout->addItem(new QSpacerItem(20, 73, QSizePolicy::Minimum, QSizePolicy::Expanding));
}
void QtContactEditWidget::setName(const std::string& name) {
name_->setText(P2QSTRING(name));
}
std::string QtContactEditWidget::getName() const {
std::string name = Q2PSTRING(name_->text());
QList<QRadioButton*> buttons = findChildren<QRadioButton*>();
- foreach(const QRadioButton* button, buttons) {
+ for (const auto button : buttons) {
if (button->isChecked()) {
if (button == nameRadioButton_) {
name = Q2PSTRING(name_->text());
} else {
name = singleAmpersand(button->text());
}
break;
}
}
return name;
}
void QtContactEditWidget::setSelectedGroups(const std::vector<std::string>& groups) {
- foreach (std::string group, groups) {
+ for (auto&& group : groups) {
checkBoxes_[group]->setCheckState(Qt::Checked);
}
}
std::set<std::string> QtContactEditWidget::getSelectedGroups() const {
std::set<std::string> groups;
- foreach(const CheckBoxMap::value_type& group, checkBoxes_) {
+ for (const auto& group : checkBoxes_) {
if (group.second->checkState() == Qt::Checked) {
groups.insert(group.first);
}
}
if (newGroup_->checkState() == Qt::Checked && !newGroupName_->text().isEmpty()) {
groups.insert(Q2PSTRING(newGroupName_->text()));
}
return groups;
}
void QtContactEditWidget::setNameSuggestions(const std::vector<std::string>& suggestions) {
throbberLabel_->movie()->stop();
throbberLabel_->hide();
// remove old suggestions except for the user input text field
QLayoutItem* suggestionItem = nullptr;
while ((suggestionItem = suggestionsLayout_->itemAt(0)) && suggestionItem->widget() != name_) {
QWidget* suggestionWidget = suggestionItem->widget();
suggestionsLayout_->removeWidget(suggestionWidget);
delete suggestionWidget;
}
// populate new suggestions
- foreach(const std::string& name, suggestions) {
+ for (const auto& name : suggestions) {
suggestionsLayout_->insertWidget(nameLayout_->count() - 2, new QRadioButton(doubleAmpersand(name), this));
}
nameRadioButton_ = new QRadioButton(tr("Name:"), this);
suggestionsLayout_->insertWidget(nameLayout_->count(), nameRadioButton_);
QRadioButton* suggestedRadioButton = nullptr;
QList<QRadioButton*> radioButtons = findChildren<QRadioButton*>();
- foreach (QRadioButton* candidate, radioButtons) {
+ for (auto candidate : radioButtons) {
if (candidate->text() == name_->text()) {
suggestedRadioButton = candidate;
break;
}
}
if (suggestedRadioButton) {
suggestedRadioButton->setChecked(true);
} else {
nameRadioButton_->setChecked(true);
}
}
QString QtContactEditWidget::doubleAmpersand(const std::string& name) const {
return P2QSTRING(name).replace("&", "&&");
}
std::string QtContactEditWidget::singleAmpersand(const QString& name) const {
return Q2PSTRING(QString(name).replace("&&", "&"));
}
void QtContactEditWidget::clear() {
name_->clear();
setSelectedGroups(std::vector<std::string>());
newGroup_->setChecked(false);
newGroupName_->clear();
throbberLabel_->movie()->start();
throbberLabel_->show();
// clear suggestions
diff --git a/Swift/QtUI/QtContactEditWidget.h b/Swift/QtUI/QtContactEditWidget.h
index d4ea609..0718fee 100644
--- a/Swift/QtUI/QtContactEditWidget.h
+++ b/Swift/QtUI/QtContactEditWidget.h
@@ -14,44 +14,44 @@
#include <QWidget>
class QLabel;
class QLineEdit;
class QCheckBox;
class QHBoxLayout;
class QRadioButton;
namespace Swift {
class QtContactEditWidget : public QWidget {
Q_OBJECT
public:
QtContactEditWidget(const std::set<std::string>& allGroups, QWidget* parent);
void setName(const std::string&);
std::string getName() const;
void setSelectedGroups(const std::vector<std::string>& groups);
std::set<std::string> getSelectedGroups() const;
void setNameSuggestions(const std::vector<std::string>& suggestions);
void clear();
private:
QString doubleAmpersand(const std::string& name) const;
std::string singleAmpersand(const QString& name) const;
+
private:
- typedef std::map<std::string, QCheckBox*> CheckBoxMap;
- CheckBoxMap checkBoxes_;
+ std::map<std::string, QCheckBox*> checkBoxes_;
QHBoxLayout* nameLayout_;
QHBoxLayout* suggestionsLayout_;
QRadioButton* nameRadioButton_;
QLineEdit* name_;
QWidget* groups_;
QCheckBox* newGroup_;
QLineEdit* newGroupName_;
QLabel* throbberLabel_;
};
}
diff --git a/Swift/QtUI/QtEmoticonsGrid.cpp b/Swift/QtUI/QtEmoticonsGrid.cpp
index a81f516..4c8c024 100644
--- a/Swift/QtUI/QtEmoticonsGrid.cpp
+++ b/Swift/QtUI/QtEmoticonsGrid.cpp
@@ -1,65 +1,63 @@
/*
* Copyright (c) 2015 Daniel Baczynski
* Licensed under the Simplified BSD license.
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
/*
* Copyright (c) 2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/QtUI/QtEmoticonsGrid.h>
#include <set>
-#include <QPushButton>
+#include <boost/range/adaptor/reversed.hpp>
-#include <Swiften/Base/foreach.h>
+#include <QPushButton>
#include <Swift/QtUI/QtSwiftUtil.h>
namespace Swift {
-typedef std::map<std::string, std::string> EmoticonsMap; // Without this typedef compiler complains when using foreach
-
QtEmoticonsGrid::QtEmoticonsGrid(const std::map<std::string, std::string>& emoticons, QWidget* parent) : QGridLayout(parent) {
makeUniqueEmoticonsMap(emoticons);
// Create grid: 3 columns, [uniqueEmoticons_.size()/3] rows
int row = 0;
int column = 0;
- foreach(EmoticonsMap::value_type emoticon, uniqueEmoticons_) {
+ for (auto&& emoticon : uniqueEmoticons_) {
QtEmoticonCell* newCell = new QtEmoticonCell(P2QSTRING(emoticon.first), P2QSTRING(emoticon.second));
addWidget(newCell, row, column);
connect(newCell, SIGNAL(emoticonClicked(QString)), this, SLOT(emoticonClickedSlot(QString)));
column++;
if (column >= 3) {
column = 0;
row++;
}
}
}
QtEmoticonsGrid::~QtEmoticonsGrid() {
}
void QtEmoticonsGrid::makeUniqueEmoticonsMap(const std::map<std::string, std::string>& emoticons) {
std::set<std::string> paths;
- reverse_foreach(EmoticonsMap::value_type emoticon, emoticons) {
+ for (auto&& emoticon : boost::adaptors::reverse(emoticons)) {
if (paths.find(emoticon.second) == paths.end()) {
uniqueEmoticons_.insert(emoticon);
paths.insert(emoticon.second);
}
}
}
void QtEmoticonsGrid::emoticonClickedSlot(QString emoticonAsText) {
emit emoticonClicked(emoticonAsText);
}
}
diff --git a/Swift/QtUI/QtFormResultItemModel.cpp b/Swift/QtUI/QtFormResultItemModel.cpp
index 60cf0c0..b35bb4f 100644
--- a/Swift/QtUI/QtFormResultItemModel.cpp
+++ b/Swift/QtUI/QtFormResultItemModel.cpp
@@ -1,95 +1,93 @@
/*
* Copyright (c) 2012 Tobias Markmann
* Licensed under the simplified BSD license.
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
/*
* Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/QtUI/QtFormResultItemModel.h>
#include <boost/algorithm/string/join.hpp>
-#include <Swiften/Base/foreach.h>
-
#include <Swift/QtUI/QtSwiftUtil.h>
namespace Swift {
QtFormResultItemModel::QtFormResultItemModel(QObject *parent) : QAbstractTableModel(parent) {
}
QtFormResultItemModel::QtFormResultItemModel(QObject* parent, Form::ref formResult) : QAbstractTableModel(parent), formResult_(formResult) {
}
void QtFormResultItemModel::setForm(Form::ref formResult) {
emit layoutAboutToBeChanged();
formResult_ = formResult;
emit layoutChanged();
}
const Form::ref QtFormResultItemModel::getForm() const {
return formResult_;
}
QVariant QtFormResultItemModel::headerData(int section, Qt::Orientation /*orientation*/, int role) const {
if (!formResult_) return QVariant();
if (role != Qt::DisplayRole) return QVariant();
if (static_cast<size_t>(section) >= formResult_->getReportedFields().size()) return QVariant();
return QVariant(P2QSTRING(formResult_->getReportedFields().at(section)->getLabel()));
}
int QtFormResultItemModel::rowCount(const QModelIndex &/*parent*/) const {
if (!formResult_) return 0;
return formResult_->getItems().size();
}
int QtFormResultItemModel::columnCount(const QModelIndex &/*parent*/) const {
if (!formResult_) return 0;
return formResult_->getReportedFields().size();
}
QVariant QtFormResultItemModel::data(const QModelIndex &index, int role) const {
if (!formResult_) return QVariant();
if (role != Qt::DisplayRole || !index.isValid()) {
return QVariant();
}
if (static_cast<size_t>(index.row()) >= formResult_->getItems().size()) return QVariant();
if (static_cast<size_t>(index.column()) >= formResult_->getReportedFields().size()) return QVariant();
Form::FormItem item = formResult_->getItems().at(index.row());
return QVariant(P2QSTRING(getFieldValue(item, index.column())));
}
const std::string QtFormResultItemModel::getFieldValue(const Form::FormItem& item, const int column) const {
// determine field name
std::string name = formResult_->getReportedFields().at(column)->getName();
- foreach(FormField::ref field, item) {
+ for (auto&& field : item) {
if (field->getName() == name) {
std::string delimiter = "";
if (field->getType() == FormField::TextMultiType) {
delimiter = "\n";
}
else if (field->getType() == FormField::JIDMultiType) {
delimiter = ", ";
}
else if (field->getType() == FormField::ListMultiType) {
delimiter = ", ";
}
return boost::algorithm::join(field->getValues(), delimiter);
}
}
return "";
}
}
diff --git a/Swift/QtUI/QtFormWidget.cpp b/Swift/QtUI/QtFormWidget.cpp
index 1d26815..96c2da0 100644
--- a/Swift/QtUI/QtFormWidget.cpp
+++ b/Swift/QtUI/QtFormWidget.cpp
@@ -1,118 +1,116 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/QtUI/QtFormWidget.h>
#include <memory>
#include <boost/algorithm/string/join.hpp>
#include <QCheckBox>
#include <QGridLayout>
#include <QLabel>
#include <QLineEdit>
#include <QListWidget>
#include <QScrollArea>
#include <QTextEdit>
#include <qdebug.h>
-#include <Swiften/Base/foreach.h>
-
#include <Swift/QtUI/QtSwiftUtil.h>
namespace Swift {
QtFormWidget::QtFormWidget(Form::ref form, QWidget* parent) : QWidget(parent), form_(form) {
QGridLayout* thisLayout = new QGridLayout(this);
int row = 0;
if (!form->getTitle().empty()) {
QLabel* instructions = new QLabel(("<b>" + form->getTitle() + "</b>").c_str(), this);
thisLayout->addWidget(instructions, row++, 0, 1, 2);
}
if (!form->getInstructions().empty()) {
QLabel* instructions = new QLabel(form->getInstructions().c_str(), this);
thisLayout->addWidget(instructions, row++, 0, 1, 2);
}
QScrollArea* scrollArea = new QScrollArea(this);
thisLayout->addWidget(scrollArea);
QWidget* scroll = new QWidget(this);
QGridLayout* layout = new QGridLayout(scroll);
const std::vector<Form::FormItem> items = form->getItems();
if (items.empty()) { /* single item forms */
- foreach (FormField::ref field, form->getFields()) {
+ for (auto&& field : form->getFields()) {
QWidget* widget = createWidget(field, field->getType(), 0);
if (widget) {
layout->addWidget(new QLabel(field->getLabel().c_str(), this), row, 0);
layout->addWidget(widget, row++, 1);
}
}
} else { /* multi-item forms */
const Form::FormItem& headers = form->getFields();
for (size_t i = 0; i < items.size(); ++i) {
const Form::FormItem& item = items[i];
assert(item.size() == headers.size());
for (size_t j = 0; j < item.size(); ++j) {
QWidget* widget = createWidget(item[j], headers[j]->getType(), i);
if (widget) {
layout->addWidget(new QLabel(item[j]->getLabel().c_str(), this), row, 0);
layout->addWidget(widget, row++, 1);
}
}
}
}
scrollArea->setWidget(scroll);
scrollArea->setWidgetResizable(true);
setEditable(form->getType() != Form::CancelType && form->getType() != Form::ResultType);
}
QtFormWidget::~QtFormWidget() {
}
QListWidget* QtFormWidget::createList(FormField::ref field) {
QListWidget* listWidget = new QListWidget(this);
listWidget->setSortingEnabled(false);
listWidget->setSelectionMode(field->getType() == FormField::ListMultiType ? QAbstractItemView::MultiSelection : QAbstractItemView::SingleSelection);
std::vector<bool> selected;
/* if this is an editable form, use the 'options' list, otherwise use the 'values' list */
if (form_->getType() != Form::FormType) {
- foreach (const std::string& value, field->getValues()) {
+ for (const auto& value : field->getValues()) {
listWidget->addItem(P2QSTRING(value));
selected.push_back(false);
}
} else {
- foreach (FormField::Option option, field->getOptions()) {
+ for (auto&& option : field->getOptions()) {
listWidget->addItem(option.label.c_str());
if (field->getType() == FormField::ListSingleType) {
selected.push_back(!field->getValues().empty() && option.value == field->getValues()[0]);
}
else if (field->getType() == FormField::ListMultiType) {
std::string text = option.value;
selected.push_back(std::find(field->getValues().begin(), field->getValues().end(), text) != field->getValues().end());
}
}
}
for (int i = 0; i < listWidget->count(); i++) {
QListWidgetItem* item = listWidget->item(i);
item->setSelected(selected[i]);
}
return listWidget;
}
QWidget* QtFormWidget::createWidget(FormField::ref field, const FormField::Type type, const size_t index) {
QWidget* widget = nullptr;
if (type == FormField::BooleanType) {
QCheckBox* checkWidget = new QCheckBox(this);
checkWidget->setCheckState(field->getBoolValue() ? Qt::Checked : Qt::Unchecked);
widget = checkWidget;
}
if (type == FormField::FixedType) {
QString value = field->getFixedValue().c_str();
widget = new QLabel(value, this);
}
if (type == FormField::ListSingleType) {
widget = createList(field);
@@ -130,112 +128,112 @@ QWidget* QtFormWidget::createWidget(FormField::ref field, const FormField::Type
widget = lineWidget;
}
if (type == FormField::TextSingleType) {
QString value = field->getTextSingleValue().c_str();
widget = new QLineEdit(value, this);
}
if (type == FormField::JIDSingleType) {
QString value = field->getJIDSingleValue().toString().c_str();
widget = new QLineEdit(value, this);
}
if (type == FormField::JIDMultiType) {
QString text = boost::join(field->getValues(), "\n").c_str();
QTextEdit* textWidget = new QTextEdit(this);
textWidget->setPlainText(text);
widget = textWidget;
}
if (type == FormField::ListMultiType) {
widget = createList(field);
}
std::string indexString;
if (index) {
/* for multi-item forms we need to distinguish between the different rows */
indexString = boost::lexical_cast<std::string>(index);
}
fields_[field->getName() + indexString] = widget;
return widget;
}
Form::ref QtFormWidget::getCompletedForm() {
Form::ref result(new Form(Form::SubmitType));
- foreach (std::shared_ptr<FormField> field, form_->getFields()) {
+ for (auto&& field : form_->getFields()) {
std::shared_ptr<FormField> resultField = std::make_shared<FormField>(field->getType());
if (field->getType() == FormField::BooleanType) {
resultField->setBoolValue(qobject_cast<QCheckBox*>(fields_[field->getName()])->checkState() == Qt::Checked);
}
if (field->getType() == FormField::FixedType || field->getType() == FormField::HiddenType) {
resultField->addValue(field->getValues().empty() ? "" : field->getValues()[0]);
}
if (field->getType() == FormField::ListSingleType) {
QListWidget* listWidget = qobject_cast<QListWidget*>(fields_[field->getName()]);
if (listWidget->selectedItems().size() > 0) {
int i = listWidget->row(listWidget->selectedItems()[0]);
resultField->addValue(field->getOptions()[i].value);
}
}
if (field->getType() == FormField::TextMultiType) {
QTextEdit* widget = qobject_cast<QTextEdit*>(fields_[field->getName()]);
QString string = widget->toPlainText();
if (!string.isEmpty()) {
resultField->setTextMultiValue(Q2PSTRING(string));
}
}
if (field->getType() == FormField::TextPrivateType || field->getType() == FormField::TextSingleType || field->getType() == FormField::JIDSingleType) {
QLineEdit* widget = qobject_cast<QLineEdit*>(fields_[field->getName()]);
QString string = widget->text();
if (!string.isEmpty()) {
resultField->addValue(Q2PSTRING(string));
}
}
if (field->getType() == FormField::JIDMultiType) {
QTextEdit* widget = qobject_cast<QTextEdit*>(fields_[field->getName()]);
QString string = widget->toPlainText();
if (!string.isEmpty()) {
QStringList lines = string.split("\n");
- foreach (QString line, lines) {
+ for (auto&& line : lines) {
resultField->addValue(Q2PSTRING(line));
}
}
}
if (field->getType() == FormField::ListMultiType) {
QListWidget* listWidget = qobject_cast<QListWidget*>(fields_[field->getName()]);
- foreach (QListWidgetItem* item, listWidget->selectedItems()) {
+ for (auto item : listWidget->selectedItems()) {
resultField->addValue(field->getOptions()[listWidget->row(item)].value);
}
}
resultField->setName(field->getName());
result->addField(resultField);
}
return result;
}
template<class T> void QtFormWidget::setEnabled(QWidget* rawWidget, bool editable) {
T* widget = qobject_cast<T*>(rawWidget);
if (widget) {
widget->setEnabled(editable);
}
}
template<class T> void QtFormWidget::setEditable(QWidget* rawWidget, bool editable) {
T* widget = qobject_cast<T*>(rawWidget);
if (widget) {
widget->setReadOnly(!editable);
}
}
void QtFormWidget::setEditable(bool editable) {
if (!form_) {
return;
}
- foreach (std::shared_ptr<FormField> field, form_->getFields()) {
+ for (auto&& field : form_->getFields()) {
QWidget* widget = nullptr;
if (field) {
widget = fields_[field->getName()];
}
setEnabled<QCheckBox>(widget, editable);
setEnabled<QListWidget>(widget, editable);
setEditable<QTextEdit>(widget, editable);
setEditable<QLineEdit>(widget, editable);
}
}
}
diff --git a/Swift/QtUI/QtHistoryWindow.cpp b/Swift/QtUI/QtHistoryWindow.cpp
index 53e7ffe..77a7f12 100644
--- a/Swift/QtUI/QtHistoryWindow.cpp
+++ b/Swift/QtUI/QtHistoryWindow.cpp
@@ -149,61 +149,61 @@ void QtHistoryWindow::addMessage(const std::string &message, const std::string &
previousBottomSenderName_ = P2QSTRING(senderName);
}
// keep track of the days viewable in the chatView
if (!dates_.count(date)) {
dates_.insert(date);
}
}
void QtHistoryWindow::handleSomethingSelectedChanged(RosterItem* item) {
onSelectedContactChanged(item);
}
void QtHistoryWindow::resetConversationView() {
previousTopMessageWasSelf_ = false;
previousBottomMessageWasSelf_ = false;
previousTopSenderName_.clear();
previousBottomSenderName_.clear();
dates_.clear();
conversation_->resetView();
}
void QtHistoryWindow::handleScrollRequested(int pos) {
// first message starts with offset 5
if (pos < 5) {
pos = 5;
}
QDate currentDate;
- foreach (const QDate& date, dates_) {
+ for (const auto& date : dates_) {
int snippetPosition = conversation_->getSnippetPositionByDate(date);
if (snippetPosition <= pos) {
currentDate = date;
}
}
if (ui_.calendarWidget_->selectedDate() != currentDate) {
ui_.calendarWidget_->setSelectedDate(currentDate);
}
}
void QtHistoryWindow::handleScrollReachedTop() {
if (dates_.empty()) {
return;
}
int year, month, day;
QDate firstDate = *dates_.begin();
firstDate.getDate(&year, &month, &day);
onScrollReachedTop(boost::gregorian::date(boost::numeric_cast<unsigned short>(year), boost::numeric_cast<unsigned short>(month), boost::numeric_cast<unsigned short>(day)));
}
void QtHistoryWindow::handleScrollReachedBottom() {
if (dates_.empty()) {
return;
}
int year, month, day;
QDate lastDate = *dates_.rbegin();
lastDate.getDate(&year, &month, &day);
diff --git a/Swift/QtUI/QtLoginWindow.cpp b/Swift/QtUI/QtLoginWindow.cpp
index d91f694..865d8b5 100644
--- a/Swift/QtUI/QtLoginWindow.cpp
+++ b/Swift/QtUI/QtLoginWindow.cpp
@@ -472,61 +472,61 @@ void QtLoginWindow::handleToggleNotifications(bool enabled) {
settings_->storeSetting(SettingConstants::SHOW_NOTIFICATIONS, enabled);
}
void QtLoginWindow::handleQuit() {
onQuitRequest();
}
void QtLoginWindow::quit() {
QApplication::quit();
}
void QtLoginWindow::setInitialMenus() {
menuBar_->clear();
menuBar_->addMenu(swiftMenu_);
#ifdef SWIFTEN_PLATFORM_MACOSX
menuBar_->addMenu(generalMenu_);
#endif
}
void QtLoginWindow::morphInto(MainWindow *mainWindow) {
setEnabled(false);
QtMainWindow *qtMainWindow = dynamic_cast<QtMainWindow*>(mainWindow);
assert(qtMainWindow);
stack_->removeWidget(loginWidgetWrapper_);
stack_->addWidget(qtMainWindow);
stack_->setCurrentWidget(qtMainWindow);
setEnabled(true);
setInitialMenus();
std::vector<QMenu*> mainWindowMenus = qtMainWindow->getMenus();
viewMenu_ = mainWindowMenus[0];
- foreach (QMenu* menu, mainWindowMenus) {
+ for (auto menu : mainWindowMenus) {
menuBar_->addMenu(menu);
}
setFocus();
}
void QtLoginWindow::setMessage(const std::string& message) {
if (!message.empty()) {
message_->setText("<center><font color=\"red\">" + P2QSTRING(message) + "</font></center>");
}
else {
message_->setText("");
}
}
void QtLoginWindow::toggleBringToFront() {
if (!isVisible()) {
bringToFront();
}
else {
window()->hide();
}
}
void QtLoginWindow::bringToFront() {
window()->showNormal();
window()->raise();
window()->activateWindow();
}
void QtLoginWindow::hide() {
diff --git a/Swift/QtUI/QtPlainChatView.cpp b/Swift/QtUI/QtPlainChatView.cpp
index d682cfa..05a2eb0 100644
--- a/Swift/QtUI/QtPlainChatView.cpp
+++ b/Swift/QtUI/QtPlainChatView.cpp
@@ -1,78 +1,77 @@
/*
* Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/QtUI/QtPlainChatView.h>
#include <QDialog>
#include <QFileDialog>
#include <QInputDialog>
#include <QLabel>
#include <QMenu>
#include <QProgressBar>
#include <QPushButton>
#include <QScrollBar>
#include <QTextEdit>
#include <QVBoxLayout>
#include <Swiften/Base/FileSize.h>
-#include <Swiften/Base/foreach.h>
#include <Swift/Controllers/UIEvents/JoinMUCUIEvent.h>
#include <Swift/Controllers/UIEvents/UIEventStream.h>
#include <Swift/QtUI/ChatSnippet.h>
#include <Swift/QtUI/QtSwiftUtil.h>
#include <Swift/QtUI/QtUtilities.h>
namespace Swift {
QtPlainChatView::QtPlainChatView(QtChatWindow *window, UIEventStream* eventStream)
: QtChatView(window), window_(window), eventStream_(eventStream), idGenerator_(0) {
QVBoxLayout* mainLayout = new QVBoxLayout(this);
mainLayout->setSpacing(0);
mainLayout->setContentsMargins(0,0,0,0);
log_ = new LogTextEdit(this);
log_->setReadOnly(true);
log_->setAccessibleName(tr("Chat Messages"));
mainLayout->addWidget(log_);
}
QtPlainChatView::~QtPlainChatView() {
}
QString chatMessageToString(const ChatWindow::ChatMessage& message) {
QString result;
- foreach (std::shared_ptr<ChatWindow::ChatMessagePart> part, message.getParts()) {
+ for (auto&& part : message.getParts()) {
std::shared_ptr<ChatWindow::ChatTextMessagePart> textPart;
std::shared_ptr<ChatWindow::ChatURIMessagePart> uriPart;
std::shared_ptr<ChatWindow::ChatEmoticonMessagePart> emoticonPart;
std::shared_ptr<ChatWindow::ChatHighlightingMessagePart> highlightPart;
if ((textPart = std::dynamic_pointer_cast<ChatWindow::ChatTextMessagePart>(part))) {
QString text = QtUtilities::htmlEscape(P2QSTRING(textPart->text));
text.replace("\n","<br/>");
result += text;
continue;
}
if ((uriPart = std::dynamic_pointer_cast<ChatWindow::ChatURIMessagePart>(part))) {
QString uri = QtUtilities::htmlEscape(P2QSTRING(uriPart->target));
result += "<a href='" + uri + "' >" + uri + "</a>";
continue;
}
if ((emoticonPart = std::dynamic_pointer_cast<ChatWindow::ChatEmoticonMessagePart>(part))) {
result += P2QSTRING(emoticonPart->alternativeText);
continue;
}
if ((highlightPart = std::dynamic_pointer_cast<ChatWindow::ChatHighlightingMessagePart>(part))) {
//FIXME: Maybe do something here. Anything, really.
continue;
}
}
return result;
}
std::string QtPlainChatView::addMessage(const ChatWindow::ChatMessage& message, const std::string& senderName, bool senderIsSelf, std::shared_ptr<SecurityLabel> label, const std::string& /*avatarPath*/, const boost::posix_time::ptime& time) {
QString text = "<p>";
diff --git a/Swift/QtUI/QtProfileWindow.cpp b/Swift/QtUI/QtProfileWindow.cpp
index 461ea38..80e275b 100644
--- a/Swift/QtUI/QtProfileWindow.cpp
+++ b/Swift/QtUI/QtProfileWindow.cpp
@@ -129,39 +129,39 @@ void QtProfileWindow::updateTitle() {
setWindowTitle(tr("Edit Profile") + jidString);
} else {
setWindowTitle(tr("Show Profile") + jidString);
}
}
void QtProfileWindow::updateWindowSize() {
// Delay resizing to the end of the event loop, because Qt calculates the correct layout asynchronously.
// Qt will post LayoutRequests for widgets on the event loop on show and widgets will recaluclate their
// layout as they process these events.
// We use the complete and correct size hint from the freshly calculated layout by delaying execution of
// the resize code to the end of Qt's event loop.
if (!adjustSizeTimer.isActive()) {
adjustSizeTimer.start(0);
}
}
void QtProfileWindow::closeEvent(QCloseEvent* event) {
event->accept();
onWindowAboutToBeClosed(jid);
}
void QtProfileWindow::handleSave() {
onVCardChangeRequest(ui->vcard->getVCard());
}
void QtProfileWindow::handleAdjustSizeTimeout() {
// Force recaluclation of all layout geometry in children widgets.
// This is required on Windows to have the correct size even on first show.
QList<QWidget *> children = findChildren<QWidget*>();
- foreach(QWidget* child, children) {
+ for (auto child : children) {
child->updateGeometry();
}
updateGeometry();
adjustSize();
}
}
diff --git a/Swift/QtUI/QtSettingsProvider.cpp b/Swift/QtUI/QtSettingsProvider.cpp
index 3c32dc8..42ac22d 100644
--- a/Swift/QtUI/QtSettingsProvider.cpp
+++ b/Swift/QtUI/QtSettingsProvider.cpp
@@ -50,75 +50,75 @@ void QtSettingsProvider::storeSetting(const Setting<bool>& setting, const bool&
if (getSetting(setting) != settingValue) {
changed = true;
}
settings_.setValue(setting.getKey().c_str(), settingValue);
if (changed) {
onSettingChanged(setting.getKey());
}
updatePermissions();
}
int QtSettingsProvider::getSetting(const Setting<int>& setting) {
QVariant variant = settings_.value(setting.getKey().c_str());
return variant.isNull() ? setting.getDefaultValue() : variant.toInt();
}
void QtSettingsProvider::storeSetting(const Setting<int>& setting, const int& settingValue) {
bool changed = false;
if (getSetting(setting) != settingValue) {
changed = true;
}
settings_.setValue(setting.getKey().c_str(), settingValue);
if (changed) {
onSettingChanged(setting.getKey());
}
updatePermissions();
}
std::vector<std::string> QtSettingsProvider::getAvailableProfiles() {
std::vector<std::string> profiles;
QVariant profilesVariant = settings_.value("profileList");
- foreach(QString profileQString, profilesVariant.toStringList()) {
+ for (const auto& profileQString : profilesVariant.toStringList()) {
profiles.push_back(std::string(profileQString.toUtf8()));
}
return profiles;
}
void QtSettingsProvider::createProfile(const std::string& profile) {
QStringList stringList = settings_.value("profileList").toStringList();
stringList.append(profile.c_str());
settings_.setValue("profileList", stringList);
updatePermissions();
}
void QtSettingsProvider::removeProfile(const std::string& profile) {
QString profileStart(QString(profile.c_str()) + ":");
- foreach (QString key, settings_.allKeys()) {
+ for (auto&& key : settings_.allKeys()) {
if (key.startsWith(profileStart)) {
settings_.remove(key);
}
}
QStringList stringList = settings_.value("profileList").toStringList();
stringList.removeAll(profile.c_str());
settings_.setValue("profileList", stringList);
updatePermissions();
}
QSettings* QtSettingsProvider::getQSettings() {
return &settings_;
}
void QtSettingsProvider::updatePermissions() {
#if !defined(Q_OS_WIN) && !defined(Q_OS_MAC)
QFile file(settings_.fileName());
if (file.exists()) {
file.setPermissions(QFile::ReadOwner|QFile::WriteOwner);
}
#endif
}
bool QtSettingsProvider::getIsSettingFinal(const std::string& /*settingPath*/) {
return false;
}
}
diff --git a/Swift/QtUI/QtSingleWindow.cpp b/Swift/QtUI/QtSingleWindow.cpp
index ab7e81e..1fba497 100644
--- a/Swift/QtUI/QtSingleWindow.cpp
+++ b/Swift/QtUI/QtSingleWindow.cpp
@@ -1,81 +1,79 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/QtUI/QtSingleWindow.h>
-#include <Swiften/Base/foreach.h>
-
#include <Swift/QtUI/QtChatTabs.h>
#include <Swift/QtUI/QtSettingsProvider.h>
namespace Swift {
static const QString SINGLE_WINDOW_GEOMETRY = QString("SINGLE_WINDOW_GEOMETRY");
static const QString SINGLE_WINDOW_SPLITS = QString("SINGLE_WINDOW_SPLITS");
QtSingleWindow::QtSingleWindow(QtSettingsProvider* settings) : QSplitter() {
settings_ = settings;
QVariant geometryVariant = settings_->getQSettings()->value(SINGLE_WINDOW_GEOMETRY);
if (geometryVariant.isValid()) {
restoreGeometry(geometryVariant.toByteArray());
}
connect(this, SIGNAL(splitterMoved(int, int)), this, SLOT(handleSplitterMoved(int, int)));
restoreSplitters();
}
QtSingleWindow::~QtSingleWindow() {
}
void QtSingleWindow::addWidget(QWidget* widget) {
QtChatTabs* tabs = dynamic_cast<QtChatTabs*>(widget);
if (tabs) {
connect(tabs, SIGNAL(onTitleChanged(const QString&)), this, SLOT(handleTabsTitleChanged(const QString&)));
}
QSplitter::addWidget(widget);
}
void QtSingleWindow::handleTabsTitleChanged(const QString& title) {
setWindowTitle(title);
}
void QtSingleWindow::handleSplitterMoved(int, int) {
QList<QVariant> variantValues;
QList<int> intValues = sizes();
- foreach (int value, intValues) {
+ for (const auto& value : intValues) {
variantValues.append(QVariant(value));
}
settings_->getQSettings()->setValue(SINGLE_WINDOW_SPLITS, QVariant(variantValues));
}
void QtSingleWindow::restoreSplitters() {
QList<QVariant> variantValues = settings_->getQSettings()->value(SINGLE_WINDOW_SPLITS).toList();
QList<int> intValues;
- foreach (QVariant value, variantValues) {
+ for (auto&& value : variantValues) {
intValues.append(value.toInt());
}
setSizes(intValues);
}
void QtSingleWindow::insertAtFront(QWidget* widget) {
insertWidget(0, widget);
restoreSplitters();
}
void QtSingleWindow::handleGeometryChanged() {
settings_->getQSettings()->setValue(SINGLE_WINDOW_GEOMETRY, saveGeometry());
}
void QtSingleWindow::resizeEvent(QResizeEvent* event) {
handleGeometryChanged();
QSplitter::resizeEvent(event);
}
void QtSingleWindow::moveEvent(QMoveEvent*) {
handleGeometryChanged();
}
}
diff --git a/Swift/QtUI/QtSpellCheckHighlighter.cpp b/Swift/QtUI/QtSpellCheckHighlighter.cpp
index 6565b06..cb467e2 100644
--- a/Swift/QtUI/QtSpellCheckHighlighter.cpp
+++ b/Swift/QtUI/QtSpellCheckHighlighter.cpp
@@ -1,41 +1,41 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/QtUI/QtSpellCheckHighlighter.h>
#include <SwifTools/SpellChecker.h>
#include <Swift/QtUI/QtSwiftUtil.h>
namespace Swift {
QtSpellCheckHighlighter::QtSpellCheckHighlighter(QTextDocument* parent, SpellChecker* spellChecker) : QSyntaxHighlighter(parent), checker_(spellChecker) {
}
QtSpellCheckHighlighter::~QtSpellCheckHighlighter() {
}
void QtSpellCheckHighlighter::highlightBlock(const QString& text) {
misspelledPositions_.clear();
std::string fragment = Q2PSTRING(text);
checker_->checkFragment(fragment, misspelledPositions_);
QTextCharFormat spellingErrorFormat;
spellingErrorFormat.setUnderlineColor(QColor(Qt::red));
spellingErrorFormat.setUnderlineStyle(QTextCharFormat::SpellCheckUnderline);
- foreach (PositionPair position, misspelledPositions_) {
+ for (auto&& position : misspelledPositions_) {
setFormat(boost::get<0>(position), boost::get<1>(position) - boost::get<0>(position), spellingErrorFormat);
};
}
PositionPairList QtSpellCheckHighlighter::getMisspelledPositions() const {
return misspelledPositions_;
}
}
diff --git a/Swift/QtUI/QtStatusWidget.cpp b/Swift/QtUI/QtStatusWidget.cpp
index 2e9e4cc..b175e5c 100644
--- a/Swift/QtUI/QtStatusWidget.cpp
+++ b/Swift/QtUI/QtStatusWidget.cpp
@@ -117,120 +117,120 @@ QtStatusWidget::QtStatusWidget(StatusCache* statusCache, QWidget *parent) : QWid
QtStatusWidget::~QtStatusWidget() {
delete menu_;
delete connectingMovie_;
}
void QtStatusWidget::handleApplicationFocusChanged(QWidget* /*old*/, QWidget* /*now*/) {
QWidget* now = qApp->focusWidget();
if (!editing_ || stack_->currentIndex() == 0) {
return;
}
if (!now || (now != menu_ && now != statusEdit_ && !now->isAncestorOf(statusEdit_) && !now->isAncestorOf(menu_) && !statusEdit_->isAncestorOf(now) && !menu_->isAncestorOf(now))) {
handleEditCancelled();
}
}
void QtStatusWidget::mousePressEvent(QMouseEvent*) {
if (stack_->currentIndex() == 0) {
handleClicked();
}
}
void QtStatusWidget::generateList() {
if (!editing_) {
return;
}
QString text = statusEdit_->text();
newStatusText_ = text;
menu_->clear();
- foreach (StatusShow::Type type, icons_.keys()) {
+ for (const auto& type : icons_.keys()) {
QListWidgetItem* item = new QListWidgetItem(text == "" ? getNoMessage() : text, menu_);
item->setIcon(icons_[type]);
item->setToolTip(P2QSTRING(statusShowTypeToFriendlyName(type)) + ": " + item->text());
item->setStatusTip(item->toolTip());
item->setData(Qt::UserRole, QVariant(type));
}
std::vector<StatusCache::PreviousStatus> previousStatuses = statusCache_->getMatches(Q2PSTRING(text), 8);
- foreach (StatusCache::PreviousStatus savedStatus, previousStatuses) {
+ for (const auto& savedStatus : previousStatuses) {
if (savedStatus.first.empty() || std::find_if(allTypes_.begin(), allTypes_.end(),
savedStatus.second == lambda::_1 && savedStatus.first == lambda::bind(&statusShowTypeToFriendlyName, lambda::_1)) != allTypes_.end()) {
continue;
}
QListWidgetItem* item = new QListWidgetItem(P2QSTRING(savedStatus.first), menu_);
item->setIcon(icons_[savedStatus.second]);
item->setToolTip(item->text());
item->setStatusTip(item->toolTip());
item->setData(Qt::UserRole, QVariant(savedStatus.second));
}
- foreach (StatusShow::Type type, icons_.keys()) {
+ for (const auto& type : icons_.keys()) {
if (Q2PSTRING(text) == statusShowTypeToFriendlyName(type)) {
continue;
}
QListWidgetItem* item = new QListWidgetItem(P2QSTRING(statusShowTypeToFriendlyName(type)), menu_);
item->setIcon(icons_[type]);
item->setToolTip(item->text());
item->setStatusTip(item->toolTip());
item->setData(Qt::UserRole, QVariant(type));
}
resizeMenu();
}
void QtStatusWidget::resizeMenu() {
int height = menu_->sizeHintForRow(0) * menu_->count();
int marginLeft;
int marginTop;
int marginRight;
int marginBottom;
menu_->getContentsMargins(&marginLeft, &marginTop, &marginRight, &marginBottom);
height += marginTop + marginBottom;
menu_->setGeometry(menu_->x(), menu_->y(), menu_->width(), height);
}
void QtStatusWidget::handleClicked() {
editing_ = true;
QDesktopWidget* desktop = QApplication::desktop();
int screen = desktop->screenNumber(this);
QPoint point = mapToGlobal(QPoint(0, height()));
QRect geometry = desktop->availableGeometry(screen);
int x = point.x();
int y = point.y();
int width = 200;
int height = 80;
int screenWidth = geometry.x() + geometry.width();
if (x + width > screenWidth) {
x = screenWidth - width;
}
- //foreach (StatusShow::Type type, allTypes_) {
+ //for (StatusShow::Type type : allTypes_) {
// if (statusEdit_->text() == P2QSTRING(statusShowTypeToFriendlyName(type))) {
statusEdit_->setText("");
// }
//}
generateList();
height = menu_->sizeHintForRow(0) * menu_->count();
int marginLeft;
int marginTop;
int marginRight;
int marginBottom;
menu_->getContentsMargins(&marginLeft, &marginTop, &marginRight, &marginBottom);
height += marginTop + marginBottom;
width += marginLeft + marginRight;
menu_->setGeometry(x, y, width, height);
menu_->move(x, y);
menu_->setMaximumWidth(width);
menu_->show();
activateWindow();
statusEdit_->selectAll();
stack_->setCurrentIndex(1);
statusEdit_->setFocus();
connect(qApp, SIGNAL(focusChanged(QWidget*, QWidget*)), this, SLOT(handleApplicationFocusChanged(QWidget*, QWidget*)), Qt::QueuedConnection);
}
void QtStatusWidget::viewMode() {
disconnect(qApp, SIGNAL(focusChanged(QWidget*, QWidget*)), this, SLOT(handleApplicationFocusChanged(QWidget*, QWidget*)));
editing_ = false;
menu_->hide();
diff --git a/Swift/QtUI/QtSubscriptionRequestWindow.cpp b/Swift/QtUI/QtSubscriptionRequestWindow.cpp
index eea13f2..c8c4178 100644
--- a/Swift/QtUI/QtSubscriptionRequestWindow.cpp
+++ b/Swift/QtUI/QtSubscriptionRequestWindow.cpp
@@ -46,47 +46,47 @@ QtSubscriptionRequestWindow::QtSubscriptionRequestWindow(std::shared_ptr<Subscri
layout->addWidget(new QLabel);
layout->addLayout(buttonLayout);
layout->addWidget(new QLabel);
QLabel* footer = new QLabel(tr("(If you choose to defer this choice, you will be asked again when you next login.)"));
layout->addWidget(footer);
}
setLayout(layout);
}
void QtSubscriptionRequestWindow::handleYes() {
event_->accept();
delete this;
}
void QtSubscriptionRequestWindow::handleNo() {
event_->decline();
delete this;
}
void QtSubscriptionRequestWindow::handleDefer() {
event_->defer();
delete this;
}
QtSubscriptionRequestWindow::~QtSubscriptionRequestWindow() {
windows_.removeOne(this);
}
QtSubscriptionRequestWindow* QtSubscriptionRequestWindow::getWindow(std::shared_ptr<SubscriptionRequestEvent> event, QWidget* parent) {
- foreach (QtSubscriptionRequestWindow* window, windows_) {
+ for (auto window : windows_) {
if (window->getEvent() == event) {
return window;
}
}
QtSubscriptionRequestWindow* window = new QtSubscriptionRequestWindow(event, parent);
windows_.append(window);
return window;
}
std::shared_ptr<SubscriptionRequestEvent> QtSubscriptionRequestWindow::getEvent() {
return event_;
}
QList<QtSubscriptionRequestWindow*> QtSubscriptionRequestWindow::windows_;
}
diff --git a/Swift/QtUI/QtTabbable.cpp b/Swift/QtUI/QtTabbable.cpp
index bad6315..ed0963b 100644
--- a/Swift/QtUI/QtTabbable.cpp
+++ b/Swift/QtUI/QtTabbable.cpp
@@ -1,44 +1,43 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/QtUI/QtTabbable.h>
#include <QApplication>
#include <QKeyEvent>
#include <QShortcut>
#include <Swiften/Base/Platform.h>
-#include <Swiften/Base/foreach.h>
#include <Swift/QtUI/QtChatTabs.h>
#include <Swift/QtUI/QtUtilities.h>
namespace Swift {
QtTabbable::QtTabbable() : QWidget() {
}
QtTabbable::~QtTabbable() {
emit windowClosing();
}
bool QtTabbable::isWidgetSelected() {
/*isActiveWindow() shouldn't be necessary, but I don't trust it as far as I can throw it*/
if (!isActiveWindow()) {
return false;
}
QtChatTabs* parent = qobject_cast<QtChatTabs*>(window());
return parent ? parent->getCurrentTab() == this : isAncestorOf(QApplication::focusWidget());
}
bool QtTabbable::event(QEvent* event) {
QKeyEvent* keyEvent = dynamic_cast<QKeyEvent*>(event);
if (keyEvent) {
// According to Qt's focus documentation, one can only override CTRL+TAB via reimplementing QWidget::event().
if (keyEvent->modifiers().testFlag(QtUtilities::ctrlHardwareKeyModifier) && keyEvent->key() == Qt::Key_Tab) {
// Only handle KeyRelease event as Linux also generate KeyPress event in case of CTRL+TAB being pressed
// in the roster of a MUC.
diff --git a/Swift/QtUI/QtVCardWidget/QtTagComboBox.cpp b/Swift/QtUI/QtVCardWidget/QtTagComboBox.cpp
index ed36580..02ceb0a 100644
--- a/Swift/QtUI/QtVCardWidget/QtTagComboBox.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtTagComboBox.cpp
@@ -23,86 +23,86 @@ QtTagComboBox::QtTagComboBox(QWidget* parent) : QComboBox(parent) {
displayItem = new QStandardItem();
displayItem->setText("");
displayModel->insertRow(0, displayItem);
editMenu = new QMenu(this);
this->setModel(displayModel);
editable = true;
}
QtTagComboBox::~QtTagComboBox() {
}
bool QtTagComboBox::isEditable() const {
return editable;
}
void QtTagComboBox::setEditable(const bool editable) {
this->editable = editable;
}
void QtTagComboBox::addTag(const QString &id, const QString &label) {
QAction* tagAction = new QAction(editMenu);
tagAction->setText(label);
tagAction->setCheckable(true);
tagAction->setData(QString(id));
editMenu->addAction(tagAction);
}
void QtTagComboBox::setTag(const QString &id, bool value) {
QList<QAction*> tagActions = editMenu->actions();
- foreach(QAction* action, tagActions) {
+ for (auto action : tagActions) {
if (action->data() == id) {
action->setChecked(value);
updateDisplayItem();
return;
}
}
}
bool QtTagComboBox::isTagSet(const QString &id) const {
QList<QAction*> tagActions = editMenu->actions();
- foreach(QAction* action, tagActions) {
+ for (auto action : tagActions) {
if (action->data() == id) {
return action->isChecked();
}
}
return false;
}
void QtTagComboBox::showPopup() {
}
void QtTagComboBox::hidePopup() {
}
bool QtTagComboBox::event(QEvent* event) {
if (event->type() == QEvent::MouseButtonPress ||
event->type() == QEvent::KeyRelease) {
if (!editable) return true;
QPoint p = mapToGlobal(QPoint(0,0));
p += QPoint(0, height());
editMenu->exec(p);
updateDisplayItem();
return true;
}
return QComboBox::event(event);
}
void QtTagComboBox::updateDisplayItem() {
QList<QAction*> tagActions = editMenu->actions();
QString text = "";
- foreach(QAction* action, tagActions) {
+ for (auto action : tagActions) {
if (action->isChecked()) {
if (text != "") {
text += ", ";
}
text += action->text();
}
}
setItemText(0, text);
}
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardAddressField.cpp b/Swift/QtUI/QtVCardWidget/QtVCardAddressField.cpp
index 4043dbc..596006a 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardAddressField.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtVCardAddressField.cpp
@@ -63,61 +63,61 @@ void QtVCardAddressField::setupContentWidgets() {
pocodeLineEdit->setPlaceholderText(tr("Postal Code"));
regionLineEdit->setPlaceholderText(tr("Region"));
countryLineEdit->setPlaceholderText(tr("Country"));
#endif
deliveryTypeLabel = new QtElidingLabel(this);
deliveryTypeLabel->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard);
getGridLayout()->addWidget(deliveryTypeLabel, getGridLayout()->rowCount()-3, 4, Qt::AlignVCenter);
domesticRadioButton = new QRadioButton(tr("Domestic Delivery"), this);
getGridLayout()->addWidget(domesticRadioButton, getGridLayout()->rowCount()-2, 4, Qt::AlignVCenter);
internationalRadioButton = new QRadioButton(tr("International Delivery"), this);
getGridLayout()->addWidget(internationalRadioButton, getGridLayout()->rowCount()-1, 4, Qt::AlignVCenter);
buttonGroup = new QButtonGroup(this);
buttonGroup->addButton(domesticRadioButton);
buttonGroup->addButton(internationalRadioButton);
setTabOrder(internationalRadioButton, getTagComboBox());
getTagComboBox()->addTag("postal", tr("Postal"));
getTagComboBox()->addTag("parcel", tr("Parcel"));
QtVCardHomeWork::setTagComboBox(getTagComboBox());
textFields << streetLineEdit << poboxLineEdit << addressextLineEdit << cityLineEdit << pocodeLineEdit << regionLineEdit << countryLineEdit;
childWidgets << deliveryTypeLabel << domesticRadioButton << internationalRadioButton;
}
void QtVCardAddressField::customCleanup() {
- foreach(QWidget* widget, textFields) {
+ for (auto widget : textFields) {
widget->hide();
textFieldGridLayout->removeWidget(widget);
}
getGridLayout()->removeItem(textFieldGridLayoutItem);
}
bool QtVCardAddressField::isEmpty() const {
return streetLineEdit->text().isEmpty() &&
poboxLineEdit->text().isEmpty() &&
addressextLineEdit->text().isEmpty() &&
cityLineEdit->text().isEmpty() &&
pocodeLineEdit->text().isEmpty() &&
regionLineEdit->text().isEmpty() &&
countryLineEdit->text().isEmpty();
}
void QtVCardAddressField::setAddress(const VCard::Address& address) {
setPreferred(address.isPreferred);
setHome(address.isHome);
setWork(address.isWork);
getTagComboBox()->setTag("postal", address.isPostal);
getTagComboBox()->setTag("parcel", address.isParcel);
domesticRadioButton->setChecked(address.deliveryType == VCard::DomesticDelivery);
internationalRadioButton->setChecked(address.deliveryType == VCard::InternationalDelivery);
streetLineEdit->setText(P2QSTRING(address.street));
poboxLineEdit->setText(P2QSTRING(address.poBox));
addressextLineEdit->setText(P2QSTRING(address.addressExtension));
cityLineEdit->setText(P2QSTRING(address.locality));
@@ -143,40 +143,40 @@ VCard::Address QtVCardAddressField::getAddress() const {
address.country = Q2PSTRING(countryLineEdit->text());
return address;
}
void QtVCardAddressField::handleEditibleChanged(bool isEditable) {
assert(streetLineEdit);
assert(poboxLineEdit);
assert(addressextLineEdit);
assert(cityLineEdit);
assert(pocodeLineEdit);
assert(regionLineEdit);
assert(countryLineEdit);
assert(deliveryTypeLabel);
assert(domesticRadioButton);
assert(internationalRadioButton);
streetLineEdit->setEditable(isEditable);
poboxLineEdit->setEditable(isEditable);
addressextLineEdit->setEditable(isEditable);
cityLineEdit->setEditable(isEditable);
pocodeLineEdit->setEditable(isEditable);
regionLineEdit->setEditable(isEditable);
countryLineEdit->setEditable(isEditable);
deliveryTypeLabel->setText(buttonGroup->checkedButton() == nullptr ? "" : buttonGroup->checkedButton()->text());
deliveryTypeLabel->setVisible(!isEditable);
domesticRadioButton->setVisible(isEditable);
internationalRadioButton->setVisible(isEditable);
- foreach (QWidget* widget, textFields) {
+ for (auto widget : textFields) {
QtResizableLineEdit* lineEdit;
if ((lineEdit = dynamic_cast<QtResizableLineEdit*>(widget))) {
lineEdit->setVisible(isEditable ? true : !lineEdit->text().isEmpty());
lineEdit->setStyleSheet(isEditable ? "" : "QLineEdit { border: none; background: transparent; }");
}
}
}
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardGeneralField.cpp b/Swift/QtUI/QtVCardWidget/QtVCardGeneralField.cpp
index ab69cba..9bb6a35 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardGeneralField.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtVCardGeneralField.cpp
@@ -94,61 +94,61 @@ void QtVCardGeneralField::setStarVisible(const bool isVisible) {
starVisible = isVisible;
updatePreferredStarVisibility();
}
bool QtVCardGeneralField::getStarVisible() const {
return starVisible;
}
void QtVCardGeneralField::setPreferred(const bool preferred) {
if (preferredCheckBox) preferredCheckBox->setChecked(preferred);
updatePreferredStarVisibility();
}
bool QtVCardGeneralField::getPreferred() const {
return preferredCheckBox ? preferredCheckBox->isChecked() : false;
}
void QtVCardGeneralField::customCleanup() {
}
QtTagComboBox* QtVCardGeneralField::getTagComboBox() const {
return tagComboBox;
}
QGridLayout* QtVCardGeneralField::getGridLayout() const {
return layout;
}
void QtVCardGeneralField::handleCloseButtonClicked() {
customCleanup();
- foreach(QWidget* widget, childWidgets) {
+ for (auto widget : childWidgets) {
widget->hide();
layout->removeWidget(widget);
}
deleteField(this);
}
void QtVCardGeneralField::handlePreferredStarStateChanged(int state) {
if (state == Qt::Checked) {
QToolTip::showText(QCursor::pos(), tr("Marked as your preferred %1. Click again to undo.").arg(labelText));
}
}
void QtVCardGeneralField::updatePreferredStarVisibility() {
if (preferredCheckBox) {
bool showStar = false;
if (editable) {
if (starVisible) {
showStar = true;
}
else {
showStar = preferredCheckBox->isChecked();
}
}
else {
showStar = preferredCheckBox->isChecked();
}
preferredCheckBox->setVisible(showStar);
preferredCheckBox->setEnabled(editable);
}
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardOrganizationField.cpp b/Swift/QtUI/QtVCardWidget/QtVCardOrganizationField.cpp
index 9e303b7..5162c73 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardOrganizationField.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtVCardOrganizationField.cpp
@@ -51,101 +51,101 @@ void QtVCardOrganizationField::setupContentWidgets() {
#if QT_VERSION >= 0x050000
unitsTreeWidget->header()->setSectionResizeMode(0, QHeaderView::Stretch);
#else
unitsTreeWidget->header()->setResizeMode(0, QHeaderView::Stretch);
#endif
unitsTreeWidget->setHeaderHidden(true);
unitsTreeWidget->setRootIsDecorated(false);
unitsTreeWidget->setEditTriggers(QAbstractItemView::DoubleClicked);
unitsTreeWidget->setItemDelegateForColumn(1, itemDelegate);
connect(unitsTreeWidget, SIGNAL(itemChanged(QTreeWidgetItem*,int)), SLOT(handleItemChanged(QTreeWidgetItem*,int)));
getGridLayout()->addWidget(unitsTreeWidget, getGridLayout()->rowCount()-1, 4, 2, 1);
QTreeWidgetItem* item = new QTreeWidgetItem(QStringList("") << "");
item->setFlags(item->flags() | Qt::ItemIsEditable);
unitsTreeWidget->addTopLevelItem(item);
getTagComboBox()->hide();
organizationLabel->hide();
childWidgets << organizationLabel << organizationLineEdit << unitsTreeWidget;
}
bool QtVCardOrganizationField::isEmpty() const {
return organizationLineEdit->text().isEmpty() && unitsTreeWidget->model()->rowCount() != 0;
}
void QtVCardOrganizationField::setOrganization(const VCard::Organization& organization) {
organizationLineEdit->setText(P2QSTRING(organization.name));
unitsTreeWidget->clear();
- foreach(std::string unit, organization.units) {
+ for (const auto& unit : organization.units) {
QTreeWidgetItem* item = new QTreeWidgetItem(QStringList(P2QSTRING(unit)) << "");
item->setFlags(item->flags() | Qt::ItemIsEditable);
unitsTreeWidget->addTopLevelItem(item);
}
QTreeWidgetItem* item = new QTreeWidgetItem(QStringList("") << "");
item->setFlags(item->flags() | Qt::ItemIsEditable);
unitsTreeWidget->addTopLevelItem(item);
}
VCard::Organization QtVCardOrganizationField::getOrganization() const {
VCard::Organization organization;
organization.name = Q2PSTRING(organizationLineEdit->text());
for(int i=0; i < unitsTreeWidget->topLevelItemCount(); ++i) {
QTreeWidgetItem* row = unitsTreeWidget->topLevelItem(i);
if (!row->text(0).isEmpty()) {
organization.units.push_back(Q2PSTRING(row->text(0)));
}
}
return organization;
}
void QtVCardOrganizationField::handleEditibleChanged(bool isEditable) {
assert(organizationLineEdit);
assert(unitsTreeWidget);
organizationLineEdit->setVisible(isEditable);
organizationLabel->setVisible(!isEditable);
if (!isEditable) {
QString label;
for(int i=0; i < unitsTreeWidget->topLevelItemCount(); ++i) {
QTreeWidgetItem* row = unitsTreeWidget->topLevelItem(i);
if (!row->text(0).isEmpty()) {
label += row->text(0) + ", ";
}
}
label += organizationLineEdit->text();
organizationLabel->setText(label);
}
unitsTreeWidget->setVisible(isEditable);
}
void QtVCardOrganizationField::handleItemChanged(QTreeWidgetItem *, int) {
guaranteeEmptyRow();
}
void QtVCardOrganizationField::handleRowsRemoved(const QModelIndex&, int, int) {
guaranteeEmptyRow();
}
void QtVCardOrganizationField::guaranteeEmptyRow() {
bool hasEmptyRow = false;
QList<QTreeWidgetItem*> rows = unitsTreeWidget->findItems("", Qt::MatchFixedString);
- foreach(QTreeWidgetItem* row, rows) {
+ for (auto row : rows) {
if (row->text(0).isEmpty()) {
hasEmptyRow = true;
}
}
if (!hasEmptyRow) {
QTreeWidgetItem* item = new QTreeWidgetItem(QStringList("") << "");
item->setFlags(item->flags() | Qt::ItemIsEditable);
unitsTreeWidget->addTopLevelItem(item);
unitsTreeWidget->setCurrentItem(item);
}
}
}
diff --git a/Swift/QtUI/QtWebKitChatView.cpp b/Swift/QtUI/QtWebKitChatView.cpp
index c0ce3dc..6fe9397 100644
--- a/Swift/QtUI/QtWebKitChatView.cpp
+++ b/Swift/QtUI/QtWebKitChatView.cpp
@@ -472,61 +472,61 @@ void QtWebKitChatView::resetTopInsertPoint() {
}
std::string QtWebKitChatView::addMessage(
const ChatWindow::ChatMessage& message,
const std::string& senderName,
bool senderIsSelf,
std::shared_ptr<SecurityLabel> label,
const std::string& avatarPath,
const boost::posix_time::ptime& time) {
return addMessage(chatMessageToHTML(message), senderName, senderIsSelf, label, avatarPath, "", time, message.getFullMessageHighlightAction(), ChatSnippet::getDirection(message));
}
QString QtWebKitChatView::getHighlightSpanStart(const std::string& text, const std::string& background) {
QString ecsapeColor = QtUtilities::htmlEscape(P2QSTRING(text));
QString escapeBackground = QtUtilities::htmlEscape(P2QSTRING(background));
if (ecsapeColor.isEmpty()) {
ecsapeColor = "black";
}
if (escapeBackground.isEmpty()) {
escapeBackground = "yellow";
}
return QString("<span style=\"color: %1; background: %2\">").arg(ecsapeColor).arg(escapeBackground);
}
QString QtWebKitChatView::getHighlightSpanStart(const HighlightAction& highlight) {
return getHighlightSpanStart(highlight.getTextColor(), highlight.getTextBackground());
}
QString QtWebKitChatView::chatMessageToHTML(const ChatWindow::ChatMessage& message) {
QString result;
- foreach (std::shared_ptr<ChatWindow::ChatMessagePart> part, message.getParts()) {
+ for (const auto& part : message.getParts()) {
std::shared_ptr<ChatWindow::ChatTextMessagePart> textPart;
std::shared_ptr<ChatWindow::ChatURIMessagePart> uriPart;
std::shared_ptr<ChatWindow::ChatEmoticonMessagePart> emoticonPart;
std::shared_ptr<ChatWindow::ChatHighlightingMessagePart> highlightPart;
if ((textPart = std::dynamic_pointer_cast<ChatWindow::ChatTextMessagePart>(part))) {
QString text = QtUtilities::htmlEscape(P2QSTRING(textPart->text));
text.replace("\n","<br/>");
result += text;
continue;
}
if ((uriPart = std::dynamic_pointer_cast<ChatWindow::ChatURIMessagePart>(part))) {
QString uri = QtUtilities::htmlEscape(P2QSTRING(uriPart->target));
result += "<a href='" + uri + "' >" + uri + "</a>";
continue;
}
if ((emoticonPart = std::dynamic_pointer_cast<ChatWindow::ChatEmoticonMessagePart>(part))) {
QString textStyle = showEmoticons_ ? "style='display:none'" : "";
QString imageStyle = showEmoticons_ ? "" : "style='display:none'";
result += "<span class='swift_emoticon_image' " + imageStyle + "><img src='" + P2QSTRING(emoticonPart->imagePath) + "'/></span><span class='swift_emoticon_text' " + textStyle + ">" + QtUtilities::htmlEscape(P2QSTRING(emoticonPart->alternativeText)) + "</span>";
continue;
}
if ((highlightPart = std::dynamic_pointer_cast<ChatWindow::ChatHighlightingMessagePart>(part))) {
QString spanStart = getHighlightSpanStart(highlightPart->action.getTextColor(), highlightPart->action.getTextBackground());
result += spanStart + QtUtilities::htmlEscape(P2QSTRING(highlightPart->text)) + "</span>";
continue;
}
}
return result;
diff --git a/Swift/QtUI/Roster/QtFilterWidget.cpp b/Swift/QtUI/Roster/QtFilterWidget.cpp
index d2e4d09..2e1ead9 100644
--- a/Swift/QtUI/Roster/QtFilterWidget.cpp
+++ b/Swift/QtUI/Roster/QtFilterWidget.cpp
@@ -73,72 +73,72 @@ bool QtFilterWidget::eventFilter(QObject*, QEvent* event) {
QPoint itemOffset(2,2);
QPoint contextMenuPosition = treeView_->visualRect(treeView_->currentIndex()).topLeft() + itemOffset;;
QApplication::postEvent(treeView_, new QContextMenuEvent(QContextMenuEvent::Keyboard, contextMenuPosition, treeView_->mapToGlobal(contextMenuPosition)));
return true;
} else if (keyEvent->key() == Qt::Key_Return) {
JID target = treeView_->selectedJID();
if (target.isValid()) {
eventStream_->send(std::make_shared<RequestChatUIEvent>(target));
}
filterLineEdit_->setText("");
updateRosterFilters();
} else if (keyEvent->key() == Qt::Key_Escape) {
filterLineEdit_->setText("");
} else {
isModifierSinglePressed_ = false;
}
}
filterLineEdit_->event(event);
if (event->type() == QEvent::KeyRelease) {
updateRosterFilters();
}
return true;
}
return false;
}
void QtFilterWidget::popAllFilters() {
std::vector<RosterFilter*> filters = treeView_->getRoster()->getFilters();
- foreach(RosterFilter* filter, filters) {
+ for (auto filter : filters) {
filters_.push_back(filter);
treeView_->getRoster()->removeFilter(filter);
}
treeView_->getRoster()->onFilterAdded.connect(boost::bind(&QtFilterWidget::handleFilterAdded, this, _1));
treeView_->getRoster()->onFilterRemoved.connect(boost::bind(&QtFilterWidget::handleFilterRemoved, this, _1));
}
void QtFilterWidget::pushAllFilters() {
treeView_->getRoster()->onFilterAdded.disconnect(boost::bind(&QtFilterWidget::handleFilterAdded, this, _1));
treeView_->getRoster()->onFilterRemoved.disconnect(boost::bind(&QtFilterWidget::handleFilterRemoved, this, _1));
- foreach(RosterFilter* filter, filters_) {
+ for (auto filter : filters_) {
treeView_->getRoster()->addFilter(filter);
}
filters_.clear();
}
void QtFilterWidget::updateRosterFilters() {
if (fuzzyRosterFilter_) {
if (filterLineEdit_->text().isEmpty()) {
// remove currently installed search filter and put old filters back
treeView_->getRoster()->removeFilter(fuzzyRosterFilter_);
delete fuzzyRosterFilter_;
fuzzyRosterFilter_ = nullptr;
pushAllFilters();
} else {
// remove currently intsalled search filter and put new search filter in place
updateSearchFilter();
}
} else {
if (!filterLineEdit_->text().isEmpty()) {
// remove currently installed filters and put a search filter in place
popAllFilters();
updateSearchFilter();
}
}
filterLineEdit_->setVisible(!filterLineEdit_->text().isEmpty());
}
void QtFilterWidget::updateSearchFilter() {
if (fuzzyRosterFilter_) {
treeView_->getRoster()->removeFilter(fuzzyRosterFilter_);
diff --git a/Swift/QtUI/Roster/QtOccupantListWidget.cpp b/Swift/QtUI/Roster/QtOccupantListWidget.cpp
index 03c14fd..a12863d 100644
--- a/Swift/QtUI/Roster/QtOccupantListWidget.cpp
+++ b/Swift/QtUI/Roster/QtOccupantListWidget.cpp
@@ -23,54 +23,54 @@ namespace Swift {
QtOccupantListWidget::QtOccupantListWidget(UIEventStream* eventStream, SettingsProvider* settings, MessageTarget privateMessageTarget, QWidget* parent) : QtTreeWidget(eventStream, settings, privateMessageTarget, parent) {
}
QtOccupantListWidget::~QtOccupantListWidget() {
}
void QtOccupantListWidget::setAvailableOccupantActions(const std::vector<ChatWindow::OccupantAction>& actions) {
availableOccupantActions_ = actions;
}
void QtOccupantListWidget::contextMenuEvent(QContextMenuEvent* event) {
QModelIndex index = indexAt(event->pos());
if (!index.isValid()) {
return;
}
RosterItem* item = static_cast<RosterItem*>(index.internalPointer());
ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
if (contact) {
onSomethingSelectedChanged(contact);
QMenu contextMenu;
if (availableOccupantActions_.empty()) {
QAction* noAction = contextMenu.addAction(tr("No actions for this user"));
noAction->setEnabled(false);
contextMenu.exec(event->globalPos());
}
else {
std::map<QAction*, ChatWindow::OccupantAction> actions;
- foreach (ChatWindow::OccupantAction availableAction, availableOccupantActions_) {
+ for (const auto& availableAction : availableOccupantActions_) {
QString text = "Error: missing string";
switch (availableAction) {
case ChatWindow::Kick: text = tr("Kick user"); break;
case ChatWindow::Ban: text = tr("Kick and ban user"); break;
case ChatWindow::MakeModerator: text = tr("Make moderator"); break;
case ChatWindow::MakeParticipant: text = tr("Make participant"); break;
case ChatWindow::MakeVisitor: text = tr("Remove voice"); break;
case ChatWindow::AddContact: text = tr("Add to contacts"); break;
case ChatWindow::ShowProfile: text = tr("Show profile"); break;
}
QAction* action = contextMenu.addAction(text);
actions[action] = availableAction;
}
QAction* result = contextMenu.exec(event->globalPos());
if (result) {
onOccupantActionSelected(actions[result], contact);
}
}
}
}
}
diff --git a/Swift/QtUI/Roster/RosterModel.cpp b/Swift/QtUI/Roster/RosterModel.cpp
index 3f77c86..ef4d778 100644
--- a/Swift/QtUI/Roster/RosterModel.cpp
+++ b/Swift/QtUI/Roster/RosterModel.cpp
@@ -26,61 +26,61 @@
#include <Swift/QtUI/Roster/QtTreeWidget.h>
#include <Swift/QtUI/Roster/RosterTooltip.h>
namespace Swift {
RosterModel::RosterModel(QtTreeWidget* view, bool screenReaderMode) : roster_(nullptr), view_(view), screenReader_(screenReaderMode) {
const int tooltipAvatarSize = 96; // maximal suggested size according to XEP-0153
cachedImageScaler_ = new QtScaledAvatarCache(tooltipAvatarSize);
}
RosterModel::~RosterModel() {
delete cachedImageScaler_;
}
void RosterModel::setRoster(Roster* roster) {
roster_ = roster;
if (roster_) {
roster->onChildrenChanged.connect(boost::bind(&RosterModel::handleChildrenChanged, this, _1));
roster->onDataChanged.connect(boost::bind(&RosterModel::handleDataChanged, this, _1));
}
reLayout();
}
void RosterModel::reLayout() {
//emit layoutChanged();
beginResetModel();
endResetModel(); // TODO: Not sure if this isn't too early?
if (!roster_) {
return;
}
- foreach (RosterItem* item, roster_->getRoot()->getDisplayedChildren()) {
+ for (auto item : roster_->getRoot()->getDisplayedChildren()) {
GroupRosterItem* child = dynamic_cast<GroupRosterItem*>(item);
if (!child) continue;
emit itemExpanded(index(child), child->isExpanded());
}
}
void RosterModel::handleChildrenChanged(GroupRosterItem* /*group*/) {
reLayout();
}
void RosterModel::handleDataChanged(RosterItem* item) {
Q_ASSERT(item);
QModelIndex modelIndex = index(item);
if (modelIndex.isValid()) {
emit dataChanged(modelIndex, modelIndex);
view_->refreshTooltip();
}
}
Qt::ItemFlags RosterModel::flags(const QModelIndex& index) const {
Qt::ItemFlags flags = QAbstractItemModel::flags(index);
if (dynamic_cast<GroupRosterItem*>(getItem(index)) == nullptr) {
flags |= Qt::ItemIsDragEnabled;
}
return flags;
}
int RosterModel::columnCount(const QModelIndex& /*parent*/) const {
return 1;
}
diff --git a/Swift/QtUI/Roster/RosterTooltip.cpp b/Swift/QtUI/Roster/RosterTooltip.cpp
index 8d467fd..ea4c9cd 100644
--- a/Swift/QtUI/Roster/RosterTooltip.cpp
+++ b/Swift/QtUI/Roster/RosterTooltip.cpp
@@ -95,81 +95,81 @@ QString RosterTooltip::buildDetailedTooltip(ContactRosterItem* contact, QtScaled
QString statusMessage = contact->getStatusText().empty() ? QObject::tr("(No message)") : P2QSTRING(contact->getStatusText());
boost::posix_time::ptime idleTime = contact->getIdle();
QString idleString;
if (!idleTime.is_not_a_date_time()) {
idleString = QObject::tr("Idle since %1").arg(P2QSTRING(Swift::Translator::getInstance()->ptimeToHumanReadableString(idleTime)));
idleString = htmlEscape(idleString) + "<br/>";
}
boost::posix_time::ptime lastSeenTime = contact->getOfflineSince();
QString lastSeen;
if (!lastSeenTime.is_not_a_date_time()) {
lastSeen = QObject::tr("Last seen %1").arg(P2QSTRING(Swift::Translator::getInstance()->ptimeToHumanReadableString(lastSeenTime)));
lastSeen = htmlEscape(lastSeen) + "<br/>";
}
QString mucOccupant= P2QSTRING(contact->getMUCAffiliationText());
if (!mucOccupant.isEmpty()) {
mucOccupant = htmlEscape(mucOccupant) + "<br/>";
}
return tooltipTemplate.arg(scaledAvatarPath, htmlEscape(fullName), htmlEscape(bareJID), presenceIconTag, htmlEscape(statusMessage), mucOccupant, idleString, lastSeen, vCardSummary);
}
QString RosterTooltip::buildVCardSummary(VCard::ref vcard) {
QString summary;
summary = "<table>";
// star | name | content
QString currentBlock;
- foreach (const VCard::Telephone& tel, vcard->getTelephones()) {
+ for (const auto& tel : vcard->getTelephones()) {
QString type = tel.isFax ? QObject::tr("Fax") : QObject::tr("Telephone");
QString field = buildVCardField(tel.isPreferred, type, htmlEscape(P2QSTRING(tel.number)));
if (tel.isPreferred) {
currentBlock = field;
break;
}
currentBlock += field;
}
summary += currentBlock;
currentBlock = "";
- foreach (const VCard::EMailAddress& mail, vcard->getEMailAddresses()) {
+ for (const auto& mail : vcard->getEMailAddresses()) {
QString field = buildVCardField(mail.isPreferred, QObject::tr("E-Mail"), htmlEscape(P2QSTRING(mail.address)));
if (mail.isPreferred) {
currentBlock = field;
break;
}
currentBlock += field;
}
summary += currentBlock;
currentBlock = "";
- foreach (const VCard::Organization& org, vcard->getOrganizations()) {
+ for (const auto& org : vcard->getOrganizations()) {
QString field = buildVCardField(false, QObject::tr("Organization"), htmlEscape(P2QSTRING(org.name)));
currentBlock += field;
}
summary += currentBlock;
currentBlock = "";
- foreach(const std::string& title, vcard->getTitles()) {
+ for (const auto& title : vcard->getTitles()) {
QString field = buildVCardField(false, QObject::tr("Title"), htmlEscape(P2QSTRING(title)));
currentBlock += field;
}
summary += currentBlock;
summary += "</table>";
return summary;
}
QString RosterTooltip::buildVCardField(bool preferred, const QString& name, const QString& content) {
QString rowTemplate;
if (QApplication::layoutDirection() == Qt::RightToLeft) {
rowTemplate = QString("<tr><td>%3</td><td valign='middle'><strong>%2</strong></td><td valign='middle'>%1</td></tr>");
} else {
rowTemplate = QString("<tr><td>%1</td><td valign='middle'><strong>%2</strong></td><td valign='middle'>%3</td></tr>");
}
return rowTemplate.arg(preferred ? "<img src=':/icons/star-checked.png' />" : "", name, content);
}
}
diff --git a/Swift/QtUI/UserSearch/ContactListModel.cpp b/Swift/QtUI/UserSearch/ContactListModel.cpp
index 376d3b1..6ef85d7 100644
--- a/Swift/QtUI/UserSearch/ContactListModel.cpp
+++ b/Swift/QtUI/UserSearch/ContactListModel.cpp
@@ -1,48 +1,47 @@
/*
* Copyright (c) 2013 Tobias Markmann
* Licensed under the simplified BSD license.
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
/*
* Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/QtUI/UserSearch/ContactListModel.h>
#include <QMimeData>
#include <Swiften/Base/Path.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Elements/StatusShow.h>
#include <Swift/QtUI/QtResourceHelper.h>
#include <Swift/QtUI/QtSwiftUtil.h>
namespace Swift {
QDataStream& operator >>(QDataStream& in, StatusShow::Type& e){
quint32 buffer;
in >> buffer;
switch(buffer) {
case StatusShow::Online:
e = StatusShow::Online;
break;
case StatusShow::Away:
e = StatusShow::Away;
break;
case StatusShow::FFC:
e = StatusShow::FFC;
break;
case StatusShow::XA:
e = StatusShow::XA;
break;
case StatusShow::DND:
e = StatusShow::DND;
break;
default:
e = StatusShow::None;
break;
}
diff --git a/Swift/QtUI/UserSearch/QtContactListWidget.cpp b/Swift/QtUI/UserSearch/QtContactListWidget.cpp
index 1dbfc1f..73a8482 100644
--- a/Swift/QtUI/UserSearch/QtContactListWidget.cpp
+++ b/Swift/QtUI/UserSearch/QtContactListWidget.cpp
@@ -58,46 +58,46 @@ QtContactListWidget::QtContactListWidget(QWidget* parent, SettingsProvider* sett
}
QtContactListWidget::~QtContactListWidget() {
delete contactListDelegate_;
delete removableItemDelegate_;
delete contactListModel_;
}
void QtContactListWidget::setList(const std::vector<Contact::ref>& list) {
contactListModel_->setList(list);
}
std::vector<Contact::ref> QtContactListWidget::getList() const {
return contactListModel_->getList();
}
Contact::ref QtContactListWidget::getContact(const size_t i) {
return contactListModel_->getContact(i);
}
void QtContactListWidget::setMaximumNoOfContactsToOne(bool limited) {
limited_ = limited;
}
bool QtContactListWidget::isFull() const {
return limited_ && (getList().size() == 1);
}
void QtContactListWidget::updateContacts(const std::vector<Contact::ref>& contactUpdates) {
std::vector<Contact::ref> contacts = contactListModel_->getList();
- foreach(const Contact::ref& contactUpdate, contactUpdates) {
- for(auto& contact : contacts) {
+ for (const auto& contactUpdate : contactUpdates) {
+ for (auto&& contact : contacts) {
if (contactUpdate->jid == contact->jid) {
contact = contactUpdate;
break;
}
}
}
contactListModel_->setList(contacts);
}
void QtContactListWidget::handleSettingsChanged(const std::string&) {
contactListDelegate_->setCompact(settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER));
}
}
diff --git a/Swift/QtUI/WinUIHelpers.cpp b/Swift/QtUI/WinUIHelpers.cpp
index 4898916..ec39c38 100644
--- a/Swift/QtUI/WinUIHelpers.cpp
+++ b/Swift/QtUI/WinUIHelpers.cpp
@@ -1,53 +1,51 @@
/*
* Copyright (c) 2012 Tobias Markmann
* Licensed under the simplified BSD license.
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
/*
* Copyright (c) 2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/QtUI/WinUIHelpers.h>
#include <windows.h>
#include <Wincrypt.h>
#include <cryptuiapi.h>
#pragma comment(lib, "cryptui.lib")
#include <memory>
-#include <Swiften/Base/foreach.h>
-
namespace Swift {
void WinUIHelpers::displayCertificateChainAsSheet(QWidget* parent, const std::vector<Certificate::ref>& chain) {
if (chain.empty()) {
return;
}
// create certificate store to store the certificate chain in
HCERTSTORE chainStore = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, NULL, CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG, NULL);
if (!chainStore) {
return;
}
ByteArray certAsDER = chain[0]->toDER();
std::shared_ptr<const CERT_CONTEXT> certificate_chain;
{
PCCERT_CONTEXT certChain;
BOOL ok = CertAddCertificateContextToStore(chainStore, CertCreateCertificateContext(X509_ASN_ENCODING, vecptr(certAsDER), certAsDER.size()), CERT_STORE_ADD_ALWAYS, &certChain);
// maybe free the cert contex we created
if (!ok || !certChain) {
return;
}
certificate_chain.reset(certChain, CertFreeCertificateContext);
}
for (size_t i = 1; i < chain.size(); ++i) {
ByteArray certAsDER = chain[i]->toDER();
CertAddCertificateContextToStore(chainStore, CertCreateCertificateContext(X509_ASN_ENCODING, vecptr(certAsDER), certAsDER.size()), CERT_STORE_ADD_ALWAYS, NULL);
}