summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--3rdParty/Boost/src/boost/range/adaptor/reversed.hpp103
-rwxr-xr-x3rdParty/Boost/update.sh4
-rw-r--r--Slimber/LinkLocalPresenceManager.cpp9
-rw-r--r--Slimber/MainController.cpp3
-rw-r--r--Slimber/MenuletController.cpp4
-rw-r--r--Slimber/Server.cpp18
-rw-r--r--Sluift/ElementConvertors/CommandConvertor.cpp6
-rw-r--r--Sluift/ElementConvertors/DOMElementConvertor.cpp3
-rw-r--r--Sluift/ElementConvertors/FormConvertor.cpp14
-rw-r--r--Sluift/ElementConvertors/ForwardedConvertor.cpp1
-rw-r--r--Sluift/ElementConvertors/PubSubAffiliationsConvertor.cpp4
-rw-r--r--Sluift/ElementConvertors/PubSubEventItemConvertor.cpp4
-rw-r--r--Sluift/ElementConvertors/PubSubEventItemsConvertor.cpp6
-rw-r--r--Sluift/ElementConvertors/PubSubItemConvertor.cpp4
-rw-r--r--Sluift/ElementConvertors/PubSubItemsConvertor.cpp4
-rw-r--r--Sluift/ElementConvertors/PubSubOwnerAffiliationsConvertor.cpp4
-rw-r--r--Sluift/ElementConvertors/PubSubOwnerSubscriptionsConvertor.cpp4
-rw-r--r--Sluift/ElementConvertors/PubSubPublishConvertor.cpp4
-rw-r--r--Sluift/ElementConvertors/PubSubRetractConvertor.cpp4
-rw-r--r--Sluift/ElementConvertors/PubSubSubscriptionsConvertor.cpp4
-rw-r--r--Sluift/ElementConvertors/SecurityLabelConvertor.cpp4
-rw-r--r--Sluift/ElementConvertors/StanzaConvertor.h3
-rw-r--r--Sluift/Lua/FunctionRegistry.cpp4
-rw-r--r--Sluift/Lua/Value.cpp4
-rw-r--r--Sluift/LuaElementConvertors.cpp6
-rw-r--r--Sluift/client.cpp3
-rw-r--r--Sluift/component.cpp1
-rw-r--r--Sluift/main.cpp21
-rw-r--r--Sluift/sluift.cpp9
-rw-r--r--SwifTools/Application/ApplicationPathProvider.cpp3
-rw-r--r--SwifTools/Application/UnixApplicationPathProvider.cpp8
-rw-r--r--SwifTools/Notifier/GNTPNotifier.cpp3
-rw-r--r--SwifTools/TabComplete.cpp4
-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
-rw-r--r--Swiften/Base/foreach.h13
-rw-r--r--Swiften/Chat/UnitTest/ChatStateNotifierTest.cpp5
-rw-r--r--Swiften/Client/BlockListImpl.cpp12
-rw-r--r--Swiften/Client/CoreClient.cpp3
-rw-r--r--Swiften/Client/UnitTest/ClientBlockListManagerTest.cpp3
-rw-r--r--Swiften/Client/XMLBeautifier.cpp3
-rw-r--r--Swiften/Disco/CapsInfoGenerator.cpp11
-rw-r--r--Swiften/Disco/DiscoServiceWalker.cpp9
-rw-r--r--Swiften/Elements/Form.cpp6
-rw-r--r--Swiften/Elements/RosterItemExchangePayload.cpp2
-rw-r--r--Swiften/Elements/RosterPayload.cpp4
-rw-r--r--Swiften/Elements/Stanza.cpp5
-rw-r--r--Swiften/Elements/VCard.cpp6
-rw-r--r--Swiften/EventLoop/EventLoop.cpp3
-rw-r--r--Swiften/EventLoop/SimpleEventLoop.cpp2
-rw-r--r--Swiften/EventLoop/SingleThreadedEventLoop.cpp5
-rw-r--r--Swiften/Examples/MUCListAndJoin/MUCListAndJoin.cpp3
-rw-r--r--Swiften/Examples/SendFile/ReceiveFile.cpp4
-rw-r--r--Swiften/FileTransfer/DefaultFileTransferTransporter.cpp3
-rw-r--r--Swiften/FileTransfer/IncomingJingleFileTransfer.cpp5
-rw-r--r--Swiften/FileTransfer/JingleFileTransfer.cpp3
-rw-r--r--Swiften/FileTransfer/OutgoingJingleFileTransfer.cpp3
-rw-r--r--Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.cpp3
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamProxyFinder.cpp4
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamRegistry.cpp1
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamServer.cpp5
-rw-r--r--Swiften/Jingle/JingleSession.cpp3
-rw-r--r--Swiften/Jingle/JingleSessionManager.cpp3
-rw-r--r--Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuerier.cpp5
-rw-r--r--Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.cpp23
-rw-r--r--Swiften/LinkLocal/OutgoingLinkLocalSession.cpp3
-rw-r--r--Swiften/MUC/MUCBookmarkManager.cpp9
-rw-r--r--Swiften/Network/BOSHConnectionPool.cpp13
-rw-r--r--Swiften/Network/ChainedConnector.cpp1
-rw-r--r--Swiften/Network/DummyTimerFactory.cpp3
-rw-r--r--Swiften/Network/HTTPConnectProxiedConnection.cpp7
-rw-r--r--Swiften/Network/NetworkEnvironment.cpp5
-rw-r--r--Swiften/Network/PlatformDomainNameServiceQuery.cpp3
-rw-r--r--Swiften/Network/UnixProxyProvider.cpp1
-rw-r--r--Swiften/Network/WindowsNetworkEnvironment.cpp5
-rw-r--r--Swiften/Parser/PayloadParsers/BytestreamsParser.cpp4
-rw-r--r--Swiften/Parser/PayloadParsers/FormParser.cpp10
-rw-r--r--Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.cpp5
-rw-r--r--Swiften/Parser/PayloadParsers/IBBParser.cpp1
-rw-r--r--Swiften/Parser/PayloadParsers/MUCAdminPayloadParser.cpp5
-rw-r--r--Swiften/Parser/PayloadParsers/MUCDestroyPayloadParser.cpp4
-rw-r--r--Swiften/Parser/PayloadParsers/MUCUserPayloadParser.cpp3
-rw-r--r--Swiften/Parser/PayloadParsers/StreamInitiationParser.cpp4
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/MUCUserPayloadParserTest.cpp3
-rw-r--r--Swiften/Parser/PayloadParsers/VCardParser.cpp3
-rw-r--r--Swiften/Parser/SerializingParser.cpp3
-rw-r--r--Swiften/Parser/Tree/TreeReparser.cpp3
-rw-r--r--Swiften/Presence/DirectedPresenceSender.cpp4
-rw-r--r--Swiften/Presence/SubscriptionManager.cpp3
-rw-r--r--Swiften/QA/ConcurrentFileTransferTest/ConcurrentFileTransferTest.cpp1
-rw-r--r--Swiften/QA/FileTransferTest/FileTransferTest.cpp9
-rw-r--r--Swiften/QA/ProxyProviderTest/ProxyProviderTest.cpp1
-rw-r--r--Swiften/Queries/IQRouter.cpp3
-rw-r--r--Swiften/Roster/XMPPRosterController.cpp7
-rw-r--r--Swiften/Roster/XMPPRosterImpl.cpp8
-rw-r--r--Swiften/Serializer/PayloadSerializers/BytestreamsSerializer.cpp3
-rw-r--r--Swiften/Serializer/PayloadSerializers/CommandSerializer.cpp5
-rw-r--r--Swiften/Serializer/PayloadSerializers/DiscoInfoSerializer.cpp7
-rw-r--r--Swiften/Serializer/PayloadSerializers/DiscoItemsSerializer.cpp3
-rw-r--r--Swiften/Serializer/PayloadSerializers/FormSerializer.cpp39
-rw-r--r--Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.cpp5
-rw-r--r--Swiften/Serializer/PayloadSerializers/IBBSerializer.cpp1
-rw-r--r--Swiften/Serializer/PayloadSerializers/InBandRegistrationPayloadSerializer.cpp1
-rw-r--r--Swiften/Serializer/PayloadSerializers/JingleContentPayloadSerializer.cpp5
-rw-r--r--Swiften/Serializer/PayloadSerializers/JingleFileTransferDescriptionSerializer.cpp1
-rw-r--r--Swiften/Serializer/PayloadSerializers/JingleFileTransferFileInfoSerializer.cpp3
-rw-r--r--Swiften/Serializer/PayloadSerializers/JingleFileTransferHashSerializer.cpp1
-rw-r--r--Swiften/Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.cpp1
-rw-r--r--Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.cpp3
-rw-r--r--Swiften/Serializer/PayloadSerializers/JingleS5BTransportPayloadSerializer.cpp3
-rw-r--r--Swiften/Serializer/PayloadSerializers/MUCAdminPayloadSerializer.cpp3
-rw-r--r--Swiften/Serializer/PayloadSerializers/MUCDestroyPayloadSerializer.cpp1
-rw-r--r--Swiften/Serializer/PayloadSerializers/MUCInvitationPayloadSerializer.cpp1
-rw-r--r--Swiften/Serializer/PayloadSerializers/MUCUserPayloadSerializer.cpp5
-rw-r--r--Swiften/Serializer/PayloadSerializers/PrivateStorageSerializer.cpp1
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubAffiliationsSerializer.cpp5
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventItemSerializer.cpp5
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventItemsSerializer.cpp7
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventSerializer.cpp3
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubItemSerializer.cpp5
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubItemsSerializer.cpp5
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationsSerializer.cpp4
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubOwnerPubSubSerializer.cpp3
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionsSerializer.cpp4
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubPublishSerializer.cpp5
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubRetractSerializer.cpp3
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubSerializer.cpp5
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubSubscriptionsSerializer.cpp3
-rw-r--r--Swiften/Serializer/PayloadSerializers/RosterItemExchangeSerializer.cpp5
-rw-r--r--Swiften/Serializer/PayloadSerializers/RosterSerializer.cpp5
-rw-r--r--Swiften/Serializer/PayloadSerializers/SearchPayloadSerializer.cpp3
-rw-r--r--Swiften/Serializer/PayloadSerializers/SecurityLabelSerializer.cpp3
-rw-r--r--Swiften/Serializer/PayloadSerializers/SecurityLabelsCatalogSerializer.cpp3
-rw-r--r--Swiften/Serializer/PayloadSerializers/StorageSerializer.cpp5
-rw-r--r--Swiften/Serializer/PayloadSerializers/StreamInitiationFileInfoSerializer.cpp1
-rw-r--r--Swiften/Serializer/PayloadSerializers/StreamInitiationSerializer.cpp3
-rw-r--r--Swiften/Serializer/PayloadSerializers/VCardSerializer.cpp23
-rw-r--r--Swiften/Serializer/StanzaSerializer.cpp3
-rw-r--r--Swiften/Serializer/StreamFeaturesSerializer.cpp5
-rw-r--r--Swiften/Serializer/XML/XMLElement.cpp6
-rw-r--r--Swiften/Serializer/XMPPSerializer.cpp1
-rw-r--r--Swiften/Session/BOSHSessionStream.cpp1
-rw-r--r--Swiften/StreamStack/StreamStack.cpp1
-rw-r--r--Swiften/TLS/ServerIdentityVerifier.cpp9
-rw-r--r--Swiften/Whiteboard/WhiteboardSessionManager.cpp3
215 files changed, 533 insertions, 684 deletions
diff --git a/3rdParty/Boost/src/boost/range/adaptor/reversed.hpp b/3rdParty/Boost/src/boost/range/adaptor/reversed.hpp
new file mode 100644
index 0000000..944fbff
--- /dev/null
+++ b/3rdParty/Boost/src/boost/range/adaptor/reversed.hpp
@@ -0,0 +1,103 @@
+// Boost.Range library
+//
+// Copyright Thorsten Ottosen, Neil Groves 2006 - 2008. Use, modification and
+// distribution is subject to the Boost Software License, Version
+// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+//
+// For more information, see http://www.boost.org/libs/range/
+//
+
+#ifndef BOOST_RANGE_ADAPTOR_REVERSED_HPP
+#define BOOST_RANGE_ADAPTOR_REVERSED_HPP
+
+#include <boost/range/iterator_range.hpp>
+#include <boost/range/concepts.hpp>
+#include <boost/iterator/reverse_iterator.hpp>
+
+namespace boost
+{
+ namespace range_detail
+ {
+ template< class R >
+ struct reversed_range :
+ public boost::iterator_range<
+ boost::reverse_iterator<
+ BOOST_DEDUCED_TYPENAME range_iterator<R>::type
+ >
+ >
+ {
+ private:
+ typedef boost::iterator_range<
+ boost::reverse_iterator<
+ BOOST_DEDUCED_TYPENAME range_iterator<R>::type
+ >
+ >
+ base;
+
+ public:
+ typedef boost::reverse_iterator<BOOST_DEDUCED_TYPENAME range_iterator<R>::type> iterator;
+
+ explicit reversed_range( R& r )
+ : base( iterator(boost::end(r)), iterator(boost::begin(r)) )
+ { }
+ };
+
+ struct reverse_forwarder {};
+
+ template< class BidirectionalRange >
+ inline reversed_range<BidirectionalRange>
+ operator|( BidirectionalRange& r, reverse_forwarder )
+ {
+ BOOST_RANGE_CONCEPT_ASSERT((
+ BidirectionalRangeConcept<BidirectionalRange>));
+
+ return reversed_range<BidirectionalRange>( r );
+ }
+
+ template< class BidirectionalRange >
+ inline reversed_range<const BidirectionalRange>
+ operator|( const BidirectionalRange& r, reverse_forwarder )
+ {
+ BOOST_RANGE_CONCEPT_ASSERT((
+ BidirectionalRangeConcept<const BidirectionalRange>));
+
+ return reversed_range<const BidirectionalRange>( r );
+ }
+
+ } // 'range_detail'
+
+ using range_detail::reversed_range;
+
+ namespace adaptors
+ {
+ namespace
+ {
+ const range_detail::reverse_forwarder reversed =
+ range_detail::reverse_forwarder();
+ }
+
+ template<class BidirectionalRange>
+ inline reversed_range<BidirectionalRange>
+ reverse(BidirectionalRange& rng)
+ {
+ BOOST_RANGE_CONCEPT_ASSERT((
+ BidirectionalRangeConcept<BidirectionalRange>));
+
+ return reversed_range<BidirectionalRange>(rng);
+ }
+
+ template<class BidirectionalRange>
+ inline reversed_range<const BidirectionalRange>
+ reverse(const BidirectionalRange& rng)
+ {
+ BOOST_RANGE_CONCEPT_ASSERT((
+ BidirectionalRangeConcept<const BidirectionalRange>));
+
+ return reversed_range<const BidirectionalRange>(rng);
+ }
+ } // 'adaptors'
+
+} // 'boost'
+
+#endif
diff --git a/3rdParty/Boost/update.sh b/3rdParty/Boost/update.sh
index 44114ed..afa7722 100755
--- a/3rdParty/Boost/update.sh
+++ b/3rdParty/Boost/update.sh
@@ -1,86 +1,84 @@
#!/usr/bin/env bash
set -e
if [ -z "$1" ]; then
echo "Please specify the location of the boost source tree"
exit -1
fi
TARGET_DIR=src
if [ ! -d "$TARGET_DIR" ]; then
mkdir $TARGET_DIR
fi
./bcp --boost="$1" \
tools/bcp \
algorithm/string.hpp \
archive/text_iarchive.hpp \
archive/text_oarchive.hpp \
asio.hpp \
assign/list_of.hpp \
bind.hpp \
cast.hpp \
date_time/posix_time/posix_time.hpp \
date_time/posix_time/time_serialize.hpp \
date_time/local_time/local_time.hpp \
date_time/c_local_time_adjustor.hpp \
date_time/gregorian/gregorian_types.hpp \
- foreach.hpp \
filesystem.hpp \
filesystem/fstream.hpp \
format.hpp \
lambda/lambda.hpp \
lambda/bind.hpp \
logic/tribool.hpp \
noncopyable.hpp \
numeric/conversion/cast.hpp \
optional.hpp \
program_options.hpp \
random/mersenne_twister.hpp \
random/variate_generator.hpp \
random/uniform_int.hpp \
regex.hpp \
scope_exit.hpp \
- shared_ptr.hpp \
- smart_ptr/make_shared.hpp \
serialization/serialization.hpp \
serialization/vector.hpp \
serialization/list.hpp \
serialization/map.hpp \
serialization/shared_ptr.hpp \
serialization/string.hpp \
serialization/set.hpp \
serialization/version.hpp \
serialization/split_member.hpp \
serialization/optional.hpp \
signals2.hpp \
thread.hpp \
unordered_map.hpp \
uuid/uuid.hpp \
uuid/uuid_io.hpp \
uuid/uuid_generators.hpp \
variant.hpp \
spirit/include/lex_lexertl.hpp \
typeof/incr_registration_group.hpp \
atomic \
system/src/error_code.cpp \
phoenix/support/detail/iterate.hpp \
type_traits.hpp \
+ range/adaptor/reversed.hpp \
$TARGET_DIR
cp $1/LICENSE_1_0.txt $TARGET_DIR
rm -rf $TARGET_DIR/libs/config
rm -rf $TARGET_DIR/libs/smart_ptr
LIBS="date_time regex system thread signals2 filesystem program_options serialization archive atomic"
for lib in $LIBS; do
rm -rf $TARGET_DIR/libs/$lib/build $TARGET_DIR/libs/$lib/*.doc $TARGET_DIR/libs/$lib/src/*.doc $TARGET_DIR/libs/$lib/src/CMakeLists.txt $TARGET_DIR/libs/$lib/test
done
rm -rf $TARGET_DIR/tools/bcp/*.html $TARGET_DIR/libs/test $TARGET_DIR/doc $TARGET_DIR/boost.png $TARGET_DIR/boost/test $TARGET_DIR/tools/bcp/Jamfile.v2 $TARGET_DIR/tools/bcp/doc $TARGET_DIR/tools/bcp/test $TARGET_DIR/Jamroot
mv $TARGET_DIR/libs/filesystem/src/utf8_codecvt_facet.cpp $TARGET_DIR/libs/filesystem/src/filesystem_utf8_codecvt_facet.cpp
mv $TARGET_DIR/libs/program_options/src/utf8_codecvt_facet.cpp $TARGET_DIR/libs/program_options/src/program_options_utf8_codecvt_facet.cpp
for diff in *.diff; do
patch -p3 < $diff
done
diff --git a/Slimber/LinkLocalPresenceManager.cpp b/Slimber/LinkLocalPresenceManager.cpp
index f166b38..ec5f2cd 100644
--- a/Slimber/LinkLocalPresenceManager.cpp
+++ b/Slimber/LinkLocalPresenceManager.cpp
@@ -1,100 +1,99 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Slimber/LinkLocalPresenceManager.h>
#include <boost/bind.hpp>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Elements/Presence.h>
#include <Swiften/Elements/RosterPayload.h>
#include <Swiften/LinkLocal/LinkLocalServiceBrowser.h>
namespace Swift {
LinkLocalPresenceManager::LinkLocalPresenceManager(LinkLocalServiceBrowser* browser) : browser(browser) {
browser->onServiceAdded.connect(
boost::bind(&LinkLocalPresenceManager::handleServiceAdded, this, _1));
browser->onServiceChanged.connect(
boost::bind(&LinkLocalPresenceManager::handleServiceChanged, this, _1));
browser->onServiceRemoved.connect(
boost::bind(&LinkLocalPresenceManager::handleServiceRemoved, this, _1));
}
boost::optional<LinkLocalService> LinkLocalPresenceManager::getServiceForJID(const JID& j) const {
- foreach(const LinkLocalService& service, browser->getServices()) {
+ for (const auto& service : browser->getServices()) {
if (service.getJID() == j) {
return service;
}
}
return boost::optional<LinkLocalService>();
}
void LinkLocalPresenceManager::handleServiceAdded(const LinkLocalService& service) {
std::shared_ptr<RosterPayload> roster(new RosterPayload());
roster->addItem(getRosterItem(service));
onRosterChanged(roster);
onPresenceChanged(getPresence(service));
}
void LinkLocalPresenceManager::handleServiceChanged(const LinkLocalService& service) {
onPresenceChanged(getPresence(service));
}
void LinkLocalPresenceManager::handleServiceRemoved(const LinkLocalService& service) {
std::shared_ptr<RosterPayload> roster(new RosterPayload());
roster->addItem(RosterItemPayload(service.getJID(), "", RosterItemPayload::Remove));
onRosterChanged(roster);
}
std::shared_ptr<RosterPayload> LinkLocalPresenceManager::getRoster() const {
std::shared_ptr<RosterPayload> roster(new RosterPayload());
- foreach(const LinkLocalService& service, browser->getServices()) {
+ for (const auto& service : browser->getServices()) {
roster->addItem(getRosterItem(service));
}
return roster;
}
std::vector<std::shared_ptr<Presence> > LinkLocalPresenceManager::getAllPresence() const {
std::vector<std::shared_ptr<Presence> > result;
- foreach(const LinkLocalService& service, browser->getServices()) {
+ for (const auto& service : browser->getServices()) {
result.push_back(getPresence(service));
}
return result;
}
RosterItemPayload LinkLocalPresenceManager::getRosterItem(const LinkLocalService& service) const {
- return RosterItemPayload(service.getJID(), getRosterName(service), RosterItemPayload::Both);
+ return RosterItemPayload(service.getJID(), getRosterName(service), RosterItemPayload::Both);
}
std::string LinkLocalPresenceManager::getRosterName(const LinkLocalService& service) const {
LinkLocalServiceInfo info = service.getInfo();
if (!info.getNick().empty()) {
return info.getNick();
}
else if (!info.getFirstName().empty()) {
std::string result = info.getFirstName();
if (!info.getLastName().empty()) {
result += " " + info.getLastName();
}
return result;
}
else if (!info.getLastName().empty()) {
return info.getLastName();
}
return "";
}
std::shared_ptr<Presence> LinkLocalPresenceManager::getPresence(const LinkLocalService& service) const {
std::shared_ptr<Presence> presence(new Presence());
presence->setFrom(service.getJID());
switch (service.getInfo().getStatus()) {
case LinkLocalServiceInfo::Available:
presence->setShow(StatusShow::Online);
break;
case LinkLocalServiceInfo::Away:
presence->setShow(StatusShow::Away);
break;
diff --git a/Slimber/MainController.cpp b/Slimber/MainController.cpp
index dcec6d5..cd36132 100644
--- a/Slimber/MainController.cpp
+++ b/Slimber/MainController.cpp
@@ -1,42 +1,41 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Slimber/MainController.h>
#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
-#include <Swiften/Base/foreach.h>
#include <Swiften/LinkLocal/DNSSD/PlatformDNSSDQuerierFactory.h>
#include <Swiften/LinkLocal/LinkLocalService.h>
#include <Swiften/LinkLocal/LinkLocalServiceBrowser.h>
#include <Slimber/FileVCardCollection.h>
#include <Slimber/Menulet.h>
#include <Slimber/MenuletController.h>
#include <Slimber/Server.h>
#include <SwifTools/Application/PlatformApplicationPathProvider.h>
using namespace Swift;
MainController::MainController(Menulet* menulet, EventLoop* eventLoop) {
dnsSDQuerier = PlatformDNSSDQuerierFactory(eventLoop).createQuerier();
assert(dnsSDQuerier);
linkLocalServiceBrowser = new LinkLocalServiceBrowser(dnsSDQuerier);
linkLocalServiceBrowser->onServiceAdded.connect(
boost::bind(&MainController::handleServicesChanged, this));
linkLocalServiceBrowser->onServiceRemoved.connect(
boost::bind(&MainController::handleServicesChanged, this));
linkLocalServiceBrowser->onServiceChanged.connect(
boost::bind(&MainController::handleServicesChanged, this));
vCardCollection = new FileVCardCollection(
PlatformApplicationPathProvider("Slimber").getDataDir());
server = new Server(5222, 5562, linkLocalServiceBrowser, vCardCollection, eventLoop);
server->onStopped.connect(
@@ -61,61 +60,61 @@ MainController::~MainController() {
dnsSDQuerier->stop();
}
void MainController::start() {
dnsSDQuerier->start();
linkLocalServiceBrowser->start();
handleSelfConnected(false);
handleServicesChanged();
server->start();
}
void MainController::stop() {
server->stop();
linkLocalServiceBrowser->stop();
dnsSDQuerier->stop();
}
void MainController::handleSelfConnected(bool b) {
if (b) {
menuletController->setXMPPStatus("You are logged in", MenuletController::Online);
}
else {
menuletController->setXMPPStatus("You are not logged in", MenuletController::Offline);
}
}
void MainController::handleServicesChanged() {
std::vector<std::string> names;
- foreach(const LinkLocalService& service, linkLocalServiceBrowser->getServices()) {
+ for (const auto& service : linkLocalServiceBrowser->getServices()) {
std::string description = service.getDescription();
if (description != service.getName()) {
description += " (" + service.getName() + ")";
}
names.push_back(description);
}
menuletController->setUserNames(names);
}
void MainController::handleServerStopped(boost::optional<ServerError> error) {
if (error) {
std::string message;
switch (error->getType()) {
case ServerError::C2SPortConflict:
message = std::string("Error: Port ") + boost::lexical_cast<std::string>(server->getClientToServerPort()) + std::string(" in use");
break;
case ServerError::C2SError:
message = std::string("Local connection server error");
break;
case ServerError::LinkLocalPortConflict:
message = std::string("Error: Port ") + boost::lexical_cast<std::string>(server->getLinkLocalPort()) + std::string(" in use");
break;
case ServerError::LinkLocalError:
message = std::string("External connection server error");
break;
}
menuletController->setXMPPStatus(message, MenuletController::Offline);
}
else {
menuletController->setXMPPStatus("XMPP Server Not Running", MenuletController::Offline);
diff --git a/Slimber/MenuletController.cpp b/Slimber/MenuletController.cpp
index fdf2fc7..5ea5bc9 100644
--- a/Slimber/MenuletController.cpp
+++ b/Slimber/MenuletController.cpp
@@ -1,55 +1,53 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Slimber/MenuletController.h>
#include <string>
-#include <Swiften/Base/foreach.h>
-
#include <Slimber/Menulet.h>
MenuletController::MenuletController(Menulet* menulet) :
menulet(menulet), xmppStatus(Offline) {
menulet->onRestartClicked.connect(boost::ref(onRestartRequested));
update();
}
MenuletController::~MenuletController() {
}
void MenuletController::setXMPPStatus(const std::string& message, Status status) {
xmppStatus = status;
xmppStatusMessage = message;
update();
}
void MenuletController::setUserNames(const std::vector<std::string>& users) {
linkLocalUsers = users;
update();
}
void MenuletController::update() {
menulet->clear();
if (linkLocalUsers.empty()) {
menulet->setIcon("UsersOffline");
menulet->addItem("No online users");
}
else {
menulet->setIcon("UsersOnline");
menulet->addItem("Online users:");
- foreach(const std::string& user, linkLocalUsers) {
+ for (const auto& user : linkLocalUsers) {
menulet->addItem(std::string(" ") + user);
}
}
menulet->addSeparator();
menulet->addItem(xmppStatusMessage, (xmppStatus == Online ? "Online" : "Offline"));
menulet->addSeparator();
menulet->addAboutItem();
menulet->addSeparator();
menulet->addRestartItem();
menulet->addExitItem();
}
diff --git a/Slimber/Server.cpp b/Slimber/Server.cpp
index 7e24abe..3bc3112 100644
--- a/Slimber/Server.cpp
+++ b/Slimber/Server.cpp
@@ -1,45 +1,45 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Slimber/Server.h>
+#include <cassert>
#include <string>
#include <boost/bind.hpp>
#include <Swiften/Base/Log.h>
#include <Swiften/Base/String.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Elements/IQ.h>
#include <Swiften/Elements/Presence.h>
#include <Swiften/Elements/RosterPayload.h>
#include <Swiften/Elements/ToplevelElement.h>
#include <Swiften/Elements/VCard.h>
#include <Swiften/LinkLocal/IncomingLinkLocalSession.h>
#include <Swiften/LinkLocal/LinkLocalConnector.h>
#include <Swiften/LinkLocal/LinkLocalServiceBrowser.h>
#include <Swiften/LinkLocal/LinkLocalServiceInfo.h>
#include <Swiften/LinkLocal/OutgoingLinkLocalSession.h>
#include <Swiften/Network/BoostConnection.h>
#include <Swiften/Network/BoostConnectionServer.h>
#include <Swiften/Network/Connection.h>
#include <Swiften/Network/ConnectionServer.h>
#include <Swiften/Session/Session.h>
#include <Swiften/Session/SessionTracer.h>
#include <Limber/Server/ServerFromClientSession.h>
#include <Limber/Server/UserRegistry.h>
#include <Slimber/LinkLocalPresenceManager.h>
#include <Slimber/VCardCollection.h>
namespace Swift {
Server::Server(
int clientConnectionPort,
int linkLocalConnectionPort,
LinkLocalServiceBrowser* linkLocalServiceBrowser,
VCardCollection* vCardCollection,
@@ -84,81 +84,81 @@ void Server::start() {
assert(!presenceManager);
presenceManager = new LinkLocalPresenceManager(linkLocalServiceBrowser);
presenceManager->onRosterChanged.connect(
boost::bind(&Server::handleRosterChanged, this, _1));
presenceManager->onPresenceChanged.connect(
boost::bind(&Server::handlePresenceChanged, this, _1));
serverFromClientConnectionServer->start();
serverFromNetworkConnectionServer->start();
}
void Server::stop() {
stop(boost::optional<ServerError>());
}
void Server::stop(boost::optional<ServerError> e) {
if (stopping) {
return;
}
stopping = true;
delete presenceManager;
presenceManager = nullptr;
if (serverFromClientSession) {
serverFromClientSession->finishSession();
}
serverFromClientSession.reset();
- foreach(std::shared_ptr<Session> session, linkLocalSessions) {
+ for (auto&& session : linkLocalSessions) {
session->finishSession();
}
linkLocalSessions.clear();
- foreach(std::shared_ptr<LinkLocalConnector> connector, connectors) {
+ for (auto&& connector : connectors) {
connector->cancel();
}
connectors.clear();
tracers.clear();
if (serverFromNetworkConnectionServer) {
serverFromNetworkConnectionServer->stop();
- foreach(boost::signals2::connection& connection, serverFromNetworkConnectionServerSignalConnections) {
+ for (auto&& connection : serverFromNetworkConnectionServerSignalConnections) {
connection.disconnect();
}
serverFromNetworkConnectionServerSignalConnections.clear();
serverFromNetworkConnectionServer.reset();
}
if (serverFromClientConnectionServer) {
serverFromClientConnectionServer->stop();
- foreach(boost::signals2::connection& connection, serverFromClientConnectionServerSignalConnections) {
+ for (auto&& connection : serverFromClientConnectionServerSignalConnections) {
connection.disconnect();
}
serverFromClientConnectionServerSignalConnections.clear();
serverFromClientConnectionServer.reset();
}
stopping = false;
onStopped(e);
}
void Server::handleNewClientConnection(std::shared_ptr<Connection> connection) {
if (serverFromClientSession) {
connection->disconnect();
}
serverFromClientSession = std::shared_ptr<ServerFromClientSession>(
new ServerFromClientSession(idGenerator.generateID(), connection,
&payloadParserFactories, &payloadSerializers, &xmlParserFactory, &userRegistry));
serverFromClientSession->setAllowSASLEXTERNAL();
serverFromClientSession->onSessionStarted.connect(
boost::bind(&Server::handleSessionStarted, this));
serverFromClientSession->onElementReceived.connect(
boost::bind(&Server::handleElementReceived, this, _1,
serverFromClientSession));
serverFromClientSession->onSessionFinished.connect(
boost::bind(&Server::handleSessionFinished, this,
serverFromClientSession));
//tracers.push_back(std::shared_ptr<SessionTracer>(
// new SessionTracer(serverFromClientSession)));
serverFromClientSession->startSession();
}
@@ -191,61 +191,61 @@ void Server::handleElementReceived(std::shared_ptr<ToplevelElement> element, std
stanza->setFrom(session->getRemoteJID());
if (!stanza->getTo().isValid()) {
stanza->setTo(session->getLocalJID());
}
if (std::shared_ptr<Presence> presence = std::dynamic_pointer_cast<Presence>(stanza)) {
if (presence->getType() == Presence::Available) {
if (!linkLocalServiceRegistered) {
linkLocalServiceRegistered = true;
linkLocalServiceBrowser->registerService(
session->getRemoteJID().toBare().toString(),
linkLocalConnectionPort, getLinkLocalServiceInfo(presence));
}
else {
linkLocalServiceBrowser->updateService(
getLinkLocalServiceInfo(presence));
}
lastPresence = presence;
}
else {
unregisterService();
}
}
else if (!stanza->getTo().isValid() || stanza->getTo() == session->getLocalJID() || stanza->getTo() == session->getRemoteJID().toBare()) {
if (std::shared_ptr<IQ> iq = std::dynamic_pointer_cast<IQ>(stanza)) {
if (iq->getPayload<RosterPayload>()) {
if (iq->getType() == IQ::Get) {
session->sendElement(IQ::createResult(iq->getFrom(), iq->getID(), presenceManager->getRoster()));
rosterRequested = true;
- foreach(const std::shared_ptr<Presence> presence, presenceManager->getAllPresence()) {
+ for (const auto& presence : presenceManager->getAllPresence()) {
session->sendElement(presence);
}
}
else {
session->sendElement(IQ::createError(iq->getFrom(), iq->getID(), ErrorPayload::Forbidden, ErrorPayload::Cancel));
}
}
if (std::shared_ptr<VCard> vcard = iq->getPayload<VCard>()) {
if (iq->getType() == IQ::Get) {
session->sendElement(IQ::createResult(iq->getFrom(), iq->getID(), vCardCollection->getOwnVCard()));
}
else {
vCardCollection->setOwnVCard(vcard);
session->sendElement(IQ::createResult(iq->getFrom(), iq->getID()));
if (lastPresence) {
linkLocalServiceBrowser->updateService(getLinkLocalServiceInfo(lastPresence));
}
}
}
else {
session->sendElement(IQ::createError(iq->getFrom(), iq->getID(), ErrorPayload::FeatureNotImplemented, ErrorPayload::Cancel));
}
}
}
else {
JID toJID = stanza->getTo();
std::shared_ptr<Session> outgoingSession =
getLinkLocalSessionForJID(toJID);
if (outgoingSession) {
outgoingSession->sendElement(stanza);
@@ -287,89 +287,89 @@ void Server::handleNewLinkLocalConnection(std::shared_ptr<Connection> connection
}
void Server::handleLinkLocalSessionFinished(std::shared_ptr<Session> session) {
//std::cout << "Link local session from " << session->getRemoteJID() << " ended" << std::endl;
linkLocalSessions.erase(
std::remove(linkLocalSessions.begin(), linkLocalSessions.end(), session),
linkLocalSessions.end());
}
void Server::handleLinkLocalElementReceived(std::shared_ptr<ToplevelElement> element, std::shared_ptr<Session> session) {
if (std::shared_ptr<Stanza> stanza = std::dynamic_pointer_cast<Stanza>(element)) {
JID fromJID = session->getRemoteJID();
if (!presenceManager->getServiceForJID(fromJID.toBare())) {
return; // TODO: Send error back
}
stanza->setFrom(fromJID);
serverFromClientSession->sendElement(stanza);
}
}
void Server::handleConnectFinished(std::shared_ptr<LinkLocalConnector> connector, bool error) {
if (error) {
SWIFT_LOG(warning) << "Error connecting" << std::endl;
// TODO: Send back queued stanzas
}
else {
std::shared_ptr<OutgoingLinkLocalSession> outgoingSession(
new OutgoingLinkLocalSession(
selfJID, connector->getService().getJID(), connector->getConnection(),
&payloadParserFactories, &payloadSerializers, &xmlParserFactory));
- foreach(const std::shared_ptr<ToplevelElement> element, connector->getQueuedElements()) {
+ for (const auto& element : connector->getQueuedElements()) {
outgoingSession->queueElement(element);
}
registerLinkLocalSession(outgoingSession);
}
connectors.erase(std::remove(connectors.begin(), connectors.end(), connector), connectors.end());
}
void Server::registerLinkLocalSession(std::shared_ptr<Session> session) {
session->onSessionFinished.connect(
boost::bind(&Server::handleLinkLocalSessionFinished, this, session));
session->onElementReceived.connect(
boost::bind(&Server::handleLinkLocalElementReceived, this, _1, session));
linkLocalSessions.push_back(session);
//tracers.push_back(std::make_shared<SessionTracer>(session));
session->startSession();
}
std::shared_ptr<Session> Server::getLinkLocalSessionForJID(const JID& jid) {
- foreach(const std::shared_ptr<Session> session, linkLocalSessions) {
+ for (const auto& session : linkLocalSessions) {
if (session->getRemoteJID() == jid) {
return session;
}
}
return std::shared_ptr<Session>();
}
std::shared_ptr<LinkLocalConnector> Server::getLinkLocalConnectorForJID(const JID& jid) {
- foreach(const std::shared_ptr<LinkLocalConnector> connector, connectors) {
+ for (const auto& connector : connectors) {
if (connector->getService().getJID() == jid) {
return connector;
}
}
return std::shared_ptr<LinkLocalConnector>();
}
void Server::handleServiceRegistered(const DNSSDServiceID& service) {
selfJID = JID(service.getName());
}
void Server::handleRosterChanged(std::shared_ptr<RosterPayload> roster) {
if (rosterRequested) {
assert(serverFromClientSession);
std::shared_ptr<IQ> iq = IQ::createRequest(
IQ::Set, serverFromClientSession->getRemoteJID(),
idGenerator.generateID(), roster);
iq->setFrom(serverFromClientSession->getRemoteJID().toBare());
serverFromClientSession->sendElement(iq);
}
}
void Server::handlePresenceChanged(std::shared_ptr<Presence> presence) {
if (rosterRequested) {
serverFromClientSession->sendElement(presence);
}
}
void Server::handleClientConnectionServerStopped(boost::optional<BoostConnectionServer::Error> e) {
if (e) {
diff --git a/Sluift/ElementConvertors/CommandConvertor.cpp b/Sluift/ElementConvertors/CommandConvertor.cpp
index 1e2f8e3..de7a439 100644
--- a/Sluift/ElementConvertors/CommandConvertor.cpp
+++ b/Sluift/ElementConvertors/CommandConvertor.cpp
@@ -1,46 +1,44 @@
/*
* Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/CommandConvertor.h>
#include <memory>
#include <boost/numeric/conversion/cast.hpp>
#include <lua.hpp>
-#include <Swiften/Base/foreach.h>
-
#include <Sluift/Lua/Check.h>
#include <Sluift/Lua/Value.h>
#include <Sluift/LuaElementConvertors.h>
using namespace Swift;
static Command::Action convertActionFromString(const std::string& action) {
if (action == "cancel") { return Command::Cancel; }
else if (action == "execute") { return Command::Execute; }
else if (action == "complete") { return Command::Complete; }
else if (action == "prev") { return Command::Prev; }
else if (action == "next") { return Command::Next; }
return Command::NoAction;
}
static std::string convertActionToString(Command::Action action) {
switch (action) {
case Command::Cancel: return "cancel";
case Command::Execute: return "execute";
case Command::Complete: return "complete";
case Command::Prev: return "prev";
case Command::Next: return "next";
case Command::NoAction: assert(false); return "";
}
assert(false);
return "";
}
CommandConvertor::CommandConvertor(LuaElementConvertors* convertors) :
GenericLuaElementConvertor<Command>("command"),
@@ -127,71 +125,71 @@ std::shared_ptr<Command> CommandConvertor::doConvertFromLua(lua_State* L) {
lua_pop(L, 1);
lua_getfield(L, -1, "form");
if (!lua_isnil(L, -1)) {
if (std::shared_ptr<Form> form = std::dynamic_pointer_cast<Form>(convertors->convertFromLuaUntyped(L, -1, "form"))) {
result->setForm(form);
}
}
lua_pop(L, 1);
return result;
}
void CommandConvertor::doConvertToLua(lua_State* L, std::shared_ptr<Command> payload) {
Lua::Table result;
if (!payload->getNode().empty()) {
result["node"] = Lua::valueRef(payload->getNode());
}
if (!payload->getSessionID().empty()) {
result["session_id"] = Lua::valueRef(payload->getSessionID());
}
switch (payload->getStatus()) {
case Command::Executing: result["status"] = Lua::valueRef("executing"); break;
case Command::Completed: result["status"] = Lua::valueRef("completed"); break;
case Command::Canceled: result["status"] = Lua::valueRef("canceled"); break;
case Command::NoStatus: break;
}
if (!payload->getNotes().empty()) {
std::vector<Lua::Value> notes;
- foreach (const Command::Note& note, payload->getNotes()) {
+ for (const auto& note : payload->getNotes()) {
Lua::Table noteTable;
if (!note.note.empty()) {
noteTable["note"] = Lua::valueRef(note.note);
}
switch (note.type) {
case Command::Note::Info: noteTable["type"] = Lua::valueRef("info"); break;
case Command::Note::Warn: noteTable["type"] = Lua::valueRef("warn"); break;
case Command::Note::Error: noteTable["type"] = Lua::valueRef("error"); break;
}
notes.push_back(noteTable);
}
result["notes"] = Lua::valueRef(notes);
}
if (payload->getAction() != Command::NoAction) {
result["action"] = Lua::valueRef(convertActionToString(payload->getAction()));
}
if (payload->getExecuteAction() != Command::NoAction) {
result["execute_action"] = Lua::valueRef(convertActionToString(payload->getAction()));
}
if (!payload->getAvailableActions().empty()) {
std::vector<Lua::Value> availableActions;
- foreach (const Command::Action& action, payload->getAvailableActions()) {
+ for (const auto& action : payload->getAvailableActions()) {
if (action != Command::NoAction) {
availableActions.push_back(convertActionToString(action));
}
}
result["available_actions"] = Lua::valueRef(availableActions);
}
Lua::pushValue(L, result);
if (payload->getForm()) {
bool result = convertors->convertToLuaUntyped(L, payload->getForm());
assert(result);
lua_setfield(L, -2, "form");
}
}
diff --git a/Sluift/ElementConvertors/DOMElementConvertor.cpp b/Sluift/ElementConvertors/DOMElementConvertor.cpp
index c03eb8c..b957686 100644
--- a/Sluift/ElementConvertors/DOMElementConvertor.cpp
+++ b/Sluift/ElementConvertors/DOMElementConvertor.cpp
@@ -1,81 +1,80 @@
/*
* Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/DOMElementConvertor.h>
#include <memory>
#include <lua.hpp>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Elements/RawXMLPayload.h>
#include <Swiften/Parser/Attribute.h>
#include <Swiften/Parser/AttributeMap.h>
#include <Swiften/Parser/XMLParser.h>
#include <Swiften/Parser/XMLParserClient.h>
#include <Swiften/Serializer/PayloadSerializer.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
#include <Sluift/Lua/Check.h>
#include <Sluift/Lua/Debug.h>
#include <Sluift/Lua/LuaUtils.h>
using namespace Swift;
namespace {
class ParserClient : public XMLParserClient {
public:
ParserClient(lua_State* L) : L(L), currentIndex(1) {
}
virtual void handleStartElement(
const std::string& element, const std::string& ns,
const AttributeMap& attributes) SWIFTEN_OVERRIDE {
lua_checkstack(L, 6);
lua_pushnumber(L, currentIndex);
lua_newtable(L);
lua_pushstring(L, element.c_str());
lua_setfield(L, -2, "tag");
if (!ns.empty()) {
lua_pushstring(L, ns.c_str());
lua_setfield(L, -2, "ns");
}
if (!attributes.getEntries().empty()) {
lua_newtable(L);
int i = 1;
- foreach(const AttributeMap::Entry& entry, attributes.getEntries()) {
+ for (const auto& entry : attributes.getEntries()) {
lua_pushnumber(L, i);
lua_newtable(L);
lua_pushstring(L, entry.getAttribute().getName().c_str());
lua_setfield(L, -2, "name");
if (!entry.getAttribute().getNamespace().empty()) {
lua_pushstring(L, entry.getAttribute().getNamespace().c_str());
lua_setfield(L, -2, "ns");
}
lua_pushstring(L, entry.getValue().c_str());
lua_setfield(L, -2, "value");
lua_settable(L, -3);
++i;
}
lua_setfield(L, -2, "attributes");
}
indexStack.push_back(currentIndex);
currentIndex = 1;
lua_newtable(L);
}
virtual void handleEndElement(
const std::string&, const std::string&) SWIFTEN_OVERRIDE {
lua_setfield(L, -2, "children");
lua_settable(L, -3);
currentIndex = indexStack.back();
indexStack.pop_back();
currentIndex++;
}
diff --git a/Sluift/ElementConvertors/FormConvertor.cpp b/Sluift/ElementConvertors/FormConvertor.cpp
index 85f40a1..90fd9fe 100644
--- a/Sluift/ElementConvertors/FormConvertor.cpp
+++ b/Sluift/ElementConvertors/FormConvertor.cpp
@@ -1,48 +1,46 @@
/*
* Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/FormConvertor.h>
#include <memory>
#include <sstream>
#include <boost/assign/list_of.hpp>
#include <boost/numeric/conversion/cast.hpp>
#include <lua.hpp>
-#include <Swiften/Base/foreach.h>
-
#include <Sluift/Lua/Check.h>
#include <Sluift/Lua/Value.h>
using namespace Swift;
namespace {
int formIndex(lua_State* L) {
lua_getfield(L, 1, "fields");
if (lua_type(L, -1) != LUA_TTABLE) {
return 0;
}
int index = Lua::absoluteOffset(L, -1);
lua_pushnil(L);
for (lua_pushnil(L); lua_next(L, index) != 0; ) {
lua_getfield(L, -1, "name");
if (lua_equal(L, -1, 2)) {
lua_pop(L, 1);
return 1;
}
lua_pop(L, 2);
}
return 0;
}
int formNewIndex(lua_State* L) {
lua_getfield(L, 1, "fields");
bool foundField = false;
if (lua_type(L, -1) == LUA_TTABLE) {
for (lua_pushnil(L); lua_next(L, -2) != 0; ) {
lua_getfield(L, -1, "name");
@@ -78,74 +76,74 @@ namespace {
case FormField::TextMultiType: type = "text-multi"; break;
case FormField::TextPrivateType: type = "text-private"; break;
case FormField::TextSingleType: type = "text-single"; break;
case FormField::JIDSingleType: type = "jid-single"; break;
case FormField::JIDMultiType: type = "jid-multi"; break;
case FormField::ListMultiType: type = "list-multi"; break;
}
if (!type.empty()) {
luaField["type"] = Lua::valueRef(type);
}
if (!field->getLabel().empty()) {
luaField["label"] = Lua::valueRef(field->getLabel());
}
if (field->getRequired()) {
luaField["required"] = Lua::boolRef(field->getRequired());
}
if (!field->getDescription().empty()) {
luaField["description"] = Lua::valueRef(field->getDescription());
}
if (field->getType() == FormField::BooleanType) {
luaField["value"] = Lua::boolRef(field->getBoolValue());
}
else if (field->getValues().size() > 1) {
luaField["value"] = Lua::valueRef(Lua::Array(field->getValues().begin(), field->getValues().end()));
}
else if (field->getValues().size() == 1) {
luaField["value"] = Lua::valueRef(field->getValues()[0]);
}
if (!field->getOptions().empty()) {
Lua::Array options;
- foreach(const FormField::Option& option, field->getOptions()) {
+ for (const auto& option : field->getOptions()) {
Lua::Table luaOption = boost::assign::map_list_of
("label", Lua::valueRef(option.label))
("value", Lua::valueRef(option.value));
options.push_back(luaOption);
}
luaField["options"] = valueRef(options);
}
return luaField;
}
Lua::Array convertFieldListToLua(const std::vector< std::shared_ptr<FormField> >& fieldList) {
Lua::Array fields;
- foreach(std::shared_ptr<FormField> field, fieldList) {
+ for (auto&& field : fieldList) {
fields.push_back(convertFieldToLua(field));
}
return fields;
}
std::shared_ptr<FormField> convertFieldFromLua(lua_State* L) {
std::shared_ptr<FormField> result = std::make_shared<FormField>();
FormField::Type fieldType = FormField::UnknownType;
boost::optional<std::string> type = Lua::getStringField(L, -1, "type");
if (type) {
if (*type == "boolean") {
fieldType = FormField::BooleanType;
}
if (*type == "fixed") {
fieldType = FormField::FixedType;
}
if (*type == "hidden") {
fieldType = FormField::HiddenType;
}
if (*type == "list-single") {
fieldType = FormField::ListSingleType;
}
if (*type == "text-multi") {
fieldType = FormField::TextMultiType;
}
if (*type == "text-private") {
fieldType = FormField::TextPrivateType;
}
if (*type == "text-single") {
@@ -218,138 +216,138 @@ namespace {
result.push_back(convertFieldFromLua(L));
lua_pop(L, 1);
}
return result;
}
std::shared_ptr<Form> convertFormFromLua(lua_State* L) {
std::shared_ptr<Form> result = std::make_shared<Form>();
if (boost::optional<std::string> title = Lua::getStringField(L, -1, "title")) {
result->setTitle(*title);
}
if (boost::optional<std::string> instructions = Lua::getStringField(L, -1, "instructions")) {
result->setInstructions(*instructions);
}
if (boost::optional<std::string> type = Lua::getStringField(L, -1, "type")) {
Form::Type formType = Form::FormType;
if (*type == "submit") {
formType = Form::SubmitType;
}
else if (*type == "cancel") {
formType = Form::CancelType;
}
else if (*type == "result") {
formType = Form::ResultType;
}
result->setType(formType);
}
lua_getfield(L, -1, "fields");
if (lua_istable(L, -1)) {
- foreach (std::shared_ptr<FormField> formField, convertFieldListFromLua(L)) {
+ for (auto&& formField : convertFieldListFromLua(L)) {
result->addField(formField);
}
}
lua_pop(L, 1);
lua_getfield(L, -1, "reported_fields");
if (lua_istable(L, -1)) {
- foreach (std::shared_ptr<FormField> formField, convertFieldListFromLua(L)) {
+ for (auto&& formField : convertFieldListFromLua(L)) {
result->addReportedField(formField);
}
}
lua_pop(L, 1);
lua_getfield(L, -1, "items");
if (lua_istable(L, -1)) {
for (lua_pushnil(L); lua_next(L, -2);) {
result->addItem(convertFieldListFromLua(L));
lua_pop(L, 1);
}
}
lua_pop(L, 1);
return result;
}
void convertFormToLua(lua_State* L, std::shared_ptr<Form> payload) {
std::string type;
switch (payload->getType()) {
case Form::FormType: type = "form"; break;
case Form::SubmitType: type = "submit"; break;
case Form::CancelType: type = "cancel"; break;
case Form::ResultType: type = "result"; break;
}
Lua::Table result = boost::assign::map_list_of("type", Lua::valueRef(type));
if (!payload->getTitle().empty()) {
result["title"] = Lua::valueRef(payload->getTitle());
}
if (!payload->getInstructions().empty()) {
result["instructions"] = Lua::valueRef(payload->getInstructions());
}
result["fields"] = valueRef(convertFieldListToLua(payload->getFields()));
if (!payload->getReportedFields().empty()) {
result["reported_fields"] = valueRef(convertFieldListToLua(payload->getReportedFields()));
}
if (!payload->getItems().empty()) {
Lua::Array luaItems;
- foreach(const Form::FormItem& item, payload->getItems()) {
+ for (const auto& item : payload->getItems()) {
if (!item.empty()) {
luaItems.push_back(convertFieldListToLua(item));
}
}
result["items"] = valueRef(luaItems);
}
Lua::pushValue(L, result);
lua_newtable(L);
lua_pushcfunction(L, formIndex);
lua_setfield(L, -2, "__index");
lua_pushcfunction(L, formNewIndex);
lua_setfield(L, -2, "__newindex");
lua_setmetatable(L, -2);
}
int createSubmission(lua_State* L) {
std::shared_ptr<Form> form = convertFormFromLua(L);
// Remove all redundant elements
form->setInstructions("");
form->setTitle("");
form->clearItems();
form->clearReportedFields();
std::vector< std::shared_ptr<FormField> > fields(form->getFields());
form->clearFields();
- foreach (std::shared_ptr<FormField> field, fields) {
+ for (auto&& field : fields) {
if (field->getType() == FormField::FixedType) {
continue;
}
field->clearOptions();
field->setLabel("");
field->setType(FormField::UnknownType);
field->setDescription("");
form->addField(field);
}
form->setType(Form::SubmitType);
// Convert back
convertFormToLua(L, form);
Lua::registerTableToString(L, -1);
return 1;
}
}
FormConvertor::FormConvertor() : GenericLuaElementConvertor<Form>("form") {
}
FormConvertor::~FormConvertor() {
}
std::shared_ptr<Form> FormConvertor::doConvertFromLua(lua_State* L) {
return convertFormFromLua(L);
}
void FormConvertor::doConvertToLua(lua_State* L, std::shared_ptr<Form> payload) {
diff --git a/Sluift/ElementConvertors/ForwardedConvertor.cpp b/Sluift/ElementConvertors/ForwardedConvertor.cpp
index 8474252..b353eea 100644
--- a/Sluift/ElementConvertors/ForwardedConvertor.cpp
+++ b/Sluift/ElementConvertors/ForwardedConvertor.cpp
@@ -1,45 +1,44 @@
/*
* Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/ForwardedConvertor.h>
#include <memory>
#include <boost/numeric/conversion/cast.hpp>
#include <lua.hpp>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Elements/Delay.h>
#include <Swiften/Elements/IQ.h>
#include <Swiften/Elements/Message.h>
#include <Swiften/Elements/Presence.h>
#include <Sluift/LuaElementConvertors.h>
using namespace Swift;
ForwardedConvertor::ForwardedConvertor(LuaElementConvertors* convertors) :
GenericLuaElementConvertor<Forwarded>("forwarded"),
convertors(convertors) {
}
ForwardedConvertor::~ForwardedConvertor() {
}
std::shared_ptr<Forwarded> ForwardedConvertor::doConvertFromLua(lua_State* L) {
std::shared_ptr<Forwarded> result = std::make_shared<Forwarded>();
lua_getfield(L, -1, "delay");
if (!lua_isnil(L, -1)) {
std::shared_ptr<Delay> delay = std::dynamic_pointer_cast<Delay>(convertors->convertFromLuaUntyped(L, -1, "delay"));
if (!!delay) {
result->setDelay(delay);
}
}
lua_pop(L, 1);
lua_getfield(L, -1, "stanza");
if (!lua_isnil(L, -1)) {
std::shared_ptr<Stanza> stanza = std::dynamic_pointer_cast<Stanza>(convertors->convertFromLua(L, -1));
diff --git a/Sluift/ElementConvertors/PubSubAffiliationsConvertor.cpp b/Sluift/ElementConvertors/PubSubAffiliationsConvertor.cpp
index 8eae795..c6ba09e 100644
--- a/Sluift/ElementConvertors/PubSubAffiliationsConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubAffiliationsConvertor.cpp
@@ -1,80 +1,78 @@
/*
* Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/PubSubAffiliationsConvertor.h>
#include <memory>
#include <boost/numeric/conversion/cast.hpp>
#include <lua.hpp>
-#include <Swiften/Base/foreach.h>
-
#include <Sluift/LuaElementConvertors.h>
using namespace Swift;
PubSubAffiliationsConvertor::PubSubAffiliationsConvertor(LuaElementConvertors* convertors) :
GenericLuaElementConvertor<PubSubAffiliations>("pubsub_affiliations"),
convertors(convertors) {
}
PubSubAffiliationsConvertor::~PubSubAffiliationsConvertor() {
}
std::shared_ptr<PubSubAffiliations> PubSubAffiliationsConvertor::doConvertFromLua(lua_State* L) {
std::shared_ptr<PubSubAffiliations> result = std::make_shared<PubSubAffiliations>();
lua_getfield(L, -1, "node");
if (lua_isstring(L, -1)) {
result->setNode(std::string(lua_tostring(L, -1)));
}
lua_pop(L, 1);
if (lua_type(L, -1) == LUA_TTABLE) {
std::vector< std::shared_ptr<PubSubAffiliation> > items;
for(size_t i = 0; i < lua_objlen(L, -1); ++i) {
lua_pushnumber(L, i + 1);
lua_gettable(L, -2);
if (!lua_isnil(L, -1)) {
if (std::shared_ptr<PubSubAffiliation> payload = std::dynamic_pointer_cast<PubSubAffiliation>(convertors->convertFromLuaUntyped(L, -1, "pubsub_affiliation"))) {
items.push_back(payload);
}
}
lua_pop(L, 1);
}
result->setAffiliations(items);
}
return result;
}
void PubSubAffiliationsConvertor::doConvertToLua(lua_State* L, std::shared_ptr<PubSubAffiliations> payload) {
lua_createtable(L, 0, 0);
if (payload->getNode()) {
lua_pushstring(L, (*payload->getNode()).c_str());
lua_setfield(L, -2, "node");
}
if (!payload->getAffiliations().empty()) {
{
int i = 0;
- foreach(std::shared_ptr<PubSubAffiliation> item, payload->getAffiliations()) {
+ for (auto&& item : payload->getAffiliations()) {
if (convertors->convertToLuaUntyped(L, item) > 0) {
lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
++i;
}
}
}
}
}
boost::optional<LuaElementConvertor::Documentation> PubSubAffiliationsConvertor::getDocumentation() const {
return Documentation(
"PubSubAffiliations",
"This table has the following fields:\n\n"
"- `node`: string (Optional)\n"
"- `affiliations`: array<@{PubSubAffiliation}>\n"
);
}
diff --git a/Sluift/ElementConvertors/PubSubEventItemConvertor.cpp b/Sluift/ElementConvertors/PubSubEventItemConvertor.cpp
index e8ba5b5..ac86024 100644
--- a/Sluift/ElementConvertors/PubSubEventItemConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubEventItemConvertor.cpp
@@ -1,46 +1,44 @@
/*
* Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/PubSubEventItemConvertor.h>
#include <memory>
#include <boost/numeric/conversion/cast.hpp>
#include <lua.hpp>
-#include <Swiften/Base/foreach.h>
-
#include <Sluift/LuaElementConvertors.h>
using namespace Swift;
PubSubEventItemConvertor::PubSubEventItemConvertor(LuaElementConvertors* convertors) :
GenericLuaElementConvertor<PubSubEventItem>("pubsub_event_item"),
convertors(convertors) {
}
PubSubEventItemConvertor::~PubSubEventItemConvertor() {
}
std::shared_ptr<PubSubEventItem> PubSubEventItemConvertor::doConvertFromLua(lua_State* L) {
std::shared_ptr<PubSubEventItem> result = std::make_shared<PubSubEventItem>();
lua_getfield(L, -1, "node");
if (lua_isstring(L, -1)) {
result->setNode(std::string(lua_tostring(L, -1)));
}
lua_pop(L, 1);
lua_getfield(L, -1, "publisher");
if (lua_isstring(L, -1)) {
result->setPublisher(std::string(lua_tostring(L, -1)));
}
lua_pop(L, 1);
lua_getfield(L, -1, "data");
if (lua_type(L, -1) == LUA_TTABLE) {
std::vector< std::shared_ptr<Payload> > items;
for(size_t i = 0; i < lua_objlen(L, -1); ++i) {
lua_pushnumber(L, i + 1);
lua_gettable(L, -2);
@@ -50,55 +48,55 @@ std::shared_ptr<PubSubEventItem> PubSubEventItemConvertor::doConvertFromLua(lua_
}
}
lua_pop(L, 1);
}
result->setData(items);
}
lua_pop(L, 1);
lua_getfield(L, -1, "id");
if (lua_isstring(L, -1)) {
result->setID(std::string(lua_tostring(L, -1)));
}
lua_pop(L, 1);
return result;
}
void PubSubEventItemConvertor::doConvertToLua(lua_State* L, std::shared_ptr<PubSubEventItem> payload) {
lua_createtable(L, 0, 0);
if (payload->getNode()) {
lua_pushstring(L, (*payload->getNode()).c_str());
lua_setfield(L, -2, "node");
}
if (payload->getPublisher()) {
lua_pushstring(L, (*payload->getPublisher()).c_str());
lua_setfield(L, -2, "publisher");
}
if (!payload->getData().empty()) {
lua_createtable(L, boost::numeric_cast<int>(payload->getData().size()), 0);
{
int i = 0;
- foreach(std::shared_ptr<Payload> item, payload->getData()) {
+ for (auto&& item : payload->getData()) {
if (convertors->convertToLua(L, item) > 0) {
lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
++i;
}
}
}
lua_setfield(L, -2, "data");
}
if (payload->getID()) {
lua_pushstring(L, (*payload->getID()).c_str());
lua_setfield(L, -2, "id");
}
}
boost::optional<LuaElementConvertor::Documentation> PubSubEventItemConvertor::getDocumentation() const {
return Documentation(
"PubSubEventItem",
"This table has the following fields:\n\n"
"- `node`: string (Optional)\n"
"- `publisher`: string (Optional)\n"
"- `data`: array<element (table)>\n"
"- `id`: string (Optional)\n"
);
}
diff --git a/Sluift/ElementConvertors/PubSubEventItemsConvertor.cpp b/Sluift/ElementConvertors/PubSubEventItemsConvertor.cpp
index c89c4a6..7a3cde1 100644
--- a/Sluift/ElementConvertors/PubSubEventItemsConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubEventItemsConvertor.cpp
@@ -1,46 +1,44 @@
/*
* Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/PubSubEventItemsConvertor.h>
#include <memory>
#include <boost/numeric/conversion/cast.hpp>
#include <lua.hpp>
-#include <Swiften/Base/foreach.h>
-
#include <Sluift/LuaElementConvertors.h>
using namespace Swift;
PubSubEventItemsConvertor::PubSubEventItemsConvertor(LuaElementConvertors* convertors) :
GenericLuaElementConvertor<PubSubEventItems>("pubsub_event_items"),
convertors(convertors) {
}
PubSubEventItemsConvertor::~PubSubEventItemsConvertor() {
}
std::shared_ptr<PubSubEventItems> PubSubEventItemsConvertor::doConvertFromLua(lua_State* L) {
std::shared_ptr<PubSubEventItems> result = std::make_shared<PubSubEventItems>();
lua_getfield(L, -1, "node");
if (lua_isstring(L, -1)) {
result->setNode(std::string(lua_tostring(L, -1)));
}
lua_pop(L, 1);
lua_getfield(L, -1, "items");
if (lua_type(L, -1) == LUA_TTABLE) {
std::vector< std::shared_ptr<PubSubEventItem> > items;
for(size_t i = 0; i < lua_objlen(L, -1); ++i) {
lua_pushnumber(L, i + 1);
lua_gettable(L, -2);
if (!lua_isnil(L, -1)) {
if (std::shared_ptr<PubSubEventItem> payload = std::dynamic_pointer_cast<PubSubEventItem>(convertors->convertFromLuaUntyped(L, -1, "pubsub_event_item"))) {
items.push_back(payload);
}
}
@@ -51,63 +49,63 @@ std::shared_ptr<PubSubEventItems> PubSubEventItemsConvertor::doConvertFromLua(lu
}
lua_pop(L, 1);
lua_getfield(L, -1, "retracts");
if (lua_type(L, -1) == LUA_TTABLE) {
std::vector< std::shared_ptr<PubSubEventRetract> > items;
for(size_t i = 0; i < lua_objlen(L, -1); ++i) {
lua_pushnumber(L, i + 1);
lua_gettable(L, -2);
if (!lua_isnil(L, -1)) {
if (std::shared_ptr<PubSubEventRetract> payload = std::dynamic_pointer_cast<PubSubEventRetract>(convertors->convertFromLuaUntyped(L, -1, "pubsub_event_retract"))) {
items.push_back(payload);
}
}
lua_pop(L, 1);
}
result->setRetracts(items);
}
lua_pop(L, 1);
return result;
}
void PubSubEventItemsConvertor::doConvertToLua(lua_State* L, std::shared_ptr<PubSubEventItems> payload) {
lua_createtable(L, 0, 0);
lua_pushstring(L, payload->getNode().c_str());
lua_setfield(L, -2, "node");
if (!payload->getItems().empty()) {
lua_createtable(L, boost::numeric_cast<int>(payload->getItems().size()), 0);
{
int i = 0;
- foreach(std::shared_ptr<PubSubEventItem> item, payload->getItems()) {
+ for (auto&& item : payload->getItems()) {
if (convertors->convertToLuaUntyped(L, item) > 0) {
lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
++i;
}
}
}
lua_setfield(L, -2, "items");
}
if (!payload->getRetracts().empty()) {
lua_createtable(L, boost::numeric_cast<int>(payload->getRetracts().size()), 0);
{
int i = 0;
- foreach(std::shared_ptr<PubSubEventRetract> item, payload->getRetracts()) {
+ for (auto&& item : payload->getRetracts()) {
if (convertors->convertToLuaUntyped(L, item) > 0) {
lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
++i;
}
}
}
lua_setfield(L, -2, "retracts");
}
}
boost::optional<LuaElementConvertor::Documentation> PubSubEventItemsConvertor::getDocumentation() const {
return Documentation(
"PubSubEventItems",
"This table has the following fields:\n\n"
"- `node`: string\n"
"- `items`: array<@{PubSubEventItem}>\n"
"- `retracts`: array<@{PubSubEventRetract}>\n"
);
}
diff --git a/Sluift/ElementConvertors/PubSubItemConvertor.cpp b/Sluift/ElementConvertors/PubSubItemConvertor.cpp
index 99802bf..27fd4a3 100644
--- a/Sluift/ElementConvertors/PubSubItemConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubItemConvertor.cpp
@@ -1,82 +1,80 @@
/*
* Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/PubSubItemConvertor.h>
#include <memory>
#include <boost/numeric/conversion/cast.hpp>
#include <lua.hpp>
-#include <Swiften/Base/foreach.h>
-
#include <Sluift/LuaElementConvertors.h>
using namespace Swift;
PubSubItemConvertor::PubSubItemConvertor(LuaElementConvertors* convertors) :
GenericLuaElementConvertor<PubSubItem>("pubsub_item"),
convertors(convertors) {
}
PubSubItemConvertor::~PubSubItemConvertor() {
}
std::shared_ptr<PubSubItem> PubSubItemConvertor::doConvertFromLua(lua_State* L) {
std::shared_ptr<PubSubItem> result = std::make_shared<PubSubItem>();
lua_getfield(L, -1, "data");
if (lua_type(L, -1) == LUA_TTABLE) {
std::vector< std::shared_ptr<Payload> > items;
for(size_t i = 0; i < lua_objlen(L, -1); ++i) {
lua_pushnumber(L, i + 1);
lua_gettable(L, -2);
if (!lua_isnil(L, -1)) {
if (std::shared_ptr<Payload> payload = std::dynamic_pointer_cast<Payload>(convertors->convertFromLua(L, -1))) {
items.push_back(payload);
}
}
lua_pop(L, 1);
}
result->setData(items);
}
lua_pop(L, 1);
lua_getfield(L, -1, "id");
if (lua_isstring(L, -1)) {
result->setID(std::string(lua_tostring(L, -1)));
}
lua_pop(L, 1);
return result;
}
void PubSubItemConvertor::doConvertToLua(lua_State* L, std::shared_ptr<PubSubItem> payload) {
lua_createtable(L, 0, 0);
if (!payload->getData().empty()) {
lua_createtable(L, boost::numeric_cast<int>(payload->getData().size()), 0);
{
int i = 0;
- foreach(std::shared_ptr<Payload> item, payload->getData()) {
+ for (auto&& item : payload->getData()) {
if (convertors->convertToLua(L, item) > 0) {
lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
++i;
}
}
}
lua_setfield(L, -2, "data");
}
lua_pushstring(L, payload->getID().c_str());
lua_setfield(L, -2, "id");
}
boost::optional<LuaElementConvertor::Documentation> PubSubItemConvertor::getDocumentation() const {
return Documentation(
"PubSubItem",
"This table has the following fields:\n\n"
"- `data`: array<element (table)>\n"
"- `id`: string\n"
);
}
diff --git a/Sluift/ElementConvertors/PubSubItemsConvertor.cpp b/Sluift/ElementConvertors/PubSubItemsConvertor.cpp
index 8e1f08d..5fa1bd3 100644
--- a/Sluift/ElementConvertors/PubSubItemsConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubItemsConvertor.cpp
@@ -1,98 +1,96 @@
/*
* Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/PubSubItemsConvertor.h>
#include <memory>
#include <boost/numeric/conversion/cast.hpp>
#include <lua.hpp>
-#include <Swiften/Base/foreach.h>
-
#include <Sluift/LuaElementConvertors.h>
using namespace Swift;
PubSubItemsConvertor::PubSubItemsConvertor(LuaElementConvertors* convertors) :
GenericLuaElementConvertor<PubSubItems>("pubsub_items"),
convertors(convertors) {
}
PubSubItemsConvertor::~PubSubItemsConvertor() {
}
std::shared_ptr<PubSubItems> PubSubItemsConvertor::doConvertFromLua(lua_State* L) {
std::shared_ptr<PubSubItems> result = std::make_shared<PubSubItems>();
lua_getfield(L, -1, "node");
if (lua_isstring(L, -1)) {
result->setNode(std::string(lua_tostring(L, -1)));
}
lua_pop(L, 1);
if (lua_type(L, -1) == LUA_TTABLE) {
std::vector< std::shared_ptr<PubSubItem> > items;
for(size_t i = 0; i < lua_objlen(L, -1); ++i) {
lua_pushnumber(L, i + 1);
lua_gettable(L, -2);
if (!lua_isnil(L, -1)) {
if (std::shared_ptr<PubSubItem> payload = std::dynamic_pointer_cast<PubSubItem>(convertors->convertFromLuaUntyped(L, -1, "pubsub_item"))) {
items.push_back(payload);
}
}
lua_pop(L, 1);
}
result->setItems(items);
}
lua_getfield(L, -1, "maximum_items");
if (lua_isnumber(L, -1)) {
result->setMaximumItems(boost::numeric_cast<unsigned int>(lua_tonumber(L, -1)));
}
lua_pop(L, 1);
lua_getfield(L, -1, "subscription_id");
if (lua_isstring(L, -1)) {
result->setSubscriptionID(std::string(lua_tostring(L, -1)));
}
lua_pop(L, 1);
return result;
}
void PubSubItemsConvertor::doConvertToLua(lua_State* L, std::shared_ptr<PubSubItems> payload) {
lua_createtable(L, 0, 0);
lua_pushstring(L, payload->getNode().c_str());
lua_setfield(L, -2, "node");
if (!payload->getItems().empty()) {
{
int i = 0;
- foreach(std::shared_ptr<PubSubItem> item, payload->getItems()) {
+ for (auto&& item : payload->getItems()) {
if (convertors->convertToLuaUntyped(L, item) > 0) {
lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
++i;
}
}
}
}
if (payload->getMaximumItems()) {
lua_pushnumber(L, (*payload->getMaximumItems()));
lua_setfield(L, -2, "maximum_items");
}
if (payload->getSubscriptionID()) {
lua_pushstring(L, (*payload->getSubscriptionID()).c_str());
lua_setfield(L, -2, "subscription_id");
}
}
boost::optional<LuaElementConvertor::Documentation> PubSubItemsConvertor::getDocumentation() const {
return Documentation(
"PubSubItems",
"This table has the following fields:\n\n"
"- `node`: string\n"
"- `items`: array<@{PubSubItem}>\n"
"- `maximum_items`: number (Optional)\n"
"- `subscription_id`: string (Optional)\n"
);
}
diff --git a/Sluift/ElementConvertors/PubSubOwnerAffiliationsConvertor.cpp b/Sluift/ElementConvertors/PubSubOwnerAffiliationsConvertor.cpp
index b66443f..ee8a8cb 100644
--- a/Sluift/ElementConvertors/PubSubOwnerAffiliationsConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubOwnerAffiliationsConvertor.cpp
@@ -1,78 +1,76 @@
/*
* Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/PubSubOwnerAffiliationsConvertor.h>
#include <memory>
#include <boost/numeric/conversion/cast.hpp>
#include <lua.hpp>
-#include <Swiften/Base/foreach.h>
-
#include <Sluift/LuaElementConvertors.h>
using namespace Swift;
PubSubOwnerAffiliationsConvertor::PubSubOwnerAffiliationsConvertor(LuaElementConvertors* convertors) :
GenericLuaElementConvertor<PubSubOwnerAffiliations>("pubsub_owner_affiliations"),
convertors(convertors) {
}
PubSubOwnerAffiliationsConvertor::~PubSubOwnerAffiliationsConvertor() {
}
std::shared_ptr<PubSubOwnerAffiliations> PubSubOwnerAffiliationsConvertor::doConvertFromLua(lua_State* L) {
std::shared_ptr<PubSubOwnerAffiliations> result = std::make_shared<PubSubOwnerAffiliations>();
lua_getfield(L, -1, "node");
if (lua_isstring(L, -1)) {
result->setNode(std::string(lua_tostring(L, -1)));
}
lua_pop(L, 1);
if (lua_type(L, -1) == LUA_TTABLE) {
std::vector< std::shared_ptr<PubSubOwnerAffiliation> > items;
for(size_t i = 0; i < lua_objlen(L, -1); ++i) {
lua_pushnumber(L, i + 1);
lua_gettable(L, -2);
if (!lua_isnil(L, -1)) {
if (std::shared_ptr<PubSubOwnerAffiliation> payload = std::dynamic_pointer_cast<PubSubOwnerAffiliation>(convertors->convertFromLuaUntyped(L, -1, "pubsub_owner_affiliation"))) {
items.push_back(payload);
}
}
lua_pop(L, 1);
}
result->setAffiliations(items);
}
return result;
}
void PubSubOwnerAffiliationsConvertor::doConvertToLua(lua_State* L, std::shared_ptr<PubSubOwnerAffiliations> payload) {
lua_createtable(L, 0, 0);
lua_pushstring(L, payload->getNode().c_str());
lua_setfield(L, -2, "node");
if (!payload->getAffiliations().empty()) {
{
int i = 0;
- foreach(std::shared_ptr<PubSubOwnerAffiliation> item, payload->getAffiliations()) {
+ for (auto&& item : payload->getAffiliations()) {
if (convertors->convertToLuaUntyped(L, item) > 0) {
lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
++i;
}
}
}
}
}
boost::optional<LuaElementConvertor::Documentation> PubSubOwnerAffiliationsConvertor::getDocumentation() const {
return Documentation(
"PubSubOwnerAffiliations",
"This table has the following fields:\n\n"
"- `node`: string\n"
"- `affiliations`: array<@{PubSubOwnerAffiliation}>\n"
);
}
diff --git a/Sluift/ElementConvertors/PubSubOwnerSubscriptionsConvertor.cpp b/Sluift/ElementConvertors/PubSubOwnerSubscriptionsConvertor.cpp
index 50cfb9b..88085b5 100644
--- a/Sluift/ElementConvertors/PubSubOwnerSubscriptionsConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubOwnerSubscriptionsConvertor.cpp
@@ -1,78 +1,76 @@
/*
* Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/PubSubOwnerSubscriptionsConvertor.h>
#include <memory>
#include <boost/numeric/conversion/cast.hpp>
#include <lua.hpp>
-#include <Swiften/Base/foreach.h>
-
#include <Sluift/LuaElementConvertors.h>
using namespace Swift;
PubSubOwnerSubscriptionsConvertor::PubSubOwnerSubscriptionsConvertor(LuaElementConvertors* convertors) :
GenericLuaElementConvertor<PubSubOwnerSubscriptions>("pubsub_owner_subscriptions"),
convertors(convertors) {
}
PubSubOwnerSubscriptionsConvertor::~PubSubOwnerSubscriptionsConvertor() {
}
std::shared_ptr<PubSubOwnerSubscriptions> PubSubOwnerSubscriptionsConvertor::doConvertFromLua(lua_State* L) {
std::shared_ptr<PubSubOwnerSubscriptions> result = std::make_shared<PubSubOwnerSubscriptions>();
lua_getfield(L, -1, "node");
if (lua_isstring(L, -1)) {
result->setNode(std::string(lua_tostring(L, -1)));
}
lua_pop(L, 1);
if (lua_type(L, -1) == LUA_TTABLE) {
std::vector< std::shared_ptr<PubSubOwnerSubscription> > items;
for(size_t i = 0; i < lua_objlen(L, -1); ++i) {
lua_pushnumber(L, i + 1);
lua_gettable(L, -2);
if (!lua_isnil(L, -1)) {
if (std::shared_ptr<PubSubOwnerSubscription> payload = std::dynamic_pointer_cast<PubSubOwnerSubscription>(convertors->convertFromLuaUntyped(L, -1, "pubsub_owner_subscription"))) {
items.push_back(payload);
}
}
lua_pop(L, 1);
}
result->setSubscriptions(items);
}
return result;
}
void PubSubOwnerSubscriptionsConvertor::doConvertToLua(lua_State* L, std::shared_ptr<PubSubOwnerSubscriptions> payload) {
lua_createtable(L, 0, 0);
lua_pushstring(L, payload->getNode().c_str());
lua_setfield(L, -2, "node");
if (!payload->getSubscriptions().empty()) {
{
int i = 0;
- foreach(std::shared_ptr<PubSubOwnerSubscription> item, payload->getSubscriptions()) {
+ for (auto&& item : payload->getSubscriptions()) {
if (convertors->convertToLuaUntyped(L, item) > 0) {
lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
++i;
}
}
}
}
}
boost::optional<LuaElementConvertor::Documentation> PubSubOwnerSubscriptionsConvertor::getDocumentation() const {
return Documentation(
"PubSubOwnerSubscriptions",
"This table has the following fields:\n\n"
"- `node`: string\n"
"- `subscriptions`: array<@{PubSubOwnerSubscription}>\n"
);
}
diff --git a/Sluift/ElementConvertors/PubSubPublishConvertor.cpp b/Sluift/ElementConvertors/PubSubPublishConvertor.cpp
index 38aca0a..63c97bc 100644
--- a/Sluift/ElementConvertors/PubSubPublishConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubPublishConvertor.cpp
@@ -1,82 +1,80 @@
/*
* Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/PubSubPublishConvertor.h>
#include <memory>
#include <boost/numeric/conversion/cast.hpp>
#include <lua.hpp>
-#include <Swiften/Base/foreach.h>
-
#include <Sluift/LuaElementConvertors.h>
using namespace Swift;
PubSubPublishConvertor::PubSubPublishConvertor(LuaElementConvertors* convertors) :
GenericLuaElementConvertor<PubSubPublish>("pubsub_publish"),
convertors(convertors) {
}
PubSubPublishConvertor::~PubSubPublishConvertor() {
}
std::shared_ptr<PubSubPublish> PubSubPublishConvertor::doConvertFromLua(lua_State* L) {
std::shared_ptr<PubSubPublish> result = std::make_shared<PubSubPublish>();
lua_getfield(L, -1, "node");
if (lua_isstring(L, -1)) {
result->setNode(std::string(lua_tostring(L, -1)));
}
lua_pop(L, 1);
lua_getfield(L, -1, "items");
if (lua_type(L, -1) == LUA_TTABLE) {
std::vector< std::shared_ptr<PubSubItem> > items;
for(size_t i = 0; i < lua_objlen(L, -1); ++i) {
lua_pushnumber(L, i + 1);
lua_gettable(L, -2);
if (!lua_isnil(L, -1)) {
if (std::shared_ptr<PubSubItem> payload = std::dynamic_pointer_cast<PubSubItem>(convertors->convertFromLuaUntyped(L, -1, "pubsub_item"))) {
items.push_back(payload);
}
}
lua_pop(L, 1);
}
result->setItems(items);
}
lua_pop(L, 1);
return result;
}
void PubSubPublishConvertor::doConvertToLua(lua_State* L, std::shared_ptr<PubSubPublish> payload) {
lua_createtable(L, 0, 0);
lua_pushstring(L, payload->getNode().c_str());
lua_setfield(L, -2, "node");
if (!payload->getItems().empty()) {
lua_createtable(L, boost::numeric_cast<int>(payload->getItems().size()), 0);
{
int i = 0;
- foreach(std::shared_ptr<PubSubItem> item, payload->getItems()) {
+ for (auto&& item : payload->getItems()) {
if (convertors->convertToLuaUntyped(L, item) > 0) {
lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
++i;
}
}
}
lua_setfield(L, -2, "items");
}
}
boost::optional<LuaElementConvertor::Documentation> PubSubPublishConvertor::getDocumentation() const {
return Documentation(
"PubSubPublish",
"This table has the following fields:\n\n"
"- `node`: string\n"
"- `items`: array<@{PubSubItem}>\n"
);
}
diff --git a/Sluift/ElementConvertors/PubSubRetractConvertor.cpp b/Sluift/ElementConvertors/PubSubRetractConvertor.cpp
index 38e15a1..c070ad6 100644
--- a/Sluift/ElementConvertors/PubSubRetractConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubRetractConvertor.cpp
@@ -1,92 +1,90 @@
/*
* Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/PubSubRetractConvertor.h>
#include <memory>
#include <boost/numeric/conversion/cast.hpp>
#include <lua.hpp>
-#include <Swiften/Base/foreach.h>
-
#include <Sluift/LuaElementConvertors.h>
using namespace Swift;
PubSubRetractConvertor::PubSubRetractConvertor(LuaElementConvertors* convertors) :
GenericLuaElementConvertor<PubSubRetract>("pubsub_retract"),
convertors(convertors) {
}
PubSubRetractConvertor::~PubSubRetractConvertor() {
}
std::shared_ptr<PubSubRetract> PubSubRetractConvertor::doConvertFromLua(lua_State* L) {
std::shared_ptr<PubSubRetract> result = std::make_shared<PubSubRetract>();
lua_getfield(L, -1, "node");
if (lua_isstring(L, -1)) {
result->setNode(std::string(lua_tostring(L, -1)));
}
lua_pop(L, 1);
lua_getfield(L, -1, "items");
if (lua_type(L, -1) == LUA_TTABLE) {
std::vector< std::shared_ptr<PubSubItem> > items;
for(size_t i = 0; i < lua_objlen(L, -1); ++i) {
lua_pushnumber(L, i + 1);
lua_gettable(L, -2);
if (!lua_isnil(L, -1)) {
if (std::shared_ptr<PubSubItem> payload = std::dynamic_pointer_cast<PubSubItem>(convertors->convertFromLuaUntyped(L, -1, "pubsub_item"))) {
items.push_back(payload);
}
}
lua_pop(L, 1);
}
result->setItems(items);
}
lua_pop(L, 1);
lua_getfield(L, -1, "notify");
if (lua_isboolean(L, -1)) {
result->setNotify(lua_toboolean(L, -1));
}
lua_pop(L, 1);
return result;
}
void PubSubRetractConvertor::doConvertToLua(lua_State* L, std::shared_ptr<PubSubRetract> payload) {
lua_createtable(L, 0, 0);
lua_pushstring(L, payload->getNode().c_str());
lua_setfield(L, -2, "node");
if (!payload->getItems().empty()) {
lua_createtable(L, boost::numeric_cast<int>(payload->getItems().size()), 0);
{
int i = 0;
- foreach(std::shared_ptr<PubSubItem> item, payload->getItems()) {
+ for (auto&& item : payload->getItems()) {
if (convertors->convertToLuaUntyped(L, item) > 0) {
lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
++i;
}
}
}
lua_setfield(L, -2, "items");
}
if (payload->isNotify().is_initialized()) {
lua_pushboolean(L, payload->isNotify().get_value_or(false));
lua_setfield(L, -2, "notify");
}
}
boost::optional<LuaElementConvertor::Documentation> PubSubRetractConvertor::getDocumentation() const {
return Documentation(
"PubSubRetract",
"This table has the following fields:\n\n"
"- `node`: string\n"
"- `items`: array<@{PubSubItem}>\n"
"- `notify`: boolean\n"
);
}
diff --git a/Sluift/ElementConvertors/PubSubSubscriptionsConvertor.cpp b/Sluift/ElementConvertors/PubSubSubscriptionsConvertor.cpp
index 4cc5686..3712192 100644
--- a/Sluift/ElementConvertors/PubSubSubscriptionsConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubSubscriptionsConvertor.cpp
@@ -1,80 +1,78 @@
/*
* Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/PubSubSubscriptionsConvertor.h>
#include <memory>
#include <boost/numeric/conversion/cast.hpp>
#include <lua.hpp>
-#include <Swiften/Base/foreach.h>
-
#include <Sluift/LuaElementConvertors.h>
using namespace Swift;
PubSubSubscriptionsConvertor::PubSubSubscriptionsConvertor(LuaElementConvertors* convertors) :
GenericLuaElementConvertor<PubSubSubscriptions>("pubsub_subscriptions"),
convertors(convertors) {
}
PubSubSubscriptionsConvertor::~PubSubSubscriptionsConvertor() {
}
std::shared_ptr<PubSubSubscriptions> PubSubSubscriptionsConvertor::doConvertFromLua(lua_State* L) {
std::shared_ptr<PubSubSubscriptions> result = std::make_shared<PubSubSubscriptions>();
lua_getfield(L, -1, "node");
if (lua_isstring(L, -1)) {
result->setNode(std::string(lua_tostring(L, -1)));
}
lua_pop(L, 1);
if (lua_type(L, -1) == LUA_TTABLE) {
std::vector< std::shared_ptr<PubSubSubscription> > items;
for(size_t i = 0; i < lua_objlen(L, -1); ++i) {
lua_pushnumber(L, i + 1);
lua_gettable(L, -2);
if (!lua_isnil(L, -1)) {
if (std::shared_ptr<PubSubSubscription> payload = std::dynamic_pointer_cast<PubSubSubscription>(convertors->convertFromLuaUntyped(L, -1, "pubsub_subscription"))) {
items.push_back(payload);
}
}
lua_pop(L, 1);
}
result->setSubscriptions(items);
}
return result;
}
void PubSubSubscriptionsConvertor::doConvertToLua(lua_State* L, std::shared_ptr<PubSubSubscriptions> payload) {
lua_createtable(L, 0, 0);
if (payload->getNode()) {
lua_pushstring(L, (*payload->getNode()).c_str());
lua_setfield(L, -2, "node");
}
if (!payload->getSubscriptions().empty()) {
{
int i = 0;
- foreach(std::shared_ptr<PubSubSubscription> item, payload->getSubscriptions()) {
+ for (auto&& item : payload->getSubscriptions()) {
if (convertors->convertToLuaUntyped(L, item) > 0) {
lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
++i;
}
}
}
}
}
boost::optional<LuaElementConvertor::Documentation> PubSubSubscriptionsConvertor::getDocumentation() const {
return Documentation(
"PubSubSubscriptions",
"This table has the following fields:\n\n"
"- `node`: string (Optional)\n"
"- `subscriptions`: array<@{PubSubSubscription}>\n"
);
}
diff --git a/Sluift/ElementConvertors/SecurityLabelConvertor.cpp b/Sluift/ElementConvertors/SecurityLabelConvertor.cpp
index 133b123..21d9a8f 100644
--- a/Sluift/ElementConvertors/SecurityLabelConvertor.cpp
+++ b/Sluift/ElementConvertors/SecurityLabelConvertor.cpp
@@ -1,100 +1,98 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/SecurityLabelConvertor.h>
#include <memory>
#include <boost/numeric/conversion/cast.hpp>
#include <lua.hpp>
-#include <Swiften/Base/foreach.h>
-
using namespace Swift;
SecurityLabelConvertor::SecurityLabelConvertor() :
GenericLuaElementConvertor<SecurityLabel>("security_label") {
}
SecurityLabelConvertor::~SecurityLabelConvertor() {
}
std::shared_ptr<SecurityLabel> SecurityLabelConvertor::doConvertFromLua(lua_State* L) {
std::shared_ptr<SecurityLabel> result = std::make_shared<SecurityLabel>();
lua_getfield(L, -1, "equivalent_labels");
if (lua_type(L, -1) == LUA_TTABLE) {
std::vector< std::string > items;
for(size_t i = 0; i < lua_objlen(L, -1); ++i) {
lua_pushnumber(L, i + 1);
lua_gettable(L, -2);
if (lua_isstring(L, -1)) {
items.push_back(std::string(lua_tostring(L, -1)));
}
lua_pop(L, 1);
}
result->setEquivalentLabels(items);
}
lua_pop(L, 1);
lua_getfield(L, -1, "foreground_color");
if (lua_isstring(L, -1)) {
result->setForegroundColor(std::string(lua_tostring(L, -1)));
}
lua_pop(L, 1);
lua_getfield(L, -1, "display_marking");
if (lua_isstring(L, -1)) {
result->setDisplayMarking(std::string(lua_tostring(L, -1)));
}
lua_pop(L, 1);
lua_getfield(L, -1, "background_color");
if (lua_isstring(L, -1)) {
result->setBackgroundColor(std::string(lua_tostring(L, -1)));
}
lua_pop(L, 1);
lua_getfield(L, -1, "label");
if (lua_isstring(L, -1)) {
result->setLabel(std::string(lua_tostring(L, -1)));
}
lua_pop(L, 1);
return result;
}
void SecurityLabelConvertor::doConvertToLua(lua_State* L, std::shared_ptr<SecurityLabel> payload) {
lua_createtable(L, 0, 0);
if (!payload->getEquivalentLabels().empty()) {
lua_createtable(L, boost::numeric_cast<int>(payload->getEquivalentLabels().size()), 0);
{
int i = 0;
- foreach(const std::string& item, payload->getEquivalentLabels()) {
+ for (const auto& item : payload->getEquivalentLabels()) {
lua_pushstring(L, item.c_str());
lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
++i;
}
}
lua_setfield(L, -2, "equivalent_labels");
}
lua_pushstring(L, payload->getForegroundColor().c_str());
lua_setfield(L, -2, "foreground_color");
lua_pushstring(L, payload->getDisplayMarking().c_str());
lua_setfield(L, -2, "display_marking");
lua_pushstring(L, payload->getBackgroundColor().c_str());
lua_setfield(L, -2, "background_color");
lua_pushstring(L, payload->getLabel().c_str());
lua_setfield(L, -2, "label");
}
boost::optional<LuaElementConvertor::Documentation> SecurityLabelConvertor::getDocumentation() const {
return Documentation(
"SecurityLabel",
"This table has the following fields:\n\n"
"- `equivalent_labels`: array<string>\n"
"- `foreground_color`: string\n"
"- `display_marking`: string\n"
"- `background_color`: string\n"
"- `label`: string\n"
);
}
diff --git a/Sluift/ElementConvertors/StanzaConvertor.h b/Sluift/ElementConvertors/StanzaConvertor.h
index e1d0cb3..bdaaad3 100644
--- a/Sluift/ElementConvertors/StanzaConvertor.h
+++ b/Sluift/ElementConvertors/StanzaConvertor.h
@@ -1,41 +1,40 @@
/*
* Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
#include <boost/numeric/conversion/cast.hpp>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Elements/IQ.h>
#include <Swiften/Elements/Message.h>
#include <Swiften/Elements/Payload.h>
#include <Swiften/Elements/Presence.h>
#include <Sluift/GenericLuaElementConvertor.h>
#include <Sluift/Lua/Exception.h>
#include <Sluift/LuaElementConvertors.h>
namespace Swift {
template <typename T> class StanzaConvertor : public GenericLuaElementConvertor<T> {
public:
StanzaConvertor(const std::string& tag)
: GenericLuaElementConvertor<T>(tag) {
}
virtual ~StanzaConvertor() {
}
std::shared_ptr<T> getStanza(lua_State* L, LuaElementConvertors* convertors) {
std::shared_ptr<T> result = std::make_shared<T>();
lua_getfield(L, -1, "id");
if (lua_isstring(L, -1)) {
result->setID(lua_tostring(L, -1));
}
lua_pop(L, 1);
lua_getfield(L, -1, "from");
if (lua_isstring(L, -1)) {
result->setFrom(lua_tostring(L, -1));
}
@@ -48,42 +47,42 @@ namespace Swift {
lua_getfield(L, -1, "payloads");
if (lua_type(L, -1) == LUA_TTABLE) {
for(size_t i = 0; i < lua_objlen(L, -1); ++i) {
lua_pushnumber(L, i + 1);
lua_gettable(L, -2);
if (!lua_isnil(L, -1)) {
std::shared_ptr<Payload> payload = std::dynamic_pointer_cast<Payload>(convertors->convertFromLua(L, -1));
if (!!payload) {
result->addPayload(payload);
}
}
lua_pop(L, 1);
}
}
lua_pop(L, 1);
return result;
}
void pushStanza(lua_State* L, const std::shared_ptr<T> stanza, LuaElementConvertors* convertors) {
lua_createtable(L, 0, 0);
lua_pushstring(L, stanza->getID().c_str());
lua_setfield(L, -2, "id");
lua_pushstring(L, stanza->getFrom().toString().c_str());
lua_setfield(L, -2, "from");
lua_pushstring(L, stanza->getTo().toString().c_str());
lua_setfield(L, -2, "to");
if (!stanza->getPayloads().empty()) {
lua_createtable(L, boost::numeric_cast<int>(stanza->getPayloads().size()), 0);
{
int i = 0;
- foreach(const std::shared_ptr<Payload> &item, stanza->getPayloads()) {
+ for (const auto& item : stanza->getPayloads()) {
if (convertors->convertToLua(L, item) > 0) {
lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
++i;
}
}
}
lua_setfield(L, -2, "payloads");
}
}
};
}
diff --git a/Sluift/Lua/FunctionRegistry.cpp b/Sluift/Lua/FunctionRegistry.cpp
index ebbd087..46c6d18 100644
--- a/Sluift/Lua/FunctionRegistry.cpp
+++ b/Sluift/Lua/FunctionRegistry.cpp
@@ -1,59 +1,57 @@
/*
* Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/Lua/FunctionRegistry.h>
-#include <Swiften/Base/foreach.h>
-
#include <Sluift/Lua/Exception.h>
#include <Sluift/Lua/LuaUtils.h>
#include <Sluift/globals.h>
using namespace Swift::Lua;
FunctionRegistry::FunctionRegistry() {
}
FunctionRegistry::~FunctionRegistry() {
}
FunctionRegistry& FunctionRegistry::getInstance() {
static FunctionRegistry instance;
return instance;
}
void FunctionRegistry::addFunction(
const std::string& name, lua_CFunction function, const std::string& type,
const std::string& helpDescription, const std::string& helpParameters, const std::string& helpOptions) {
Registration registration;
registration.name = name;
registration.function = function;
registration.type = type;
registration.helpDescription = helpDescription;
registration.helpParameters = helpParameters;
registration.helpOptions = helpOptions;
registrations.push_back(registration);
}
void FunctionRegistry::createFunctionTable(lua_State* L, const std::string& type) {
lua_newtable(L);
addFunctionsToTable(L, type);
}
void FunctionRegistry::addFunctionsToTable(lua_State* L, const std::string& type) {
- foreach(const Registration& registration, registrations) {
+ for (const auto& registration : registrations) {
if (registration.type == type) {
lua_pushcclosure(L, registration.function, 0);
if (!registration.helpDescription.empty()) {
Lua::registerHelp(L, -1, registration.helpDescription, registration.helpParameters, registration.helpOptions);
}
else {
Lua::registerExtraHelp(L, -1, registration.type + "." + registration.name);
}
lua_setfield(L, -2, registration.name.c_str());
}
}
}
diff --git a/Sluift/Lua/Value.cpp b/Sluift/Lua/Value.cpp
index 70fbb89..96d954c 100644
--- a/Sluift/Lua/Value.cpp
+++ b/Sluift/Lua/Value.cpp
@@ -1,68 +1,66 @@
/*
* Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/Lua/Value.h>
#include <boost/numeric/conversion/cast.hpp>
#include <boost/variant/apply_visitor.hpp>
extern "C" {
#include <lualib.h>
}
-#include <Swiften/Base/foreach.h>
-
using namespace Swift;
using namespace Swift::Lua;
namespace {
struct PushVisitor : public boost::static_visitor<> {
PushVisitor(lua_State* state) : state(state) {
}
void operator()(const Nil&) const {
lua_pushnil(state);
}
void operator()(const bool& b) const {
lua_pushboolean(state, b);
}
void operator()(const int& i) const {
lua_pushnumber(state, i);
}
void operator()(const std::string& s) const {
lua_pushstring(state, s.c_str());
}
void operator()(const std::vector<Value>& values) const {
lua_createtable(state, boost::numeric_cast<int>(values.size()), 0);
for(size_t i = 0; i < values.size(); ++i) {
boost::apply_visitor(PushVisitor(state), values[i]);
lua_rawseti(state, -2, boost::numeric_cast<int>(i + 1));
}
}
void operator()(const std::map<std::string, std::shared_ptr<Value> >& table) const {
lua_createtable(state, 0, boost::numeric_cast<int>(table.size()));
- for(const auto& i : table) {
+ for (const auto& i : table) {
boost::apply_visitor(PushVisitor(state), *i.second);
lua_setfield(state, -2, i.first.c_str());
}
}
lua_State* state;
};
}
namespace Swift { namespace Lua {
void pushValue(lua_State* state, const Value& value) {
boost::apply_visitor(PushVisitor(state), value);
}
}}
diff --git a/Sluift/LuaElementConvertors.cpp b/Sluift/LuaElementConvertors.cpp
index 38926e9..aac4d93 100644
--- a/Sluift/LuaElementConvertors.cpp
+++ b/Sluift/LuaElementConvertors.cpp
@@ -1,42 +1,40 @@
/*
* Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/LuaElementConvertors.h>
#include <memory>
-#include <Swiften/Base/foreach.h>
-
#include <Sluift/ElementConvertors/BodyConvertor.h>
#include <Sluift/ElementConvertors/CarbonsReceivedConvertor.h>
#include <Sluift/ElementConvertors/CarbonsSentConvertor.h>
#include <Sluift/ElementConvertors/CommandConvertor.h>
#include <Sluift/ElementConvertors/DOMElementConvertor.h>
#include <Sluift/ElementConvertors/DefaultElementConvertor.h>
#include <Sluift/ElementConvertors/DelayConvertor.h>
#include <Sluift/ElementConvertors/DiscoInfoConvertor.h>
#include <Sluift/ElementConvertors/DiscoItemsConvertor.h>
#include <Sluift/ElementConvertors/FormConvertor.h>
#include <Sluift/ElementConvertors/ForwardedConvertor.h>
#include <Sluift/ElementConvertors/IQConvertor.h>
#include <Sluift/ElementConvertors/MAMFinConvertor.h>
#include <Sluift/ElementConvertors/MAMQueryConvertor.h>
#include <Sluift/ElementConvertors/MAMResultConvertor.h>
#include <Sluift/ElementConvertors/MessageConvertor.h>
#include <Sluift/ElementConvertors/PresenceConvertor.h>
#include <Sluift/ElementConvertors/PubSubEventConvertor.h>
#include <Sluift/ElementConvertors/RawXMLElementConvertor.h>
#include <Sluift/ElementConvertors/ResultSetConvertor.h>
#include <Sluift/ElementConvertors/SoftwareVersionConvertor.h>
#include <Sluift/ElementConvertors/StatusConvertor.h>
#include <Sluift/ElementConvertors/StatusShowConvertor.h>
#include <Sluift/ElementConvertors/SubjectConvertor.h>
#include <Sluift/ElementConvertors/VCardConvertor.h>
#include <Sluift/ElementConvertors/VCardUpdateConvertor.h>
#include <Sluift/Lua/Exception.h>
#include <Sluift/Lua/LuaUtils.h>
#include <Sluift/LuaElementConvertor.h>
@@ -68,74 +66,74 @@ LuaElementConvertors::LuaElementConvertors() {
convertors.push_back(std::make_shared<CarbonsReceivedConvertor>(this));
convertors.push_back(std::make_shared<CarbonsSentConvertor>(this));
convertors.push_back(std::make_shared<DOMElementConvertor>());
convertors.push_back(std::make_shared<RawXMLElementConvertor>());
convertors.push_back(std::make_shared<DefaultElementConvertor>());
}
LuaElementConvertors::~LuaElementConvertors() {
}
#include <Sluift/ElementConvertors/ElementConvertors.ipp>
std::shared_ptr<Element> LuaElementConvertors::convertFromLua(lua_State* L, int index) {
if (lua_isstring(L, index)) {
return convertFromLuaUntyped(L, index, "xml");
}
else if (lua_istable(L, index)) {
lua_getfield(L, index, "_type");
if (lua_isstring(L, -1)) {
std::string type = lua_tostring(L, -1);
lua_pop(L, 1);
return convertFromLuaUntyped(L, index, type);
}
lua_pop(L, 1);
}
throw Lua::Exception("Unable to determine type");
}
std::shared_ptr<Element> LuaElementConvertors::convertFromLuaUntyped(lua_State* L, int index, const std::string& type) {
index = Lua::absoluteOffset(L, index);
- foreach (std::shared_ptr<LuaElementConvertor> convertor, convertors) {
+ for (auto&& convertor : convertors) {
if (std::shared_ptr<Element> result = convertor->convertFromLua(L, index, type)) {
return result;
}
}
return std::shared_ptr<Element>();
}
int LuaElementConvertors::convertToLua(lua_State* L, std::shared_ptr<Element> payload) {
if (boost::optional<std::string> type = doConvertToLuaUntyped(L, payload)) {
if (lua_istable(L, -1)) {
lua_pushstring(L, type->c_str());
lua_setfield(L, -2, "_type");
Lua::registerTableToString(L, -1);
}
else {
assert(*type == "xml");
}
return 1;
}
return 0;
}
int LuaElementConvertors::convertToLuaUntyped(lua_State* L, std::shared_ptr<Element> payload) {
if (doConvertToLuaUntyped(L, payload)) {
return 1;
}
return 0;
}
boost::optional<std::string> LuaElementConvertors::doConvertToLuaUntyped(
lua_State* L, std::shared_ptr<Element> payload) {
if (!payload) {
return LuaElementConvertor::NO_RESULT;
}
- foreach (std::shared_ptr<LuaElementConvertor> convertor, convertors) {
+ for (auto&& convertor : convertors) {
if (boost::optional<std::string> type = convertor->convertToLua(L, payload)) {
return *type;
}
}
return LuaElementConvertor::NO_RESULT;
}
diff --git a/Sluift/client.cpp b/Sluift/client.cpp
index 6376e9d..186effc 100644
--- a/Sluift/client.cpp
+++ b/Sluift/client.cpp
@@ -1,42 +1,41 @@
/*
* Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <boost/assign/list_of.hpp>
#include <boost/lambda/bind.hpp>
#include <boost/lambda/lambda.hpp>
#include <Swiften/Base/IDGenerator.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Disco/ClientDiscoManager.h>
#include <Swiften/Elements/DiscoInfo.h>
#include <Swiften/Elements/Message.h>
#include <Swiften/Elements/Presence.h>
#include <Swiften/Elements/RawXMLPayload.h>
#include <Swiften/Elements/RosterItemPayload.h>
#include <Swiften/Elements/RosterPayload.h>
#include <Swiften/Elements/SoftwareVersion.h>
#include <Swiften/JID/JID.h>
#include <Swiften/Presence/PresenceSender.h>
#include <Swiften/Presence/SubscriptionManager.h>
#include <Swiften/Queries/GenericRequest.h>
#include <Swiften/Queries/IQRouter.h>
#include <Swiften/Queries/Requests/GetSoftwareVersionRequest.h>
#include <Swiften/Roster/SetRosterRequest.h>
#include <Swiften/Roster/XMPPRoster.h>
#include <Swiften/Roster/XMPPRosterItem.h>
#include <Swiften/TLS/PKCS12Certificate.h>
#include <Sluift/ElementConvertors/IQConvertor.h>
#include <Sluift/ElementConvertors/MessageConvertor.h>
#include <Sluift/ElementConvertors/PresenceConvertor.h>
#include <Sluift/ElementConvertors/StanzaConvertor.h>
#include <Sluift/ElementConvertors/StatusShowConvertor.h>
#include <Sluift/Lua/Check.h>
#include <Sluift/Lua/Exception.h>
#include <Sluift/Lua/FunctionRegistration.h>
#include <Sluift/Lua/LuaUtils.h>
#include <Sluift/Lua/Value.h>
#include <Sluift/SluiftClient.h>
@@ -158,61 +157,61 @@ SLUIFT_LUA_FUNCTION_WITH_HELP(
SLUIFT_LUA_FUNCTION_WITH_HELP(
Client, set_version,
"Sets the published version of this client.",
"self",
"name the name of the client software\n"
"version the version identifier of this client\n"
"os the OS this client is running on\n"
) {
Sluift::globals.eventLoop.runOnce();
SluiftClient* client = getClient(L);
if (std::shared_ptr<SoftwareVersion> version = std::dynamic_pointer_cast<SoftwareVersion>(Sluift::globals.elementConvertor.convertFromLuaUntyped(L, 2, "software_version"))) {
client->setSoftwareVersion(version->getName(), version->getVersion(), version->getOS());
}
return 0;
}
SLUIFT_LUA_FUNCTION_WITH_HELP(
Client, get_contacts,
"Returns a table of all the contacts in the contact list.",
"self\n",
""
) {
Sluift::globals.eventLoop.runOnce();
SluiftClient* client = getClient(L);
Lua::Table contactsTable;
- foreach(const XMPPRosterItem& item, client->getRoster(getGlobalTimeout(L))) {
+ for (const auto& item : client->getRoster(getGlobalTimeout(L))) {
std::string subscription;
switch(item.getSubscription()) {
case RosterItemPayload::None: subscription = "none"; break;
case RosterItemPayload::To: subscription = "to"; break;
case RosterItemPayload::From: subscription = "from"; break;
case RosterItemPayload::Both: subscription = "both"; break;
case RosterItemPayload::Remove: subscription = "remove"; break;
}
Lua::Table itemTable = boost::assign::map_list_of
("jid", std::make_shared<Lua::Value>(item.getJID().toString()))
("name", std::make_shared<Lua::Value>(item.getName()))
("subscription", std::make_shared<Lua::Value>(subscription))
("groups", std::make_shared<Lua::Value>(std::vector<Lua::Value>(item.getGroups().begin(), item.getGroups().end())));
contactsTable[item.getJID().toString()] = std::make_shared<Lua::Value>(itemTable);
}
pushValue(L, contactsTable);
Lua::registerTableToString(L, -1);
return 1;
}
SLUIFT_LUA_FUNCTION_WITH_HELP(
Client, send_message,
"Send a message.",
"self\n"
"to the JID to send the message to\n"
"body the body of the message. Can alternatively be specified using the `body` option\n",
"to the JID to send the message to\n"
"body the body of the message\n"
"subject the subject of the MUC room to set\n"
diff --git a/Sluift/component.cpp b/Sluift/component.cpp
index 9c2bc3a..df96d43 100644
--- a/Sluift/component.cpp
+++ b/Sluift/component.cpp
@@ -1,42 +1,41 @@
/*
* Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <boost/assign/list_of.hpp>
#include <boost/lambda/bind.hpp>
#include <boost/lambda/lambda.hpp>
#include <Swiften/Base/IDGenerator.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Elements/DiscoInfo.h>
#include <Swiften/Elements/MAMQuery.h>
#include <Swiften/Elements/Message.h>
#include <Swiften/Elements/Presence.h>
#include <Swiften/Elements/RawXMLPayload.h>
#include <Swiften/Elements/RosterItemPayload.h>
#include <Swiften/Elements/RosterPayload.h>
#include <Swiften/Elements/SoftwareVersion.h>
#include <Swiften/JID/JID.h>
#include <Swiften/Presence/PresenceSender.h>
#include <Swiften/Presence/SubscriptionManager.h>
#include <Swiften/Queries/GenericRequest.h>
#include <Swiften/Queries/IQRouter.h>
#include <Swiften/Queries/Requests/GetSoftwareVersionRequest.h>
#include <Swiften/Roster/SetRosterRequest.h>
#include <Swiften/Roster/XMPPRoster.h>
#include <Swiften/Roster/XMPPRosterItem.h>
#include <Sluift/ElementConvertors/IQConvertor.h>
#include <Sluift/ElementConvertors/MessageConvertor.h>
#include <Sluift/ElementConvertors/PresenceConvertor.h>
#include <Sluift/ElementConvertors/StanzaConvertor.h>
#include <Sluift/ElementConvertors/StatusShowConvertor.h>
#include <Sluift/Lua/Check.h>
#include <Sluift/Lua/Exception.h>
#include <Sluift/Lua/FunctionRegistration.h>
#include <Sluift/Lua/LuaUtils.h>
#include <Sluift/Lua/Value.h>
#include <Sluift/SluiftComponent.h>
#include <Sluift/globals.h>
diff --git a/Sluift/main.cpp b/Sluift/main.cpp
index 05c7179..65d6d60 100644
--- a/Sluift/main.cpp
+++ b/Sluift/main.cpp
@@ -1,48 +1,51 @@
/*
* Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <iostream>
#include <string>
#include <vector>
-#include <iostream>
-#include <lua.hpp>
-#include <Swiften/Base/foreach.h>
-#include <Swiften/Base/Platform.h>
+
+#include <boost/assign/list_of.hpp>
+#include <boost/numeric/conversion/cast.hpp>
+#include <boost/program_options.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/variables_map.hpp>
-#include <boost/program_options.hpp>
#include <boost/version.hpp>
-#include <boost/numeric/conversion/cast.hpp>
-#include <boost/assign/list_of.hpp>
+
+#include <lua.hpp>
+
+#include <Swiften/Base/Platform.h>
+
#include <Sluift/globals.h>
#include <Sluift/Console.h>
#include <Sluift/StandardTerminal.h>
#include <Sluift/sluift.h>
#include <Sluift/Lua/LuaUtils.h>
#ifdef HAVE_EDITLINE
#include <Sluift/EditlineTerminal.h>
#endif
#include <Sluift/Version.h>
using namespace Swift;
#ifdef SWIFTEN_PLATFORM_WINDOWS
#define EXIT_KEY "Z"
#else
#define EXIT_KEY "D"
#endif
static const std::string SLUIFT_WELCOME_STRING(
"== Sluift XMPP Console (" SLUIFT_VERSION_STRING ")\nPress Ctrl-" EXIT_KEY " to exit. Type help() for help.");
static const luaL_Reg defaultLibraries[] = {
{"", luaopen_base},
{LUA_LOADLIBNAME, luaopen_package},
{LUA_TABLIBNAME, luaopen_table},
{LUA_IOLIBNAME, luaopen_io},
{LUA_OSLIBNAME, luaopen_os},
{LUA_STRLIBNAME, luaopen_string},
{LUA_MATHLIBNAME, luaopen_math},
{LUA_DBLIBNAME, luaopen_debug},
@@ -60,61 +63,61 @@ static void checkResult(lua_State* L, int result) {
throw std::runtime_error(errorMessage ? errorMessage : "Unknown error");
}
}
static void initialize(lua_State* L) {
lua_gc(L, LUA_GCSTOP, 0);
for (const luaL_Reg* lib = defaultLibraries; lib->func; lib++) {
#if LUA_VERSION_NUM >= 502
luaL_requiref(L, lib->name, lib->func, 1);
lua_pop(L, 1);
#else
lua_pushcfunction(L, lib->func);
lua_pushstring(L, lib->name);
lua_call(L, 1, 0);
#endif
}
lua_gc(L, LUA_GCRESTART, 0);
}
static void runScript(lua_State* L, const std::string& script, const std::vector<std::string>& scriptArguments) {
// Create arguments table
lua_createtable(L, boost::numeric_cast<int>(scriptArguments.size()), 0);
for (size_t i = 0; i < scriptArguments.size(); ++i) {
lua_pushstring(L, scriptArguments[i].c_str());
lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
}
lua_setglobal(L, "arg");
// Load file
checkResult(L, luaL_loadfile(L, script.c_str()));
- foreach (const std::string& scriptArgument, scriptArguments) {
+ for (const auto& scriptArgument : scriptArguments) {
lua_pushstring(L, scriptArgument.c_str());
}
checkResult(L, Console::call(L, boost::numeric_cast<int>(scriptArguments.size()), false));
}
int main(int argc, char* argv[]) {
// Parse program options
boost::program_options::options_description visibleOptions("Options");
visibleOptions.add_options()
("help,h", "Display this help message")
("version,v", "Display version information")
("interactive,i", "Enter interactive mode after executing script")
;
boost::program_options::options_description hiddenOptions("Hidden Options");
hiddenOptions.add_options()
("script", boost::program_options::value< std::string >(), "Script to be executed")
("script-arguments", boost::program_options::value< std::vector<std::string> >(), "Script arguments")
;
boost::program_options::options_description options("All Options");
options.add(visibleOptions).add(hiddenOptions);
boost::program_options::positional_options_description positional_options;
positional_options.add("script", 1).add("script-arguments", -1);
boost::program_options::variables_map arguments;
try {
boost::program_options::store(
boost::program_options::command_line_parser(argc, argv)
.options(options)
.positional(positional_options).run(), arguments);
@@ -136,54 +139,54 @@ int main(int argc, char* argv[]) {
if (arguments.count("help")) {
std::cout << visibleOptions << "\n";
return 0;
}
else if (arguments.count("version")) {
std::cout << SLUIFT_VERSION_STRING;
return 0;
}
lua_State* L = luaL_newstate();
initialize(L);
try {
// Run script
if (arguments.count("script")) {
std::vector<std::string> scriptArguments;
if (arguments.count("script-arguments")) {
scriptArguments = arguments["script-arguments"].as< std::vector<std::string> >();
}
runScript(L, arguments["script"].as<std::string>(), scriptArguments);
}
// Run console
if (arguments.count("interactive") || arguments.count("script") == 0) {
// Set up signal handler
signal(SIGINT, handleInterruptSignal);
// Import some useful functions into the global namespace
lua_getglobal(L, "sluift");
std::vector<std::string> globalImports = boost::assign::list_of
("help")("with");
- foreach (const std::string& globalImport, globalImports) {
+ for (const auto& globalImport : globalImports) {
lua_getfield(L, -1, globalImport.c_str());
lua_setglobal(L, globalImport.c_str());
}
lua_pop(L, 1);
std::cout << SLUIFT_WELCOME_STRING << std::endl;
#ifdef HAVE_EDITLINE
EditlineTerminal& terminal = EditlineTerminal::getInstance();
#else
StandardTerminal terminal;
#endif
Console console(L, &terminal);
console.run();
}
}
catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
lua_close(L);
return -1;
}
lua_close(L);
return 0;
}
diff --git a/Sluift/sluift.cpp b/Sluift/sluift.cpp
index d92f0db..561f404 100644
--- a/Sluift/sluift.cpp
+++ b/Sluift/sluift.cpp
@@ -1,49 +1,48 @@
/*
* Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/sluift.h>
#include <string>
#include <boost/assign/list_of.hpp>
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
#include <boost/numeric/conversion/cast.hpp>
#include <lua.hpp>
#include <Swiften/Base/IDGenerator.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Base/sleep.h>
#include <Swiften/Crypto/CryptoProvider.h>
#include <Swiften/Crypto/PlatformCryptoProvider.h>
#include <Swiften/IDN/IDNConverter.h>
#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h>
#include <Swiften/Serializer/PayloadSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h>
#include <Swiften/StringCodecs/Base64.h>
#include <Swiften/StringCodecs/Hexify.h>
#include <Swiften/TLS/Certificate.h>
#include <Swiften/TLS/CertificateFactory.h>
#include <Sluift/ITunesInterface.h>
#include <Sluift/Lua/Check.h>
#include <Sluift/Lua/Debug.h>
#include <Sluift/Lua/Exception.h>
#include <Sluift/Lua/FunctionRegistration.h>
#include <Sluift/Lua/LuaUtils.h>
#include <Sluift/LuaElementConvertor.h>
#include <Sluift/SluiftClient.h>
#include <Sluift/SluiftComponent.h>
#include <Sluift/Watchdog.h>
#include <Sluift/globals.h>
using namespace Swift;
namespace Swift {
namespace Sluift {
SluiftGlobals globals;
}
@@ -434,69 +433,69 @@ SLUIFT_API int luaopen_sluift(lua_State* L) {
// Load core lib code
if (luaL_loadbuffer(L, core_lua, core_lua_size, "core.lua") != 0) {
lua_error(L);
}
lua_pushvalue(L, -2);
lua_call(L, 1, 1);
Sluift::globals.coreLibIndex = luaL_ref(L, LUA_REGISTRYINDEX);
// Register functions
Lua::FunctionRegistry::getInstance().addFunctionsToTable(L, "Sluift");
Lua::FunctionRegistry::getInstance().createFunctionTable(L, "JID");
lua_setfield(L, -2, "jid");
Lua::FunctionRegistry::getInstance().createFunctionTable(L, "Base64");
lua_setfield(L, -2, "base64");
Lua::FunctionRegistry::getInstance().createFunctionTable(L, "IDN");
lua_setfield(L, -2, "idn");
Lua::FunctionRegistry::getInstance().createFunctionTable(L, "Crypto");
lua_setfield(L, -2, "crypto");
Lua::FunctionRegistry::getInstance().createFunctionTable(L, "FS");
lua_setfield(L, -2, "fs");
#ifdef HAVE_ITUNES
Lua::FunctionRegistry::getInstance().createFunctionTable(L, "iTunes");
lua_setfield(L, -2, "itunes");
#endif
// Register convenience functions
lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.coreLibIndex);
std::vector<std::string> coreLibExports = boost::assign::list_of
("tprint")("disco")("help")("get_help")("copy")("with")("read_file")("create_form");
- foreach (const std::string& coreLibExport, coreLibExports) {
+ for (const auto& coreLibExport : coreLibExports) {
lua_getfield(L, -1, coreLibExport.c_str());
lua_setfield(L, -3, coreLibExport.c_str());
}
lua_pop(L, 1);
// Load client metatable
lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.coreLibIndex);
std::vector<std::string> tables = boost::assign::list_of("Client");
- foreach(const std::string& table, tables) {
+ for (const auto& table : tables) {
lua_getfield(L, -1, table.c_str());
Lua::FunctionRegistry::getInstance().addFunctionsToTable(L, table);
lua_pop(L, 1);
}
lua_pop(L, 1);
// Load component metatable
lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.coreLibIndex);
std::vector<std::string> comp_tables = boost::assign::list_of("Component");
- foreach(const std::string& table, comp_tables) {
+ for (const auto& table : comp_tables) {
lua_getfield(L, -1, table.c_str());
Lua::FunctionRegistry::getInstance().addFunctionsToTable(L, table);
lua_pop(L, 1);
}
lua_pop(L, 1);
// Register documentation for all elements
- foreach (std::shared_ptr<LuaElementConvertor> convertor, Sluift::globals.elementConvertor.getConvertors()) {
+ for (auto&& convertor : Sluift::globals.elementConvertor.getConvertors()) {
boost::optional<LuaElementConvertor::Documentation> documentation = convertor->getDocumentation();
if (documentation) {
Lua::registerClassHelp(L, documentation->className, documentation->description);
}
}
// Register global documentation
Lua::registerExtraHelp(L, -1, "sluift");
return 1;
}
diff --git a/SwifTools/Application/ApplicationPathProvider.cpp b/SwifTools/Application/ApplicationPathProvider.cpp
index a5080f9..8b952bb 100644
--- a/SwifTools/Application/ApplicationPathProvider.cpp
+++ b/SwifTools/Application/ApplicationPathProvider.cpp
@@ -1,49 +1,48 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <SwifTools/Application/ApplicationPathProvider.h>
#include <boost/filesystem.hpp>
#include <Swiften/Base/Log.h>
#include <Swiften/Base/Paths.h>
-#include <Swiften/Base/foreach.h>
namespace Swift {
ApplicationPathProvider::ApplicationPathProvider(const std::string& applicationName) : applicationName(applicationName) {
}
ApplicationPathProvider::~ApplicationPathProvider() {
}
boost::filesystem::path ApplicationPathProvider::getProfileDir(const std::string& profile) const {
boost::filesystem::path result(getHomeDir() / profile);
try {
boost::filesystem::create_directory(result);
}
catch (const boost::filesystem::filesystem_error& e) {
SWIFT_LOG(error) << e.what() << std::endl;
}
return result;
}
boost::filesystem::path ApplicationPathProvider::getResourcePath(const std::string& resource) const {
std::vector<boost::filesystem::path> resourcePaths = getResourceDirs();
- foreach(const boost::filesystem::path& resourcePath, resourcePaths) {
+ for (const auto& resourcePath : resourcePaths) {
boost::filesystem::path r(resourcePath / resource);
if (boost::filesystem::exists(r)) {
return r;
}
}
return boost::filesystem::path();
}
boost::filesystem::path ApplicationPathProvider::getExecutableDir() const {
return Paths::getExecutablePath();
}
}
diff --git a/SwifTools/Application/UnixApplicationPathProvider.cpp b/SwifTools/Application/UnixApplicationPathProvider.cpp
index c561d72..e455d23 100644
--- a/SwifTools/Application/UnixApplicationPathProvider.cpp
+++ b/SwifTools/Application/UnixApplicationPathProvider.cpp
@@ -1,64 +1,62 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <SwifTools/Application/UnixApplicationPathProvider.h>
#include <stdlib.h>
-#include <iostream>
-
#include <boost/algorithm/string.hpp>
#include <unistd.h>
+#include <Swiften/Base/Log.h>
#include <Swiften/Base/String.h>
-#include <Swiften/Base/foreach.h>
namespace Swift {
UnixApplicationPathProvider::UnixApplicationPathProvider(const std::string& name) : ApplicationPathProvider(name) {
resourceDirs.push_back(getExecutableDir() / "../resources"); // Development
resourceDirs.push_back(getExecutableDir() / ".." / "share" / boost::to_lower_copy(getApplicationName())); // Local install
char* xdgDataDirs = getenv("XDG_DATA_DIRS");
if (xdgDataDirs) {
std::vector<std::string> dataDirs = String::split(xdgDataDirs, ':');
if (!dataDirs.empty()) {
- foreach(const std::string& dir, dataDirs) {
+ for (const auto& dir : dataDirs) {
resourceDirs.push_back(boost::filesystem::path(dir) / "swift");
}
return;
}
}
resourceDirs.push_back("/usr/local/share/" + boost::to_lower_copy(getApplicationName()));
resourceDirs.push_back("/usr/share/" + boost::to_lower_copy(getApplicationName()));
}
boost::filesystem::path UnixApplicationPathProvider::getHomeDir() const {
char* home = getenv("HOME");
return home ? boost::filesystem::path(home) : boost::filesystem::path();
}
boost::filesystem::path UnixApplicationPathProvider::getDataDir() const {
char* xdgDataHome = getenv("XDG_DATA_HOME");
std::string dataDir;
if (xdgDataHome) {
dataDir = std::string(xdgDataHome);
}
boost::filesystem::path dataPath = (dataDir.empty() ?
getHomeDir() / ".local" / "share"
: boost::filesystem::path(dataDir)) / boost::to_lower_copy(getApplicationName());
try {
boost::filesystem::create_directories(dataPath);
}
catch (const boost::filesystem::filesystem_error& e) {
- std::cerr << "ERROR: " << e.what() << std::endl;
+ SWIFT_LOG(error) << "file system error: " << e.what() << std::endl;
}
return dataPath;
}
}
diff --git a/SwifTools/Notifier/GNTPNotifier.cpp b/SwifTools/Notifier/GNTPNotifier.cpp
index 62203b4..89025af 100644
--- a/SwifTools/Notifier/GNTPNotifier.cpp
+++ b/SwifTools/Notifier/GNTPNotifier.cpp
@@ -1,62 +1,61 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
// FIXME: This notifier needs finishing (handling callbacks etc.)
#include <SwifTools/Notifier/GNTPNotifier.h>
#include <cassert>
#include <iostream>
#include <sstream>
#include <boost/bind.hpp>
#include <Swiften/Base/Path.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Network/ConnectionFactory.h>
namespace Swift {
GNTPNotifier::GNTPNotifier(const std::string& name, const boost::filesystem::path& icon, ConnectionFactory* connectionFactory) : name(name), icon(icon), connectionFactory(connectionFactory), initialized(false), registered(false) {
// Registration message
std::ostringstream message;
message << "GNTP/1.0 REGISTER NONE\r\n";
message << "Application-Name: " << name << "\r\n";
message << "Application-Icon: file://" << pathToString(icon) << "\r\n";
message << "Notifications-Count: " << getAllTypes().size() << "\r\n";
std::vector<Notifier::Type> defaultTypes = getDefaultTypes();
std::vector<Notifier::Type> allTypes = getAllTypes();
- foreach(Notifier::Type type, allTypes) {
+ for (const auto& type : allTypes) {
message << "\r\n";
message << "Notification-Name: " << typeToString(type) << "\r\n";
message << "Notification-Enabled: " << (std::find(defaultTypes.begin(), defaultTypes.end(), type) == defaultTypes.end() ? "false" : "true") << "\r\n";
}
message << "\r\n";
send(message.str());
}
GNTPNotifier::~GNTPNotifier() {
}
void GNTPNotifier::send(const std::string& message) {
if (currentConnection) {
return;
}
currentMessage = message;
currentConnection = connectionFactory->createConnection();
currentConnection->onConnectFinished.connect(boost::bind(&GNTPNotifier::handleConnectFinished, this, _1));
currentConnection->onDataRead.connect(boost::bind(&GNTPNotifier::handleDataRead, this, _1));
currentConnection->connect(HostAddressPort(HostAddress("127.0.0.1"), 23053));
}
void GNTPNotifier::showMessage(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picture, boost::function<void()>) {
if (registered) {
std::ostringstream message;
message << "GNTP/1.0 NOTIFY NONE\r\n";
message << "Application-Name: " << name << "\r\n";
message << "Notification-Name: " << typeToString(type) << "\r\n";
message << "Notification-Title: " << subject << "\r\n";
diff --git a/SwifTools/TabComplete.cpp b/SwifTools/TabComplete.cpp
index f158ffa..39a70cc 100644
--- a/SwifTools/TabComplete.cpp
+++ b/SwifTools/TabComplete.cpp
@@ -1,56 +1,54 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <SwifTools/TabComplete.h>
#include <algorithm>
#include <boost/algorithm/string.hpp>
-#include <Swiften/Base/foreach.h>
-
namespace Swift {
void TabComplete::addWord(const std::string& word) {
words_.erase(std::remove(words_.begin(), words_.end(), word), words_.end());
words_.insert(words_.begin(), word);
if (boost::starts_with(boost::to_lower_copy(word), lastShort_)) {
lastCompletionCandidates_.insert(lastCompletionCandidates_.begin(), word);
}
}
void TabComplete::removeWord(const std::string& word) {
words_.erase(std::remove(words_.begin(), words_.end(), word), words_.end());
lastCompletionCandidates_.erase(std::remove(lastCompletionCandidates_.begin(), lastCompletionCandidates_.end(), word), lastCompletionCandidates_.end());
}
std::string TabComplete::completeWord(const std::string& word) {
if (word == lastCompletion_) {
if (!lastCompletionCandidates_.empty()) {
size_t match = 0;
for (match = 0; match < lastCompletionCandidates_.size(); match++) {
if (lastCompletionCandidates_[match] == lastCompletion_) {
break;
}
}
size_t nextIndex = match + 1;
nextIndex = nextIndex >= lastCompletionCandidates_.size() ? 0 : nextIndex;
lastCompletion_ = lastCompletionCandidates_[nextIndex];
}
} else {
lastShort_ = boost::to_lower_copy(word);
lastCompletionCandidates_.clear();
- foreach (std::string candidate, words_) {
+ for (auto&& candidate : words_) {
if (boost::starts_with(boost::to_lower_copy(candidate), boost::to_lower_copy(word))) {
lastCompletionCandidates_.push_back(candidate);
}
}
lastCompletion_ = !lastCompletionCandidates_.empty() ? lastCompletionCandidates_[0] : word;
}
return lastCompletion_;
}
}
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);
}
diff --git a/Swiften/Base/foreach.h b/Swiften/Base/foreach.h
deleted file mode 100644
index 3e8ec43..0000000
--- a/Swiften/Base/foreach.h
+++ /dev/null
@@ -1,13 +0,0 @@
-/*
- * Copyright (c) 2010 Isode Limited.
- * All rights reserved.
- * See the COPYING file for more information.
- */
-
-#pragma once
-
-#include <boost/foreach.hpp>
-
-#undef foreach
-#define foreach BOOST_FOREACH
-#define reverse_foreach BOOST_REVERSE_FOREACH
diff --git a/Swiften/Chat/UnitTest/ChatStateNotifierTest.cpp b/Swiften/Chat/UnitTest/ChatStateNotifierTest.cpp
index 278068a..7eeb531 100644
--- a/Swiften/Chat/UnitTest/ChatStateNotifierTest.cpp
+++ b/Swiften/Chat/UnitTest/ChatStateNotifierTest.cpp
@@ -1,42 +1,41 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <boost/bind.hpp>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Chat/ChatStateNotifier.h>
#include <Swiften/Client/DummyStanzaChannel.h>
#include <Swiften/Disco/DummyEntityCapsProvider.h>
using namespace Swift;
class ChatStateNotifierTest : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE(ChatStateNotifierTest);
CPPUNIT_TEST(testStartTypingReply_CapsNotIncluded);
CPPUNIT_TEST(testStartTypingReply_CapsIncluded);
CPPUNIT_TEST(testCancelledNewMessage);
CPPUNIT_TEST(testContinueTypingReply_CapsIncluded);
CPPUNIT_TEST(testTypeReplies_WentOffline);
CPPUNIT_TEST(testContactShouldReceiveStates_CapsOnly);
CPPUNIT_TEST(testContactShouldReceiveStates_CapsNorActive);
CPPUNIT_TEST(testContactShouldReceiveStates_ActiveOverrideOn);
CPPUNIT_TEST(testContactShouldReceiveStates_ActiveOverrideOff);
CPPUNIT_TEST_SUITE_END();
public:
void setUp() {
stanzaChannel = new DummyStanzaChannel();
stanzaChannel->setAvailable(true);
entityCapsProvider = new DummyEntityCapsProvider();
notifier_ = new ChatStateNotifier(stanzaChannel, JID("foo@bar.com/baz"), entityCapsProvider);
notifier_->setContactIsOnline(true);
}
void tearDown() {
delete notifier_;
@@ -115,55 +114,55 @@ public:
notifier_->setUserIsTyping();
notifier_->setUserIsTyping();
notifier_->setUserIsTyping();
CPPUNIT_ASSERT_EQUAL(1, getComposingCount());
notifier_->userSentMessage();
notifier_->setUserIsTyping();
CPPUNIT_ASSERT_EQUAL(2, getComposingCount());
}
void testTypeReplies_WentOffline() {
setContactHas85Caps();
notifier_->setUserIsTyping();
CPPUNIT_ASSERT_EQUAL(1, getComposingCount());
notifier_->setContactIsOnline(false);
notifier_->userSentMessage();
notifier_->setUserIsTyping();
CPPUNIT_ASSERT_EQUAL(1, getComposingCount());
}
private:
void setContactHas85Caps() {
DiscoInfo::ref caps(new DiscoInfo());
caps->addFeature(DiscoInfo::ChatStatesFeature);
entityCapsProvider->caps[JID("foo@bar.com/baz")] = caps;
entityCapsProvider->onCapsChanged(JID("foo@bar.com/baz"));
}
int getComposingCount() const {
int result = 0;
- foreach(std::shared_ptr<Stanza> stanza, stanzaChannel->sentStanzas) {
+ for (auto&& stanza : stanzaChannel->sentStanzas) {
if (stanza->getPayload<ChatState>() && stanza->getPayload<ChatState>()->getChatState() == ChatState::Composing) {
result++;
}
}
return result;
}
int getActiveCount() const {
int result = 0;
- foreach(std::shared_ptr<Stanza> stanza, stanzaChannel->sentStanzas) {
+ for (auto&& stanza : stanzaChannel->sentStanzas) {
if (stanza->getPayload<ChatState>() && stanza->getPayload<ChatState>()->getChatState() == ChatState::Active) {
result++;
}
}
return result;
}
private:
DummyStanzaChannel* stanzaChannel;
DummyEntityCapsProvider* entityCapsProvider;
ChatStateNotifier* notifier_;
};
CPPUNIT_TEST_SUITE_REGISTRATION(ChatStateNotifierTest);
diff --git a/Swiften/Client/BlockListImpl.cpp b/Swiften/Client/BlockListImpl.cpp
index ebffff8..54dcdf5 100644
--- a/Swiften/Client/BlockListImpl.cpp
+++ b/Swiften/Client/BlockListImpl.cpp
@@ -1,74 +1,72 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Client/BlockListImpl.h>
#include <algorithm>
-#include <Swiften/Base/foreach.h>
-
using namespace Swift;
BlockListImpl::BlockListImpl() : state(Init) {
}
void BlockListImpl::setItems(const std::vector<JID>& newItems) {
// JIDs which are in the current list but not in the new list, are removed.
- foreach (const JID& jid, items) {
+ for (const auto& jid : items) {
if (std::find(newItems.begin(), newItems.end(), jid) == newItems.end()) {
onItemRemoved(jid);
}
}
// JIDs which are in the new list but not in the current list, are added.
- foreach (const JID& jid, newItems) {
+ for (const auto& jid : newItems) {
if (std::find(items.begin(), items.end(), jid) == items.end()) {
onItemAdded(jid);
}
}
items = newItems;
}
void BlockListImpl::addItem(const JID& item) {
if (std::find(items.begin(), items.end(), item) == items.end()) {
items.push_back(item);
onItemAdded(item);
}
}
void BlockListImpl::removeItem(const JID& item) {
size_t oldSize = items.size();
items.erase(std::remove(items.begin(), items.end(), item), items.end());
if (items.size() != oldSize) {
onItemRemoved(item);
}
}
void BlockListImpl::setState(State state) {
if (this->state != state) {
this->state = state;
onStateChanged();
}
}
void BlockListImpl::addItems(const std::vector<JID>& items) {
- foreach (const JID& item, items) {
+ for (const auto& item : items) {
addItem(item);
}
}
void BlockListImpl::removeItems(const std::vector<JID>& items) {
std::vector<JID> itemsToRemove = items;
- foreach (const JID& item, itemsToRemove) {
+ for (const auto& item : itemsToRemove) {
removeItem(item);
}
}
void BlockListImpl::removeAllItems() {
removeItems(items);
}
diff --git a/Swiften/Client/CoreClient.cpp b/Swiften/Client/CoreClient.cpp
index c2f8fd7..3d75d8b 100644
--- a/Swiften/Client/CoreClient.cpp
+++ b/Swiften/Client/CoreClient.cpp
@@ -1,47 +1,46 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Client/CoreClient.h>
#include <memory>
#include <boost/bind.hpp>
#include <boost/optional.hpp>
#include <Swiften/Base/Algorithm.h>
#include <Swiften/Base/IDGenerator.h>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Client/ClientSession.h>
#include <Swiften/Client/ClientSessionStanzaChannel.h>
#include <Swiften/Network/ChainedConnector.h>
#include <Swiften/Network/DomainNameResolveError.h>
#include <Swiften/Network/HTTPConnectProxiedConnectionFactory.h>
#include <Swiften/Network/NetworkFactories.h>
#include <Swiften/Network/ProxyProvider.h>
#include <Swiften/Network/SOCKS5ProxiedConnectionFactory.h>
#include <Swiften/Queries/IQRouter.h>
#include <Swiften/Session/BOSHSessionStream.h>
#include <Swiften/Session/BasicSessionStream.h>
#include <Swiften/TLS/CertificateVerificationError.h>
#include <Swiften/TLS/PKCS12Certificate.h>
#include <Swiften/TLS/TLSError.h>
namespace Swift {
CoreClient::CoreClient(const JID& jid, const SafeByteArray& password, NetworkFactories* networkFactories) : jid_(jid), password_(password), networkFactories(networkFactories), disconnectRequested_(false), certificateTrustChecker(nullptr) {
stanzaChannel_ = new ClientSessionStanzaChannel();
stanzaChannel_->onMessageReceived.connect(boost::bind(&CoreClient::handleMessageReceived, this, _1));
stanzaChannel_->onPresenceReceived.connect(boost::bind(&CoreClient::handlePresenceReceived, this, _1));
stanzaChannel_->onStanzaAcked.connect(boost::bind(&CoreClient::handleStanzaAcked, this, _1));
stanzaChannel_->onAvailableChanged.connect(boost::bind(&CoreClient::handleStanzaChannelAvailableChanged, this, _1));
iqRouter_ = new IQRouter(stanzaChannel_);
iqRouter_->setJID(jid);
}
CoreClient::~CoreClient() {
forceReset();
@@ -416,61 +415,61 @@ bool CoreClient::isAvailable() const {
}
bool CoreClient::getStreamManagementEnabled() const {
return stanzaChannel_->getStreamManagementEnabled();
}
bool CoreClient::isStreamEncrypted() const {
return sessionStream_->isTLSEncrypted();
}
StanzaChannel* CoreClient::getStanzaChannel() const {
return stanzaChannel_;
}
const JID& CoreClient::getJID() const {
if (session_) {
return session_->getLocalJID();
}
else {
return jid_;
}
}
void CoreClient::purgePassword() {
safeClear(password_);
}
void CoreClient::resetConnector() {
connector_->onConnectFinished.disconnect(boost::bind(&CoreClient::handleConnectorFinished, this, _1, _2));
connector_.reset();
- foreach(ConnectionFactory* f, proxyConnectionFactories) {
+ for (auto f : proxyConnectionFactories) {
delete f;
}
proxyConnectionFactories.clear();
}
void CoreClient::resetSession() {
session_->onFinished.disconnect(boost::bind(&CoreClient::handleSessionFinished, this, _1));
session_->onNeedCredentials.disconnect(boost::bind(&CoreClient::handleNeedCredentials, this));
sessionStream_->onDataRead.disconnect(boost::bind(&CoreClient::handleDataRead, this, _1));
sessionStream_->onDataWritten.disconnect(boost::bind(&CoreClient::handleDataWritten, this, _1));
if (connection_) {
connection_->disconnect();
}
else if (std::dynamic_pointer_cast<BOSHSessionStream>(sessionStream_)) {
sessionStream_->close();
}
sessionStream_.reset();
connection_.reset();
}
void CoreClient::forceReset() {
if (connector_) {
SWIFT_LOG(warning) << "Client not disconnected properly: Connector still active" << std::endl;
resetConnector();
}
if (sessionStream_ || connection_) {
SWIFT_LOG(warning) << "Client not disconnected properly: Session still active" << std::endl;
resetSession();
diff --git a/Swiften/Client/UnitTest/ClientBlockListManagerTest.cpp b/Swiften/Client/UnitTest/ClientBlockListManagerTest.cpp
index aaf99e0..5d22cac 100644
--- a/Swiften/Client/UnitTest/ClientBlockListManagerTest.cpp
+++ b/Swiften/Client/UnitTest/ClientBlockListManagerTest.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) 2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <algorithm>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Client/ClientBlockListManager.h>
#include <Swiften/Client/DummyStanzaChannel.h>
#include <Swiften/Client/StanzaChannel.h>
#include <Swiften/Elements/IQ.h>
#include <Swiften/Queries/IQRouter.h>
using namespace Swift;
class ClientBlockListManagerTest : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE(ClientBlockListManagerTest);
CPPUNIT_TEST(testFetchBlockList);
CPPUNIT_TEST(testBlockCommand);
CPPUNIT_TEST(testUnblockCommand);
CPPUNIT_TEST(testUnblockAllCommand);
CPPUNIT_TEST_SUITE_END();
public:
void setUp() {
ownJID_ = JID("kev@wonderland.lit");
stanzaChannel_ = new DummyStanzaChannel();
iqRouter_ = new IQRouter(stanzaChannel_);
iqRouter_->setJID(ownJID_);
clientBlockListManager_ = new ClientBlockListManager(iqRouter_);
}
void testFetchBlockList() {
std::vector<JID> blockJids;
blockJids.push_back(JID("romeo@montague.net"));
blockJids.push_back(JID("iago@shakespeare.lit"));
helperInitialBlockListFetch(blockJids);
@@ -144,52 +143,52 @@ class ClientBlockListManagerTest : public CppUnit::TestFixture {
std::shared_ptr<UnblockPayload> pushPayload = std::make_shared<UnblockPayload>();
IQ::ref unblockPush = IQ::createRequest(IQ::Set, ownJID_, "push1", pushPayload);
stanzaChannel_->sendIQ(unblockPush);
stanzaChannel_->onIQReceived(unblockPush);
CPPUNIT_ASSERT_EQUAL(true, clientBlockListManager_->getBlockList()->getItems().empty());
}
void tearDown() {
delete clientBlockListManager_;
delete iqRouter_;
delete stanzaChannel_;
}
private:
void helperInitialBlockListFetch(const std::vector<JID>& blockedJids) {
std::shared_ptr<BlockList> blockList = clientBlockListManager_->requestBlockList();
CPPUNIT_ASSERT(blockList);
// check for IQ request
IQ::ref request = stanzaChannel_->getStanzaAtIndex<IQ>(0);
CPPUNIT_ASSERT(request.get() != nullptr);
std::shared_ptr<BlockListPayload> requestPayload = request->getPayload<BlockListPayload>();
CPPUNIT_ASSERT(requestPayload.get() != nullptr);
CPPUNIT_ASSERT_EQUAL(BlockList::Requesting, blockList->getState());
CPPUNIT_ASSERT_EQUAL(BlockList::Requesting, clientBlockListManager_->getBlockList()->getState());
// build IQ response
std::shared_ptr<BlockListPayload> responsePayload = std::make_shared<BlockListPayload>();
- foreach(const JID& jid, blockedJids) {
+ for (const auto& jid : blockedJids) {
responsePayload->addItem(jid);
}
IQ::ref response = IQ::createResult(ownJID_, JID(), request->getID(), responsePayload);
stanzaChannel_->sendIQ(response);
stanzaChannel_->onIQReceived(response);
CPPUNIT_ASSERT_EQUAL(BlockList::Available, clientBlockListManager_->getBlockList()->getState());
CPPUNIT_ASSERT(responsePayload->getItems() == clientBlockListManager_->getBlockList()->getItems());
}
private:
JID ownJID_;
IQRouter* iqRouter_;
DummyStanzaChannel* stanzaChannel_;
ClientBlockListManager* clientBlockListManager_;
};
CPPUNIT_TEST_SUITE_REGISTRATION(ClientBlockListManagerTest);
diff --git a/Swiften/Client/XMLBeautifier.cpp b/Swiften/Client/XMLBeautifier.cpp
index 9e9c4c5..e2cd58e 100644
--- a/Swiften/Client/XMLBeautifier.cpp
+++ b/Swiften/Client/XMLBeautifier.cpp
@@ -1,49 +1,48 @@
/*
* Copyright (c) 2011 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 <Swiften/Client/XMLBeautifier.h>
#include <sstream>
#include <stack>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Parser/PlatformXMLParserFactory.h>
namespace Swift {
XMLBeautifier::XMLBeautifier(bool indention, bool coloring) : doIndention(indention), doColoring(coloring), intLevel(0), parser(nullptr), lastWasStepDown(false) {
factory = new PlatformXMLParserFactory();
}
XMLBeautifier::~XMLBeautifier() {
delete factory;
}
std::string XMLBeautifier::beautify(const std::string &text) {
parser = factory->createXMLParser(this);
intLevel = 0;
buffer.str(std::string());
parser->parse(text);
delete parser;
return buffer.str();
}
void XMLBeautifier::indent() {
for (int i = 0; i < intLevel; ++i) {
buffer << " ";
}
}
// all bold but reset
// static const char colorBlue[] = "\x1b[01;34m";
static const char colorCyan[] = "\x1b[01;36m";
@@ -72,61 +71,61 @@ std::string XMLBeautifier::styleNamespace(const std::string& text) const {
}
std::string XMLBeautifier::styleAttribute(const std::string& text) const {
std::string result;
result += colorGreen;
result += text;
result += colorReset;
return result;
}
std::string XMLBeautifier::styleValue(const std::string& text) const {
std::string result;
result += colorCyan;
result += text;
result += colorReset;
return result;
}
void XMLBeautifier::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
if (doIndention) {
if (intLevel) buffer << std::endl;
}
indent();
buffer << "<" << (doColoring ? styleTag(element) : element);
if (!ns.empty() && (!parentNSs.empty() && parentNSs.top() != ns)) {
buffer << " ";
buffer << (doColoring ? styleAttribute("xmlns") : "xmlns");
buffer << "=";
buffer << "\"" << (doColoring ? styleNamespace(ns) : ns) << "\"";
}
if (!attributes.getEntries().empty()) {
- foreach(AttributeMap::Entry entry, attributes.getEntries()) {
+ for (const auto& entry : attributes.getEntries()) {
buffer << " ";
buffer << (doColoring ? styleAttribute(entry.getAttribute().getName()) : entry.getAttribute().getName());
buffer << "=";
buffer << "\"" << (doColoring ? styleValue(entry.getValue()) : entry.getValue()) << "\"";
}
}
buffer << ">";
++intLevel;
lastWasStepDown = false;
parentNSs.push(ns);
}
void XMLBeautifier::handleEndElement(const std::string& element, const std::string& /* ns */) {
--intLevel;
parentNSs.pop();
if (/*hadCDATA.top() ||*/ lastWasStepDown) {
if (doIndention) {
buffer << std::endl;
}
indent();
}
buffer << "</" << (doColoring ? styleTag(element) : element) << ">";
lastWasStepDown = true;
}
void XMLBeautifier::handleCharacterData(const std::string& data) {
buffer << data;
lastWasStepDown = false;
}
diff --git a/Swiften/Disco/CapsInfoGenerator.cpp b/Swiften/Disco/CapsInfoGenerator.cpp
index b4637c7..961ef43 100644
--- a/Swiften/Disco/CapsInfoGenerator.cpp
+++ b/Swiften/Disco/CapsInfoGenerator.cpp
@@ -1,64 +1,63 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Disco/CapsInfoGenerator.h>
#include <algorithm>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Crypto/CryptoProvider.h>
#include <Swiften/Elements/DiscoInfo.h>
#include <Swiften/Elements/FormField.h>
#include <Swiften/StringCodecs/Base64.h>
namespace {
bool compareFields(Swift::FormField::ref f1, Swift::FormField::ref f2) {
return f1->getName() < f2->getName();
}
}
namespace Swift {
CapsInfoGenerator::CapsInfoGenerator(const std::string& node, CryptoProvider* crypto) : node_(node), crypto_(crypto) {
}
CapsInfo CapsInfoGenerator::generateCapsInfo(const DiscoInfo& discoInfo) const {
std::string serializedCaps;
std::vector<DiscoInfo::Identity> identities(discoInfo.getIdentities());
std::sort(identities.begin(), identities.end());
- foreach (const DiscoInfo::Identity& identity, identities) {
+ for (const auto& identity : identities) {
serializedCaps += identity.getCategory() + "/" + identity.getType() + "/" + identity.getLanguage() + "/" + identity.getName() + "<";
}
std::vector<std::string> features(discoInfo.getFeatures());
std::sort(features.begin(), features.end());
- foreach (const std::string& feature, features) {
+ for (const auto& feature : features) {
serializedCaps += feature + "<";
}
- foreach(Form::ref extension, discoInfo.getExtensions()) {
+ for (const auto& extension : discoInfo.getExtensions()) {
serializedCaps += extension->getFormType() + "<";
std::vector<FormField::ref> fields(extension->getFields());
std::sort(fields.begin(), fields.end(), &compareFields);
- foreach(FormField::ref field, fields) {
+ for (const auto& field : fields) {
if (field->getName() == "FORM_TYPE") {
continue;
}
serializedCaps += field->getName() + "<";
std::vector<std::string> values(field->getValues());
std::sort(values.begin(), values.end());
- foreach(const std::string& value, values) {
+ for (const auto& value : values) {
serializedCaps += value + "<";
}
}
}
std::string version(Base64::encode(crypto_->getSHA1Hash(createByteArray(serializedCaps))));
return CapsInfo(node_, version, "sha-1");
}
}
diff --git a/Swiften/Disco/DiscoServiceWalker.cpp b/Swiften/Disco/DiscoServiceWalker.cpp
index 761e6ab..a3f95d2 100644
--- a/Swiften/Disco/DiscoServiceWalker.cpp
+++ b/Swiften/Disco/DiscoServiceWalker.cpp
@@ -1,131 +1,130 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Disco/DiscoServiceWalker.h>
#include <boost/bind.hpp>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
namespace Swift {
DiscoServiceWalker::DiscoServiceWalker(const JID& service, IQRouter* iqRouter, size_t maxSteps) : service_(service), iqRouter_(iqRouter), maxSteps_(maxSteps), active_(false) {
}
void DiscoServiceWalker::beginWalk() {
SWIFT_LOG(debug) << "Starting walk to " << service_ << std::endl;
assert(!active_);
assert(servicesBeingSearched_.empty());
active_ = true;
walkNode(service_);
}
void DiscoServiceWalker::endWalk() {
if (active_) {
SWIFT_LOG(debug) << "Ending walk to " << service_ << std::endl;
- foreach (GetDiscoInfoRequest::ref request, pendingDiscoInfoRequests_) {
+ for (auto&& request : pendingDiscoInfoRequests_) {
request->onResponse.disconnect(boost::bind(&DiscoServiceWalker::handleDiscoInfoResponse, this, _1, _2, request));
}
- foreach (GetDiscoItemsRequest::ref request, pendingDiscoItemsRequests_) {
+ for (auto&& request : pendingDiscoItemsRequests_) {
request->onResponse.disconnect(boost::bind(&DiscoServiceWalker::handleDiscoItemsResponse, this, _1, _2, request));
}
active_ = false;
onWalkAborted();
}
}
void DiscoServiceWalker::walkNode(const JID& jid) {
SWIFT_LOG(debug) << "Walking node " << jid << std::endl;
servicesBeingSearched_.insert(jid);
searchedServices_.insert(jid);
GetDiscoInfoRequest::ref discoInfoRequest = GetDiscoInfoRequest::create(jid, iqRouter_);
discoInfoRequest->onResponse.connect(boost::bind(&DiscoServiceWalker::handleDiscoInfoResponse, this, _1, _2, discoInfoRequest));
pendingDiscoInfoRequests_.insert(discoInfoRequest);
discoInfoRequest->send();
}
void DiscoServiceWalker::handleDiscoInfoResponse(std::shared_ptr<DiscoInfo> info, ErrorPayload::ref error, GetDiscoInfoRequest::ref request) {
/* If we got canceled, don't do anything */
if (!active_) {
return;
}
SWIFT_LOG(debug) << "Disco info response from " << request->getReceiver() << std::endl;
request->onResponse.disconnect(boost::bind(&DiscoServiceWalker::handleDiscoInfoResponse, this, _1, _2, request));
pendingDiscoInfoRequests_.erase(request);
if (error) {
handleDiscoError(request->getReceiver(), error);
return;
}
bool couldContainServices = false;
- foreach (DiscoInfo::Identity identity, info->getIdentities()) {
+ for (const auto& identity : info->getIdentities()) {
if (identity.getCategory() == "server") {
couldContainServices = true;
}
}
bool completed = false;
if (couldContainServices) {
GetDiscoItemsRequest::ref discoItemsRequest = GetDiscoItemsRequest::create(request->getReceiver(), iqRouter_);
discoItemsRequest->onResponse.connect(boost::bind(&DiscoServiceWalker::handleDiscoItemsResponse, this, _1, _2, discoItemsRequest));
pendingDiscoItemsRequests_.insert(discoItemsRequest);
discoItemsRequest->send();
} else {
completed = true;
}
onServiceFound(request->getReceiver(), info);
if (completed) {
markNodeCompleted(request->getReceiver());
}
}
void DiscoServiceWalker::handleDiscoItemsResponse(std::shared_ptr<DiscoItems> items, ErrorPayload::ref error, GetDiscoItemsRequest::ref request) {
/* If we got canceled, don't do anything */
if (!active_) {
return;
}
SWIFT_LOG(debug) << "Received disco items from " << request->getReceiver() << std::endl;
request->onResponse.disconnect(boost::bind(&DiscoServiceWalker::handleDiscoItemsResponse, this, _1, _2, request));
pendingDiscoItemsRequests_.erase(request);
if (error) {
handleDiscoError(request->getReceiver(), error);
return;
}
- foreach (DiscoItems::Item item, items->getItems()) {
+ for (auto&& item : items->getItems()) {
if (item.getNode().empty()) {
/* Don't look at noded items. It's possible that this will exclude some services,
* but I've never seen one in the wild, and it's an easy fix for not looping.
*/
if (std::find(searchedServices_.begin(), searchedServices_.end(), item.getJID()) == searchedServices_.end()) { /* Don't recurse infinitely */
SWIFT_LOG(debug) << "Received disco item " << item.getJID() << std::endl;
walkNode(item.getJID());
}
}
}
markNodeCompleted(request->getReceiver());
}
void DiscoServiceWalker::handleDiscoError(const JID& jid, ErrorPayload::ref /*error*/) {
SWIFT_LOG(debug) << "Disco error from " << jid << std::endl;
markNodeCompleted(jid);
}
void DiscoServiceWalker::markNodeCompleted(const JID& jid) {
SWIFT_LOG(debug) << "Node completed " << jid << std::endl;
servicesBeingSearched_.erase(jid);
/* All results are in */
if (servicesBeingSearched_.empty()) {
active_ = false;
onWalkComplete();
}
/* Check if we're on a rampage */
else if (searchedServices_.size() >= maxSteps_) {
active_ = false;
onWalkComplete();
diff --git a/Swiften/Elements/Form.cpp b/Swiften/Elements/Form.cpp
index f8414b2..dc4bd72 100644
--- a/Swiften/Elements/Form.cpp
+++ b/Swiften/Elements/Form.cpp
@@ -1,66 +1,64 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Elements/Form.h>
-#include <Swiften/Base/foreach.h>
-
namespace Swift {
std::string Form::getFormType() const {
FormField::ref field = getField("FORM_TYPE");
if (field && field->getType() == FormField::HiddenType) {
return field->getValues().empty() ? "" : field->getValues()[0];
}
return "";
}
FormField::ref Form::getField(const std::string& name) const {
- foreach(FormField::ref field, fields_) {
+ for (const auto& field : fields_) {
if (field->getName() == name) {
return field;
}
}
return FormField::ref();
}
void Form::addReportedField(FormField::ref field) {
reportedFields_.push_back(field);
}
const std::vector<FormField::ref>& Form::getReportedFields() const {
return reportedFields_;
}
void Form::addItem(const Form::FormItem& item) {
items_.push_back(item);
}
const std::vector<Form::FormItem>& Form::getItems() const {
return items_;
}
void Form::clearEmptyTextFields() {
std::vector<FormField::ref> populatedFields;
- foreach (FormField::ref field, fields_) {
+ for (const auto& field : fields_) {
if (field->getType() == FormField::TextSingleType) {
if (!field->getTextSingleValue().empty()) {
populatedFields.push_back(field);
}
}
else if (field->getType() == FormField::TextMultiType) {
if (!field->getTextMultiValue().empty()) {
populatedFields.push_back(field);
}
}
else {
populatedFields.push_back(field);
}
}
fields_ = populatedFields;
}
}
diff --git a/Swiften/Elements/RosterItemExchangePayload.cpp b/Swiften/Elements/RosterItemExchangePayload.cpp
index 1890811..79d0371 100644
--- a/Swiften/Elements/RosterItemExchangePayload.cpp
+++ b/Swiften/Elements/RosterItemExchangePayload.cpp
@@ -1,25 +1,23 @@
/*
* Copyright (c) 2011 Jan Kaluza
* 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 <Swiften/Elements/RosterItemExchangePayload.h>
-#include <Swiften/Base/foreach.h>
-
namespace Swift {
RosterItemExchangePayload::Item::Item(Action action) : action(action) {
}
RosterItemExchangePayload::RosterItemExchangePayload() {
}
}
diff --git a/Swiften/Elements/RosterPayload.cpp b/Swiften/Elements/RosterPayload.cpp
index b4be7d1..d745357 100644
--- a/Swiften/Elements/RosterPayload.cpp
+++ b/Swiften/Elements/RosterPayload.cpp
@@ -1,24 +1,22 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Elements/RosterPayload.h>
-#include <Swiften/Base/foreach.h>
-
namespace Swift {
boost::optional<RosterItemPayload> RosterPayload::getItem(const JID& jid) const {
- foreach(const RosterItemPayload& item, items_) {
+ for (const auto& item : items_) {
// FIXME: MSVC rejects this. Find out why.
//if (item.getJID() == jid) {
if (item.getJID().equals(jid, JID::WithResource)) {
return boost::optional<RosterItemPayload>(item);
}
}
return boost::optional<RosterItemPayload>();
}
}
diff --git a/Swiften/Elements/Stanza.cpp b/Swiften/Elements/Stanza.cpp
index f5a1b58..0ff6b3c 100644
--- a/Swiften/Elements/Stanza.cpp
+++ b/Swiften/Elements/Stanza.cpp
@@ -1,70 +1,69 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Elements/Stanza.h>
#include <typeinfo>
#include <boost/bind.hpp>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Elements/Delay.h>
namespace Swift {
Stanza::Stanza() {
}
Stanza::~Stanza() {
payloads_.clear();
}
void Stanza::updatePayload(std::shared_ptr<Payload> payload) {
- foreach (std::shared_ptr<Payload>& i, payloads_) {
+ for (auto&& i : payloads_) {
if (typeid(*i.get()) == typeid(*payload.get())) {
i = payload;
return;
}
}
addPayload(payload);
}
static bool sameType(std::shared_ptr<Payload> a, std::shared_ptr<Payload> b) {
return typeid(*a.get()) == typeid(*b.get());
}
void Stanza::removePayloadOfSameType(std::shared_ptr<Payload> payload) {
payloads_.erase(std::remove_if(payloads_.begin(), payloads_.end(),
boost::bind<bool>(&sameType, payload, _1)),
payloads_.end());
}
std::shared_ptr<Payload> Stanza::getPayloadOfSameType(std::shared_ptr<Payload> payload) const {
- foreach (const std::shared_ptr<Payload>& i, payloads_) {
+ for (const auto& i : payloads_) {
if (typeid(*i.get()) == typeid(*payload.get())) {
return i;
}
}
return std::shared_ptr<Payload>();
}
boost::optional<boost::posix_time::ptime> Stanza::getTimestamp() const {
std::shared_ptr<Delay> delay = getPayload<Delay>();
return delay ? delay->getStamp() : boost::optional<boost::posix_time::ptime>();
}
boost::optional<boost::posix_time::ptime> Stanza::getTimestampFrom(const JID& jid) const {
std::vector< std::shared_ptr<Delay> > delays = getPayloads<Delay>();
for (auto& delay : delays) {
if (delay->getFrom() == jid) {
return delay->getStamp();
}
}
return getTimestamp();
}
}
diff --git a/Swiften/Elements/VCard.cpp b/Swiften/Elements/VCard.cpp
index f541d06..571ead4 100644
--- a/Swiften/Elements/VCard.cpp
+++ b/Swiften/Elements/VCard.cpp
@@ -1,26 +1,24 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Elements/VCard.h>
-#include <Swiften/Base/foreach.h>
-
namespace Swift {
VCard::EMailAddress VCard::getPreferredEMailAddress() const {
- foreach(const EMailAddress& address, emailAddresses_) {
+ for (const auto& address : emailAddresses_) {
if (address.isPreferred) {
return address;
}
}
if (!emailAddresses_.empty()) {
return emailAddresses_[0];
}
return EMailAddress();
}
}
diff --git a/Swiften/EventLoop/EventLoop.cpp b/Swiften/EventLoop/EventLoop.cpp
index eefbf65..186616f 100644
--- a/Swiften/EventLoop/EventLoop.cpp
+++ b/Swiften/EventLoop/EventLoop.cpp
@@ -1,94 +1,93 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/EventLoop/EventLoop.h>
#include <algorithm>
#include <cassert>
#include <vector>
#include <boost/bind.hpp>
#include <boost/lambda/bind.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/optional.hpp>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
namespace lambda = boost::lambda;
namespace Swift {
inline void invokeCallback(const Event& event) {
try {
assert(!event.callback.empty());
event.callback();
}
catch (const std::exception& e) {
SWIFT_LOG(error) << "Uncaught exception in event loop: " << e.what() << std::endl;
}
catch (...) {
SWIFT_LOG(error) << "Uncaught non-exception in event loop" << std::endl;
}
}
EventLoop::EventLoop() : nextEventID_(0), handlingEvents_(false) {
}
EventLoop::~EventLoop() {
}
void EventLoop::handleNextEvents() {
const int eventsBatched = 100;
// If handleNextEvents is already in progress, e.g. in case of a recursive call due to
// the event loop implementation, then do no handle further events. Instead call
// eventPosted() to continue event handling later.
bool callEventPosted = handlingEvents_;
if (!handlingEvents_) {
handlingEvents_ = true;
std::unique_lock<std::recursive_mutex> lock(removeEventsMutex_);
{
std::vector<Event> nextEvents;
{
std::unique_lock<std::recursive_mutex> lock(eventsMutex_);
for (int n = 0; ((n < eventsBatched) && !events_.empty()); n++) {
nextEvents.push_back(events_.front());
events_.pop_front();
}
callEventPosted = !events_.empty();
}
if (!nextEvents.empty()) {
- foreach (const Event& event, nextEvents) {
+ for (const auto& event : nextEvents) {
invokeCallback(event);
}
}
}
handlingEvents_ = false;
}
if (callEventPosted) {
eventPosted();
}
}
void EventLoop::postEvent(boost::function<void ()> callback, std::shared_ptr<EventOwner> owner) {
Event event(owner, callback);
bool callEventPosted = false;
{
std::unique_lock<std::recursive_mutex> lock(eventsMutex_);
callEventPosted = events_.empty();
event.id = nextEventID_;
nextEventID_++;
events_.push_back(event);
}
if (callEventPosted) {
eventPosted();
}
}
void EventLoop::removeEventsFromOwner(std::shared_ptr<EventOwner> owner) {
diff --git a/Swiften/EventLoop/SimpleEventLoop.cpp b/Swiften/EventLoop/SimpleEventLoop.cpp
index 2397016..cac04e4 100644
--- a/Swiften/EventLoop/SimpleEventLoop.cpp
+++ b/Swiften/EventLoop/SimpleEventLoop.cpp
@@ -1,42 +1,40 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/EventLoop/SimpleEventLoop.h>
#include <boost/bind.hpp>
-#include <Swiften/Base/foreach.h>
-
namespace Swift {
SimpleEventLoop::SimpleEventLoop() : isRunning_(true), eventAvailable_(false) {
}
SimpleEventLoop::~SimpleEventLoop() {
}
void SimpleEventLoop::doRun(bool breakAfterEvents) {
while (isRunning_) {
{
std::unique_lock<std::mutex> lock(eventAvailableMutex_);
while (!eventAvailable_) {
eventAvailableCondition_.wait(lock);
}
eventAvailable_ = false;
}
runOnce();
if (breakAfterEvents) {
return;
}
}
}
void SimpleEventLoop::runOnce() {
handleNextEvents();
}
void SimpleEventLoop::stop() {
diff --git a/Swiften/EventLoop/SingleThreadedEventLoop.cpp b/Swiften/EventLoop/SingleThreadedEventLoop.cpp
index acb6e4d..0542f37 100644
--- a/Swiften/EventLoop/SingleThreadedEventLoop.cpp
+++ b/Swiften/EventLoop/SingleThreadedEventLoop.cpp
@@ -1,62 +1,61 @@
/*
* Copyright (c) 2010 Soren Dreijer
* 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 <Swiften/EventLoop/SingleThreadedEventLoop.h>
#include <iostream>
#include <boost/bind.hpp>
-#include <Swiften/Base/foreach.h>
-
namespace Swift {
SingleThreadedEventLoop::SingleThreadedEventLoop()
: shouldShutDown_(false), eventAvailable_(false)
{
}
SingleThreadedEventLoop::~SingleThreadedEventLoop() {
}
void SingleThreadedEventLoop::waitForEvents() {
std::unique_lock<std::mutex> lock(eventAvailableMutex_);
while (!eventAvailable_ && !shouldShutDown_) {
eventAvailableCondition_.wait(lock);
}
- if (shouldShutDown_)
+ if (shouldShutDown_) {
throw EventLoopCanceledException();
+ }
}
void SingleThreadedEventLoop::handleEvents() {
{
std::lock_guard<std::mutex> lock(eventAvailableMutex_);
eventAvailable_ = false;
}
handleNextEvents();
}
void SingleThreadedEventLoop::stop() {
std::unique_lock<std::mutex> lock(eventAvailableMutex_);
shouldShutDown_ = true;
eventAvailableCondition_.notify_one();
}
void SingleThreadedEventLoop::eventPosted() {
std::lock_guard<std::mutex> lock(eventAvailableMutex_);
eventAvailable_ = true;
eventAvailableCondition_.notify_one();
}
} // namespace Swift
diff --git a/Swiften/Examples/MUCListAndJoin/MUCListAndJoin.cpp b/Swiften/Examples/MUCListAndJoin/MUCListAndJoin.cpp
index c3983f1..10b0b40 100644
--- a/Swiften/Examples/MUCListAndJoin/MUCListAndJoin.cpp
+++ b/Swiften/Examples/MUCListAndJoin/MUCListAndJoin.cpp
@@ -1,80 +1,79 @@
/*
* Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <iostream>
#include <memory>
#include <boost/optional.hpp>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Client/Client.h>
#include <Swiften/Client/ClientXMLTracer.h>
#include <Swiften/Disco/GetDiscoItemsRequest.h>
#include <Swiften/EventLoop/SimpleEventLoop.h>
#include <Swiften/JID/JID.h>
#include <Swiften/MUC/MUC.h>
#include <Swiften/MUC/MUCManager.h>
#include <Swiften/Network/BoostNetworkFactories.h>
#include <Swiften/Network/Timer.h>
#include <Swiften/Network/TimerFactory.h>
using namespace Swift;
using namespace std;
static SimpleEventLoop eventLoop;
static BoostNetworkFactories networkFactories(&eventLoop);
static std::shared_ptr<Client> client;
static MUC::ref muc;
static JID mucJID;
static JID roomJID;
static void joinMUC() {
cout << "Joining " << roomJID.toString() << endl;
muc = client->getMUCManager()->createMUC(roomJID);
muc->joinAs("SwiftExample");
}
static void handleRoomsItemsResponse(std::shared_ptr<DiscoItems> items, ErrorPayload::ref error) {
if (error) {
cout << "Error fetching list of rooms." << endl;
return;
}
int roomCount = 0;
cout << "List of rooms at " << mucJID.toString() << endl;
- foreach (DiscoItems::Item item, items->getItems()) {
+ for (auto&& item : items->getItems()) {
roomCount++;
cout << "\t" << roomCount << ". " << item.getJID().getNode() << " - " << item.getName() << std::endl;
if (roomCount == 1) {
roomJID = item.getJID();
}
}
cout << endl;
joinMUC();
}
static void handleConnected() {
cout << "Connected." << endl;
// search for MUC rooms
GetDiscoItemsRequest::ref discoItemsRequest = GetDiscoItemsRequest::create(mucJID, client->getIQRouter());
discoItemsRequest->onResponse.connect(&handleRoomsItemsResponse);
cout << "Request list of rooms." << endl;
discoItemsRequest->send();
}
static void handleDisconnected(const boost::optional<ClientError>&) {
cout << "Disconnected." << endl;
}
static void handleIncomingMessage(std::shared_ptr<Message> message) {
if (message->getFrom().toBare() == roomJID) {
cout << "[ " << roomJID << " ] " << message->getFrom().getResource() << ": " << message->getBody().get_value_or("") << endl;
}
}
diff --git a/Swiften/Examples/SendFile/ReceiveFile.cpp b/Swiften/Examples/SendFile/ReceiveFile.cpp
index 0b61987..193c1b7 100644
--- a/Swiften/Examples/SendFile/ReceiveFile.cpp
+++ b/Swiften/Examples/SendFile/ReceiveFile.cpp
@@ -1,89 +1,89 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <iostream>
#include <memory>
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Client/Client.h>
#include <Swiften/Client/ClientXMLTracer.h>
#include <Swiften/Disco/ClientDiscoManager.h>
#include <Swiften/Elements/DiscoInfo.h>
#include <Swiften/Elements/Presence.h>
#include <Swiften/EventLoop/SimpleEventLoop.h>
#include <Swiften/FileTransfer/FileTransferManager.h>
#include <Swiften/FileTransfer/FileWriteBytestream.h>
#include <Swiften/FileTransfer/IncomingFileTransferManager.h>
#include <Swiften/FileTransfer/SOCKS5BytestreamRegistry.h>
#include <Swiften/Jingle/JingleSessionManager.h>
#include <Swiften/Network/BoostNetworkFactories.h>
using namespace Swift;
static SimpleEventLoop eventLoop;
static BoostNetworkFactories networkFactories(&eventLoop);
static int exitCode = 2;
static const std::string CLIENT_NAME = "Swiften FT Test";
static const std::string CLIENT_NODE = "http://swift.im";
class FileReceiver {
public:
FileReceiver(const JID& jid, const std::string& password) : jid(jid), password(password) {
client = new Swift::Client(jid, password, &networkFactories);
client->onConnected.connect(boost::bind(&FileReceiver::handleConnected, this));
client->onDisconnected.connect(boost::bind(&FileReceiver::handleDisconnected, this, _1));
tracer = new ClientXMLTracer(client);
}
~FileReceiver() {
delete tracer;
client->onDisconnected.disconnect(boost::bind(&FileReceiver::handleDisconnected, this, _1));
client->onConnected.disconnect(boost::bind(&FileReceiver::handleConnected, this));
delete client;
}
void start() {
client->connect();
}
void stop() {
- foreach(const IncomingFileTransfer::ref transfer, incomingFileTransfers) {
+ for (const auto& transfer : incomingFileTransfers) {
+ (void)transfer;
//transfer->stop();
}
client->disconnect();
}
private:
void handleConnected() {
Log::setLogLevel(Log::debug);
client->getFileTransferManager()->onIncomingFileTransfer.connect(boost::bind(&FileReceiver::handleIncomingFileTransfer, this, _1));
DiscoInfo discoInfo;
discoInfo.addIdentity(DiscoInfo::Identity(CLIENT_NAME, "client", "pc"));
discoInfo.addFeature(DiscoInfo::JingleFeature);
discoInfo.addFeature(DiscoInfo::JingleFTFeature);
discoInfo.addFeature(DiscoInfo::Bytestream);
discoInfo.addFeature(DiscoInfo::JingleTransportsIBBFeature);
discoInfo.addFeature(DiscoInfo::JingleTransportsS5BFeature);
client->getDiscoManager()->setCapsNode(CLIENT_NODE);
client->getDiscoManager()->setDiscoInfo(discoInfo);
client->getPresenceSender()->sendPresence(Presence::create());
}
void handleIncomingFileTransfer(IncomingFileTransfer::ref transfer) {
SWIFT_LOG(debug) << "foo" << std::endl;
incomingFileTransfers.push_back(transfer);
std::shared_ptr<FileWriteBytestream> out = std::make_shared<FileWriteBytestream>("out");
transfer->onFinished.connect(boost::bind(&FileReceiver::handleFileTransferFinished, this, _1, out));
transfer->accept(out);
}
diff --git a/Swiften/FileTransfer/DefaultFileTransferTransporter.cpp b/Swiften/FileTransfer/DefaultFileTransferTransporter.cpp
index aefafd9..c6987c0 100644
--- a/Swiften/FileTransfer/DefaultFileTransferTransporter.cpp
+++ b/Swiften/FileTransfer/DefaultFileTransferTransporter.cpp
@@ -1,44 +1,43 @@
/*
* Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/FileTransfer/DefaultFileTransferTransporter.h>
#include <memory>
#include <boost/bind.hpp>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Crypto/CryptoProvider.h>
#include <Swiften/FileTransfer/FailingTransportSession.h>
#include <Swiften/FileTransfer/FileTransferOptions.h>
#include <Swiften/FileTransfer/IBBReceiveSession.h>
#include <Swiften/FileTransfer/IBBReceiveTransportSession.h>
#include <Swiften/FileTransfer/IBBSendSession.h>
#include <Swiften/FileTransfer/IBBSendTransportSession.h>
#include <Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.h>
#include <Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.h>
#include <Swiften/FileTransfer/S5BTransportSession.h>
#include <Swiften/FileTransfer/SOCKS5BytestreamProxiesManager.h>
#include <Swiften/FileTransfer/SOCKS5BytestreamRegistry.h>
#include <Swiften/FileTransfer/SOCKS5BytestreamServer.h>
#include <Swiften/FileTransfer/SOCKS5BytestreamServerManager.h>
#include <Swiften/FileTransfer/SOCKS5BytestreamServerSession.h>
#include <Swiften/FileTransfer/TransportSession.h>
#include <Swiften/Queries/GenericRequest.h>
#include <Swiften/StringCodecs/Hexify.h>
using namespace Swift;
DefaultFileTransferTransporter::DefaultFileTransferTransporter(
const JID& initiator,
const JID& responder,
Role role,
SOCKS5BytestreamRegistry* s5bRegistry,
SOCKS5BytestreamServerManager* s5bServerManager,
SOCKS5BytestreamProxiesManager* s5bProxy,
IDGenerator* idGenerator,
ConnectionFactory* connectionFactory,
@@ -268,42 +267,42 @@ std::string DefaultFileTransferTransporter::getSOCKS5DstAddr() const {
std::string DefaultFileTransferTransporter::getInitiatorCandidateSOCKS5DstAddr() const {
return Hexify::hexify(crypto->getSHA1Hash(createSafeByteArray(s5bSessionID + initiator.toString() + responder.toString())));
}
std::string DefaultFileTransferTransporter::getResponderCandidateSOCKS5DstAddr() const {
return Hexify::hexify(crypto->getSHA1Hash(createSafeByteArray(s5bSessionID + responder.toString() + initiator.toString())));
}
std::string DefaultFileTransferTransporter::getRemoteCandidateSOCKS5DstAddr() const {
if (role == Initiator) {
return getResponderCandidateSOCKS5DstAddr();
}
else {
return getInitiatorCandidateSOCKS5DstAddr();
}
}
std::string DefaultFileTransferTransporter::getLocalCandidateSOCKS5DstAddr() const {
if (role == Responder) {
return getResponderCandidateSOCKS5DstAddr();
}
else {
return getInitiatorCandidateSOCKS5DstAddr();
}
}
void DefaultFileTransferTransporter::closeLocalSession() {
s5bRegistry->setHasBytestream(getSOCKS5DstAddr(), false);
if (s5bServerManager->getServer()) {
std::vector<std::shared_ptr<SOCKS5BytestreamServerSession> > serverSessions = s5bServerManager->getServer()->getSessions(getSOCKS5DstAddr());
- foreach(std::shared_ptr<SOCKS5BytestreamServerSession> session, serverSessions) {
+ for (auto&& session : serverSessions) {
session->stop();
}
}
}
void DefaultFileTransferTransporter::closeRemoteSession() {
if (remoteS5BClientSession) {
remoteS5BClientSession->stop();
remoteS5BClientSession.reset();
}
}
diff --git a/Swiften/FileTransfer/IncomingJingleFileTransfer.cpp b/Swiften/FileTransfer/IncomingJingleFileTransfer.cpp
index f73cd38..d5de5e4 100644
--- a/Swiften/FileTransfer/IncomingJingleFileTransfer.cpp
+++ b/Swiften/FileTransfer/IncomingJingleFileTransfer.cpp
@@ -1,45 +1,44 @@
/*
* Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/FileTransfer/IncomingJingleFileTransfer.h>
#include <memory>
#include <set>
#include <boost/bind.hpp>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Elements/JingleFileTransferDescription.h>
#include <Swiften/Elements/JingleFileTransferHash.h>
#include <Swiften/Elements/JingleIBBTransportPayload.h>
#include <Swiften/Elements/JingleS5BTransportPayload.h>
#include <Swiften/FileTransfer/FileTransferOptions.h>
#include <Swiften/FileTransfer/FileTransferTransporter.h>
#include <Swiften/FileTransfer/FileTransferTransporterFactory.h>
#include <Swiften/FileTransfer/IncrementalBytestreamHashCalculator.h>
#include <Swiften/FileTransfer/TransportSession.h>
#include <Swiften/FileTransfer/WriteBytestream.h>
#include <Swiften/Jingle/JingleSession.h>
#include <Swiften/Network/TimerFactory.h>
#include <Swiften/Queries/GenericRequest.h>
#include <Swiften/StringCodecs/Base64.h>
using namespace Swift;
// TODO: ALlow terminate when already terminated.
IncomingJingleFileTransfer::IncomingJingleFileTransfer(
const JID& toJID,
JingleSession::ref session,
JingleContentPayload::ref content,
FileTransferTransporterFactory* transporterFactory,
TimerFactory* timerFactory,
CryptoProvider* crypto) :
JingleFileTransfer(session, toJID, transporterFactory),
initialContent(content),
crypto(crypto),
state(Initial),
@@ -103,61 +102,61 @@ void IncomingJingleFileTransfer::accept(
description->getFileInfo().getSize(),
stream));
session->sendAccept(getContentID(), initialContent->getDescriptions()[0], ibbTransport);
}
else {
// This might happen on incoming transfer which only list transport methods we are not allowed to use due to file-transfer options.
session->sendTerminate(JinglePayload::Reason::UnsupportedTransports);
setFinishedState(FileTransfer::State::Failed, FileTransferError(FileTransferError::PeerError));
}
}
void IncomingJingleFileTransfer::cancel() {
SWIFT_LOG(debug) << std::endl;
terminate(state == Initial ? JinglePayload::Reason::Decline : JinglePayload::Reason::Cancel);
}
void IncomingJingleFileTransfer::handleLocalTransportCandidatesGenerated(
const std::string& s5bSessionID,
const std::vector<JingleS5BTransportPayload::Candidate>& candidates,
const std::string& dstAddr) {
SWIFT_LOG(debug) << std::endl;
if (state != GeneratingInitialLocalCandidates) { SWIFT_LOG(warning) << "Incorrect state" << std::endl; return; }
fillCandidateMap(localCandidates, candidates);
JingleS5BTransportPayload::ref transport = std::make_shared<JingleS5BTransportPayload>();
transport->setSessionID(s5bSessionID);
transport->setMode(JingleS5BTransportPayload::TCPMode);
transport->setDstAddr(dstAddr);
- foreach(JingleS5BTransportPayload::Candidate candidate, candidates) {
+ for (auto&& candidate : candidates) {
transport->addCandidate(candidate);
}
session->sendAccept(getContentID(), initialContent->getDescriptions()[0], transport);
setState(TryingCandidates);
transporter->startTryingRemoteCandidates();
}
void IncomingJingleFileTransfer::handleSessionInfoReceived(JinglePayload::ref jinglePayload) {
SWIFT_LOG(debug) << std::endl;
JingleFileTransferHash::ref transferHash = jinglePayload->getPayload<JingleFileTransferHash>();
if (transferHash) {
SWIFT_LOG(debug) << "Received hash information." << std::endl;
waitOnHashTimer->stop();
if (transferHash->getFileInfo().getHashes().find("sha-1") != transferHash->getFileInfo().getHashes().end()) {
hashes["sha-1"] = transferHash->getFileInfo().getHash("sha-1").get();
}
if (transferHash->getFileInfo().getHashes().find("md5") != transferHash->getFileInfo().getHashes().end()) {
hashes["md5"] = transferHash->getFileInfo().getHash("md5").get();
}
if (state == WaitingForHash) {
checkHashAndTerminate();
}
}
else {
SWIFT_LOG(debug) << "Ignoring unknown session info" << std::endl;
}
}
@@ -170,61 +169,61 @@ void IncomingJingleFileTransfer::handleSessionTerminateReceived(boost::optional<
SWIFT_LOG(debug) << "Already terminated" << std::endl;
return;
}
stopAll();
if (reason && reason->type == JinglePayload::Reason::Cancel) {
setFinishedState(FileTransfer::State::Canceled, FileTransferError(FileTransferError::PeerError));
}
else if (reason && reason->type == JinglePayload::Reason::Success) {
setFinishedState(FileTransfer::State::Finished, boost::optional<FileTransferError>());
}
else {
setFinishedState(FileTransfer::State::Failed, FileTransferError(FileTransferError::PeerError));
}
}
void IncomingJingleFileTransfer::checkHashAndTerminate() {
if (verifyData()) {
terminate(JinglePayload::Reason::Success);
}
else {
SWIFT_LOG(warning) << "Hash verification failed" << std::endl;
terminate(JinglePayload::Reason::MediaError);
}
}
void IncomingJingleFileTransfer::checkIfAllDataReceived() {
if (receivedBytes == getFileSizeInBytes()) {
SWIFT_LOG(debug) << "All data received." << std::endl;
bool hashInfoAvailable = false;
- foreach(const JingleFileTransferFileInfo::HashElementMap::value_type& hashElement, hashes) {
+ for (const auto& hashElement : hashes) {
hashInfoAvailable |= !hashElement.second.empty();
}
if (!hashInfoAvailable) {
SWIFT_LOG(debug) << "No hash information yet. Waiting a while on hash info." << std::endl;
setState(WaitingForHash);
waitOnHashTimer->start();
}
else {
checkHashAndTerminate();
}
}
else if (receivedBytes > getFileSizeInBytes()) {
SWIFT_LOG(debug) << "We got more than we could handle!" << std::endl;
terminate(JinglePayload::Reason::MediaError);
}
}
void IncomingJingleFileTransfer::handleWriteStreamDataReceived(
const std::vector<unsigned char>& data) {
hashCalculator->feedData(data);
receivedBytes += data.size();
onProcessedBytes(data.size());
checkIfAllDataReceived();
}
void IncomingJingleFileTransfer::handleTransportReplaceReceived(
const JingleContentID& content, JingleTransportPayload::ref transport) {
SWIFT_LOG(debug) << std::endl;
if (state != WaitingForFallbackOrTerminate) {
diff --git a/Swiften/FileTransfer/JingleFileTransfer.cpp b/Swiften/FileTransfer/JingleFileTransfer.cpp
index 36725de..62c3a53 100644
--- a/Swiften/FileTransfer/JingleFileTransfer.cpp
+++ b/Swiften/FileTransfer/JingleFileTransfer.cpp
@@ -1,72 +1,71 @@
/*
* Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/FileTransfer/JingleFileTransfer.h>
#include <boost/typeof/typeof.hpp>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Crypto/CryptoProvider.h>
#include <Swiften/FileTransfer/FileTransferTransporter.h>
#include <Swiften/JID/JID.h>
#include <Swiften/Jingle/JingleSession.h>
#include <Swiften/StringCodecs/Hexify.h>
using namespace Swift;
JingleFileTransfer::JingleFileTransfer(
std::shared_ptr<JingleSession> session,
const JID& target,
FileTransferTransporterFactory* transporterFactory) :
session(session),
target(target),
transporterFactory(transporterFactory),
transporter(nullptr),
ourCandidateSelectFinished(false),
theirCandidateSelectFinished(false) {
session->addListener(this);
}
JingleFileTransfer::~JingleFileTransfer() {
session->removeListener(this);
}
void JingleFileTransfer::fillCandidateMap(CandidateMap& map, const std::vector<JingleS5BTransportPayload::Candidate>& candidates) {
map.clear();
- foreach (JingleS5BTransportPayload::Candidate candidate, candidates) {
+ for (auto&& candidate : candidates) {
map[candidate.cid] = candidate;
}
}
/*
std::string JingleFileTransfer::getS5BDstAddr(const JID& requester, const JID& target) const {
return Hexify::hexify(crypto->getSHA1Hash(
createSafeByteArray(s5bSessionID + requester.toString() + target.toString())));
}
*/
const JID& JingleFileTransfer::getInitiator() const {
return session->getInitiator();
}
const JID& JingleFileTransfer::getResponder() const {
return target;
}
FileTransfer::State::Type JingleFileTransfer::getExternalFinishedState(JinglePayload::Reason::Type reason) {
if (reason == JinglePayload::Reason::Cancel || reason == JinglePayload::Reason::Decline) {
return FileTransfer::State::Canceled;
}
else if (reason == JinglePayload::Reason::Success) {
return FileTransfer::State::Finished;
}
else {
return FileTransfer::State::Failed;
}
}
diff --git a/Swiften/FileTransfer/OutgoingJingleFileTransfer.cpp b/Swiften/FileTransfer/OutgoingJingleFileTransfer.cpp
index fcc160a..367fc97 100644
--- a/Swiften/FileTransfer/OutgoingJingleFileTransfer.cpp
+++ b/Swiften/FileTransfer/OutgoingJingleFileTransfer.cpp
@@ -1,57 +1,56 @@
/*
* Copyright (c) 2011 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.
*/
// TODO:
// - We should handle incoming terminates after we have terminated, so the other
// side can warn that he didn't receive all bytes correctly.
// - Should the proby stuff also wait for candidate used acknowledgement?
#include <Swiften/FileTransfer/OutgoingJingleFileTransfer.h>
#include <memory>
#include <boost/bind.hpp>
#include <boost/typeof/typeof.hpp>
#include <Swiften/Base/IDGenerator.h>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Crypto/CryptoProvider.h>
#include <Swiften/Elements/JingleFileTransferDescription.h>
#include <Swiften/Elements/JingleFileTransferHash.h>
#include <Swiften/Elements/JingleIBBTransportPayload.h>
#include <Swiften/Elements/JingleS5BTransportPayload.h>
#include <Swiften/Elements/JingleTransportPayload.h>
#include <Swiften/FileTransfer/FileTransferTransporter.h>
#include <Swiften/FileTransfer/FileTransferTransporterFactory.h>
#include <Swiften/FileTransfer/IncrementalBytestreamHashCalculator.h>
#include <Swiften/FileTransfer/ReadBytestream.h>
#include <Swiften/FileTransfer/TransportSession.h>
#include <Swiften/Jingle/JingleContentID.h>
#include <Swiften/Jingle/JingleSession.h>
#include <Swiften/Network/TimerFactory.h>
using namespace Swift;
static const int DEFAULT_BLOCK_SIZE = 4096;
OutgoingJingleFileTransfer::OutgoingJingleFileTransfer(
const JID& toJID,
JingleSession::ref session,
std::shared_ptr<ReadBytestream> stream,
FileTransferTransporterFactory* transporterFactory,
TimerFactory* timerFactory,
IDGenerator* idGenerator,
const JingleFileTransferFileInfo& fileInfo,
const FileTransferOptions& options,
CryptoProvider* crypto) :
JingleFileTransfer(session, toJID, transporterFactory),
@@ -188,61 +187,61 @@ void OutgoingJingleFileTransfer::sendSessionInfoHash() {
hashElement->getFileInfo().addHash(HashElement("sha-1", hashCalculator->getSHA1Hash()));
hashElement->getFileInfo().addHash(HashElement("md5", hashCalculator->getMD5Hash()));
session->sendInfo(hashElement);
}
void OutgoingJingleFileTransfer::handleLocalTransportCandidatesGenerated(
const std::string& s5bSessionID, const std::vector<JingleS5BTransportPayload::Candidate>& candidates, const std::string& dstAddr) {
SWIFT_LOG(debug) << std::endl;
if (state != GeneratingInitialLocalCandidates) { SWIFT_LOG(warning) << "Incorrect state: " << state << std::endl; return; }
fillCandidateMap(localCandidates, candidates);
JingleFileTransferDescription::ref description = std::make_shared<JingleFileTransferDescription>();
fileInfo.addHash(HashElement("sha-1", ByteArray()));
fileInfo.addHash(HashElement("md5", ByteArray()));
description->setFileInfo(fileInfo);
JingleTransportPayload::ref transport;
if (candidates.empty()) {
SWIFT_LOG(debug) << "no S5B candidates generated. Send IBB transport candidate." << std::endl;
JingleIBBTransportPayload::ref ibbTransport = std::make_shared<JingleIBBTransportPayload>();
ibbTransport->setBlockSize(DEFAULT_BLOCK_SIZE);
ibbTransport->setSessionID(idGenerator->generateID());
transport = ibbTransport;
}
else {
JingleS5BTransportPayload::ref s5bTransport = std::make_shared<JingleS5BTransportPayload>();
s5bTransport->setSessionID(s5bSessionID);
s5bTransport->setMode(JingleS5BTransportPayload::TCPMode);
s5bTransport->setDstAddr(dstAddr);
- foreach(JingleS5BTransportPayload::Candidate candidate, candidates) {
+ for (auto&& candidate : candidates) {
s5bTransport->addCandidate(candidate);
SWIFT_LOG(debug) << "\t" << "S5B candidate: " << candidate.hostPort.toString() << std::endl;
}
transport = s5bTransport;
}
setInternalState(WaitingForAccept);
session->sendInitiate(contentID, description, transport);
}
void OutgoingJingleFileTransfer::fallback() {
if (options.isInBandAllowed()) {
SWIFT_LOG(debug) << "Trying to fallback to IBB transport." << std::endl;
JingleIBBTransportPayload::ref ibbTransport = std::make_shared<JingleIBBTransportPayload>();
ibbTransport->setBlockSize(DEFAULT_BLOCK_SIZE);
ibbTransport->setSessionID(idGenerator->generateID());
setInternalState(FallbackRequested);
session->sendTransportReplace(contentID, ibbTransport);
}
else {
SWIFT_LOG(debug) << "Fallback to IBB transport not allowed." << std::endl;
terminate(JinglePayload::Reason::ConnectivityError);
}
}
void OutgoingJingleFileTransfer::handleTransferFinished(boost::optional<FileTransferError> error) {
SWIFT_LOG(debug) << std::endl;
if (state != Transferring) { SWIFT_LOG(warning) << "Incorrect state: " << state << std::endl; return; }
if (error) {
terminate(JinglePayload::Reason::ConnectivityError);
diff --git a/Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.cpp b/Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.cpp
index a0e7a6f..56013ca 100644
--- a/Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.cpp
+++ b/Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.cpp
@@ -1,72 +1,71 @@
/*
* Copyright (c) 2011 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 <Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.h>
#include <memory>
#include <boost/bind.hpp>
#include <boost/signals2.hpp>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Elements/JingleS5BTransportPayload.h>
#include <Swiften/FileTransfer/SOCKS5BytestreamRegistry.h>
#include <Swiften/Network/ConnectionFactory.h>
using namespace Swift;
RemoteJingleTransportCandidateSelector::RemoteJingleTransportCandidateSelector(
ConnectionFactory* connectionFactory,
TimerFactory* timerFactory,
const FileTransferOptions& options) :
connectionFactory(connectionFactory),
timerFactory(timerFactory),
options(options) {
}
RemoteJingleTransportCandidateSelector::~RemoteJingleTransportCandidateSelector() {
}
void RemoteJingleTransportCandidateSelector::addCandidates(
const std::vector<JingleS5BTransportPayload::Candidate>& candidates) {
- foreach(JingleS5BTransportPayload::Candidate c, candidates) {
+ for (auto&& c : candidates) {
this->candidates.push(c);
}
}
void RemoteJingleTransportCandidateSelector::startSelectingCandidate() {
tryNextCandidate();
}
void RemoteJingleTransportCandidateSelector::stopSelectingCandidate() {
if (s5bSession) {
sessionReadyConnection.disconnect();
s5bSession->stop();
}
}
void RemoteJingleTransportCandidateSelector::tryNextCandidate() {
if (candidates.empty()) {
SWIFT_LOG(debug) << "No more candidates" << std::endl;
onCandidateSelectFinished(
boost::optional<JingleS5BTransportPayload::Candidate>(), std::shared_ptr<SOCKS5BytestreamClientSession>());
}
else {
lastCandidate = candidates.top();
candidates.pop();
SWIFT_LOG(debug) << "Trying candidate " << lastCandidate.cid << std::endl;
if ((lastCandidate.type == JingleS5BTransportPayload::Candidate::DirectType && options.isDirectAllowed()) ||
(lastCandidate.type == JingleS5BTransportPayload::Candidate::AssistedType && options.isAssistedAllowed()) ||
(lastCandidate.type == JingleS5BTransportPayload::Candidate::ProxyType && options.isProxiedAllowed())) {
std::shared_ptr<Connection> connection = connectionFactory->createConnection();
s5bSession = std::make_shared<SOCKS5BytestreamClientSession>(
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamProxyFinder.cpp b/Swiften/FileTransfer/SOCKS5BytestreamProxyFinder.cpp
index 9624d4c..90c42dd 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamProxyFinder.cpp
+++ b/Swiften/FileTransfer/SOCKS5BytestreamProxyFinder.cpp
@@ -1,72 +1,70 @@
/*
* 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 <Swiften/FileTransfer/SOCKS5BytestreamProxyFinder.h>
#include <memory>
#include <boost/bind.hpp>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Elements/S5BProxyRequest.h>
#include <Swiften/Queries/GenericRequest.h>
#include <Swiften/Queries/IQRouter.h>
namespace Swift {
SOCKS5BytestreamProxyFinder::SOCKS5BytestreamProxyFinder(const JID& service, IQRouter *iqRouter) : service(service), iqRouter(iqRouter) {
}
SOCKS5BytestreamProxyFinder::~SOCKS5BytestreamProxyFinder() {
}
void SOCKS5BytestreamProxyFinder::start() {
serviceWalker = std::make_shared<DiscoServiceWalker>(service, iqRouter);
serviceWalker->onServiceFound.connect(boost::bind(&SOCKS5BytestreamProxyFinder::handleServiceFound, this, _1, _2));
serviceWalker->onWalkComplete.connect(boost::bind(&SOCKS5BytestreamProxyFinder::handleWalkEnded, this));
serviceWalker->beginWalk();
}
void SOCKS5BytestreamProxyFinder::stop() {
- typedef std::shared_ptr<GenericRequest<S5BProxyRequest> > S5BProxyRequestGenericRequest;
- foreach (S5BProxyRequestGenericRequest requester, pendingRequests) {
+ for (auto&& requester : pendingRequests) {
requester->onResponse.disconnect(boost::bind(&SOCKS5BytestreamProxyFinder::handleProxyResponse, this, requester, _1, _2));
}
serviceWalker->endWalk();
serviceWalker->onServiceFound.disconnect(boost::bind(&SOCKS5BytestreamProxyFinder::handleServiceFound, this, _1, _2));
serviceWalker->onWalkComplete.disconnect(boost::bind(&SOCKS5BytestreamProxyFinder::handleWalkEnded, this));
serviceWalker.reset();
}
void SOCKS5BytestreamProxyFinder::sendBytestreamQuery(const JID& jid) {
S5BProxyRequest::ref proxyRequest = std::make_shared<S5BProxyRequest>();
std::shared_ptr<GenericRequest<S5BProxyRequest> > request = std::make_shared<GenericRequest<S5BProxyRequest> >(IQ::Get, jid, proxyRequest, iqRouter);
request->onResponse.connect(boost::bind(&SOCKS5BytestreamProxyFinder::handleProxyResponse, this, request, _1, _2));
pendingRequests.insert(request);
request->send();
}
void SOCKS5BytestreamProxyFinder::handleServiceFound(const JID& jid, std::shared_ptr<DiscoInfo> discoInfo) {
if (discoInfo->hasFeature(DiscoInfo::Bytestream)) {
sendBytestreamQuery(jid);
}
}
void SOCKS5BytestreamProxyFinder::handleWalkEnded() {
if (pendingRequests.empty()) {
onProxiesFound(proxyHosts);
}
}
void SOCKS5BytestreamProxyFinder::handleProxyResponse(std::shared_ptr<GenericRequest<S5BProxyRequest> > requester, std::shared_ptr<S5BProxyRequest> request, ErrorPayload::ref error) {
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamRegistry.cpp b/Swiften/FileTransfer/SOCKS5BytestreamRegistry.cpp
index 1591e24..9e214fc 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamRegistry.cpp
+++ b/Swiften/FileTransfer/SOCKS5BytestreamRegistry.cpp
@@ -1,38 +1,37 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/FileTransfer/SOCKS5BytestreamRegistry.h>
#include <memory>
#include <Swiften/Base/Algorithm.h>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
namespace Swift {
SOCKS5BytestreamRegistry::SOCKS5BytestreamRegistry() {
}
void SOCKS5BytestreamRegistry::setHasBytestream(const std::string& destination, bool b) {
if (b) {
availableBytestreams.insert(destination);
}
else {
availableBytestreams.erase(destination);
}
}
bool SOCKS5BytestreamRegistry::hasBytestream(const std::string& destination) const {
return availableBytestreams.find(destination) != availableBytestreams.end();
}
std::string SOCKS5BytestreamRegistry::generateSessionID() {
return idGenerator.generateID();
}
}
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamServer.cpp b/Swiften/FileTransfer/SOCKS5BytestreamServer.cpp
index b68bd58..483ea18 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamServer.cpp
+++ b/Swiften/FileTransfer/SOCKS5BytestreamServer.cpp
@@ -1,69 +1,68 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/FileTransfer/SOCKS5BytestreamServer.h>
#include <boost/bind.hpp>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Crypto/CryptoProvider.h>
#include <Swiften/FileTransfer/SOCKS5BytestreamRegistry.h>
#include <Swiften/FileTransfer/SOCKS5BytestreamServerSession.h>
#include <Swiften/StringCodecs/Hexify.h>
namespace Swift {
SOCKS5BytestreamServer::SOCKS5BytestreamServer(
std::shared_ptr<ConnectionServer> connectionServer,
SOCKS5BytestreamRegistry* registry) :
connectionServer(connectionServer),
registry(registry) {
}
void SOCKS5BytestreamServer::start() {
connectionServer->onNewConnection.connect(boost::bind(&SOCKS5BytestreamServer::handleNewConnection, this, _1));
}
void SOCKS5BytestreamServer::stop() {
connectionServer->onNewConnection.disconnect(boost::bind(&SOCKS5BytestreamServer::handleNewConnection, this, _1));
- foreach (std::shared_ptr<SOCKS5BytestreamServerSession> session, sessions) {
+ for (auto&& session : sessions) {
session->onFinished.disconnect(boost::bind(&SOCKS5BytestreamServer::handleSessionFinished, this, session));
session->stop();
}
sessions.clear();
}
void SOCKS5BytestreamServer::handleNewConnection(std::shared_ptr<Connection> connection) {
std::shared_ptr<SOCKS5BytestreamServerSession> session =
std::make_shared<SOCKS5BytestreamServerSession>(connection, registry);
session->onFinished.connect(boost::bind(&SOCKS5BytestreamServer::handleSessionFinished, this, session));
sessions.push_back(session);
session->start();
}
HostAddressPort SOCKS5BytestreamServer::getAddressPort() const {
return connectionServer->getAddressPort();
}
std::vector< std::shared_ptr<SOCKS5BytestreamServerSession> > SOCKS5BytestreamServer::getSessions(
const std::string& streamID) const {
std::vector< std::shared_ptr<SOCKS5BytestreamServerSession> > result;
- foreach (std::shared_ptr<SOCKS5BytestreamServerSession> session, sessions) {
+ for (auto&& session : sessions) {
if (session->getStreamID() == streamID) {
result.push_back(session);
}
}
return result;
}
void SOCKS5BytestreamServer::handleSessionFinished(std::shared_ptr<SOCKS5BytestreamServerSession> session) {
sessions.erase(std::remove(sessions.begin(), sessions.end(), session), sessions.end());
session->onFinished.disconnect(boost::bind(&SOCKS5BytestreamServer::handleSessionFinished, this, session));
}
}
diff --git a/Swiften/Jingle/JingleSession.cpp b/Swiften/Jingle/JingleSession.cpp
index 778ee1d..b5cfbef 100644
--- a/Swiften/Jingle/JingleSession.cpp
+++ b/Swiften/Jingle/JingleSession.cpp
@@ -1,25 +1,24 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Jingle/JingleSession.h>
#include <algorithm>
+#include <cassert>
#include <memory>
#include <boost/function.hpp>
-#include <Swiften/Base/foreach.h>
-
using namespace Swift;
JingleSession::JingleSession(const JID& initiator, const std::string& id) : initiator(initiator), id(id) {
// initiator must always be a full JID; session lookup based on it wouldn't work otherwise
// this is checked on an upper level so that the assert never fails
assert(!initiator.isBare());
}
JingleSession::~JingleSession() {
}
diff --git a/Swiften/Jingle/JingleSessionManager.cpp b/Swiften/Jingle/JingleSessionManager.cpp
index ca6cebb..f7ed58e 100644
--- a/Swiften/Jingle/JingleSessionManager.cpp
+++ b/Swiften/Jingle/JingleSessionManager.cpp
@@ -1,56 +1,55 @@
/*
* Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Jingle/JingleSessionManager.h>
#include <Swiften/Base/Algorithm.h>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Jingle/IncomingJingleSessionHandler.h>
#include <Swiften/Jingle/JingleResponder.h>
namespace Swift {
JingleSessionManager::JingleSessionManager(IQRouter* router) : router(router) {
responder = new JingleResponder(this, router);
responder->start();
}
JingleSessionManager::~JingleSessionManager() {
responder->stop();
delete responder;
}
JingleSessionImpl::ref JingleSessionManager::getSession(const JID& jid, const std::string& id) const {
SessionMap::const_iterator i = sessions.find(JIDSession(jid, id));
return i != sessions.end() ? i->second : JingleSessionImpl::ref();
}
void JingleSessionManager::addIncomingSessionHandler(IncomingJingleSessionHandler* handler) {
incomingSessionHandlers.push_back(handler);
}
void JingleSessionManager::removeIncomingSessionHandler(IncomingJingleSessionHandler* handler) {
erase(incomingSessionHandlers, handler);
}
void JingleSessionManager::registerOutgoingSession(const JID& initiator, JingleSessionImpl::ref session) {
sessions.insert(std::make_pair(JIDSession(initiator, session->getID()), session));
SWIFT_LOG(debug) << "Added session " << session->getID() << " for initiator " << initiator.toString() << std::endl;
}
void JingleSessionManager::handleIncomingSession(const JID& initiator, const JID& recipient, JingleSessionImpl::ref session, const std::vector<JingleContentPayload::ref>& contents) {
sessions.insert(std::make_pair(JIDSession(initiator, session->getID()), session));
- foreach (IncomingJingleSessionHandler* handler, incomingSessionHandlers) {
+ for (auto handler : incomingSessionHandlers) {
if (handler->handleIncomingJingleSession(session, contents, recipient)) {
return;
}
}
// TODO: Finish session
}
}
diff --git a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuerier.cpp b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuerier.cpp
index 9cfe3cd..0906ffc 100644
--- a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuerier.cpp
+++ b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuerier.cpp
@@ -1,44 +1,43 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuerier.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <unistd.h>
#include <Swiften/Base/Algorithm.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/LinkLocal/DNSSD/Bonjour/BonjourBrowseQuery.h>
#include <Swiften/LinkLocal/DNSSD/Bonjour/BonjourRegisterQuery.h>
#include <Swiften/LinkLocal/DNSSD/Bonjour/BonjourResolveHostnameQuery.h>
#include <Swiften/LinkLocal/DNSSD/Bonjour/BonjourResolveServiceQuery.h>
namespace Swift {
BonjourQuerier::BonjourQuerier(EventLoop* eventLoop) : eventLoop(eventLoop), stopRequested(false), thread(nullptr) {
int fds[2];
int result = pipe(fds);
assert(result == 0);
(void) result;
interruptSelectReadSocket = fds[0];
fcntl(interruptSelectReadSocket, F_SETFL, fcntl(interruptSelectReadSocket, F_GETFL)|O_NONBLOCK);
interruptSelectWriteSocket = fds[1];
}
BonjourQuerier::~BonjourQuerier() {
assert(!thread);
}
std::shared_ptr<DNSSDBrowseQuery> BonjourQuerier::createBrowseQuery() {
return std::make_shared<BonjourBrowseQuery>(shared_from_this(), eventLoop);
}
std::shared_ptr<DNSSDRegisterQuery> BonjourQuerier::createRegisterQuery(const std::string& name, int port, const ByteArray& info) {
return std::make_shared<BonjourRegisterQuery>(name, port, info, shared_from_this(), eventLoop);
}
std::shared_ptr<DNSSDResolveServiceQuery> BonjourQuerier::createResolveServiceQuery(const DNSSDServiceID& service) {
@@ -79,58 +78,58 @@ void BonjourQuerier::stop() {
if (thread) {
stopRequested = true;
assert(runningQueries.empty());
runningQueriesAvailableEvent.notify_one();
interruptSelect();
thread->join();
delete thread;
thread = nullptr;
stopRequested = false;
}
}
void BonjourQuerier::run() {
while (!stopRequested) {
fd_set fdSet;
int maxSocket;
{
std::unique_lock<std::mutex> lock(runningQueriesMutex);
if (runningQueries.empty()) {
runningQueriesAvailableEvent.wait(lock);
if (runningQueries.empty()) {
continue;
}
}
// Run all running queries
FD_ZERO(&fdSet);
maxSocket = interruptSelectReadSocket;
FD_SET(interruptSelectReadSocket, &fdSet);
- foreach(const std::shared_ptr<BonjourQuery>& query, runningQueries) {
+ for (const auto& query : runningQueries) {
int socketID = query->getSocketID();
maxSocket = std::max(maxSocket, socketID);
FD_SET(socketID, &fdSet);
}
}
if (select(maxSocket+1, &fdSet, nullptr, nullptr, nullptr) <= 0) {
continue;
}
if (FD_ISSET(interruptSelectReadSocket, &fdSet)) {
char dummy;
while (read(interruptSelectReadSocket, &dummy, 1) > 0) {}
}
{
std::lock_guard<std::mutex> lock(runningQueriesMutex);
- foreach(std::shared_ptr<BonjourQuery> query, runningQueries) {
+ for (auto&& query : runningQueries) {
if (FD_ISSET(query->getSocketID(), &fdSet)) {
query->processResult();
}
}
}
}
}
}
diff --git a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.cpp b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.cpp
index 63ad3b8..c17f8b2 100644
--- a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.cpp
+++ b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.cpp
@@ -1,140 +1,139 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.h>
#include <iostream>
#include <boost/bind.hpp>
#include <Swiften/Base/Algorithm.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/EventLoop/EventLoop.h>
#include <Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDBrowseQuery.h>
#include <Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDRegisterQuery.h>
#include <Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDResolveHostnameQuery.h>
#include <Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDResolveServiceQuery.h>
namespace Swift {
FakeDNSSDQuerier::FakeDNSSDQuerier(const std::string& domain, EventLoop* eventLoop) : domain(domain), eventLoop(eventLoop) {
}
FakeDNSSDQuerier::~FakeDNSSDQuerier() {
if (!runningQueries.empty()) {
std::cerr << "FakeDNSSDQuerier: Running queries not empty at destruction time" << std::endl;
}
}
std::shared_ptr<DNSSDBrowseQuery> FakeDNSSDQuerier::createBrowseQuery() {
return std::make_shared<FakeDNSSDBrowseQuery>(shared_from_this());
}
std::shared_ptr<DNSSDRegisterQuery> FakeDNSSDQuerier::createRegisterQuery(const std::string& name, int port, const ByteArray& info) {
return std::make_shared<FakeDNSSDRegisterQuery>(name, port, info, shared_from_this());
}
std::shared_ptr<DNSSDResolveServiceQuery> FakeDNSSDQuerier::createResolveServiceQuery(const DNSSDServiceID& service) {
return std::make_shared<FakeDNSSDResolveServiceQuery>(service, shared_from_this());
}
std::shared_ptr<DNSSDResolveHostnameQuery> FakeDNSSDQuerier::createResolveHostnameQuery(const std::string& hostname, int interfaceIndex) {
return std::make_shared<FakeDNSSDResolveHostnameQuery>(hostname, interfaceIndex, shared_from_this());
}
void FakeDNSSDQuerier::addRunningQuery(std::shared_ptr<FakeDNSSDQuery> query) {
runningQueries.push_back(query);
allQueriesEverRun.push_back(query);
if (std::shared_ptr<FakeDNSSDBrowseQuery> browseQuery = std::dynamic_pointer_cast<FakeDNSSDBrowseQuery>(query)) {
- foreach(const DNSSDServiceID& service, services) {
+ for (const auto& service : services) {
eventLoop->postEvent(boost::bind(boost::ref(browseQuery->onServiceAdded), service), shared_from_this());
}
}
else if (std::shared_ptr<FakeDNSSDResolveServiceQuery> resolveQuery = std::dynamic_pointer_cast<FakeDNSSDResolveServiceQuery>(query)) {
- for(ServiceInfoMap::const_iterator i = serviceInfo.begin(); i != serviceInfo.end(); ++i) {
- if (i->first == resolveQuery->service) {
- eventLoop->postEvent(boost::bind(boost::ref(resolveQuery->onServiceResolved), i->second), shared_from_this());
+ for (const auto& i : serviceInfo) {
+ if (i.first == resolveQuery->service) {
+ eventLoop->postEvent(boost::bind(boost::ref(resolveQuery->onServiceResolved), i.second), shared_from_this());
}
}
}
else if (std::shared_ptr<FakeDNSSDRegisterQuery> registerQuery = std::dynamic_pointer_cast<FakeDNSSDRegisterQuery>(query)) {
DNSSDServiceID service(registerQuery->name, domain);
eventLoop->postEvent(boost::bind(boost::ref(registerQuery->onRegisterFinished), service), shared_from_this());
}
else if (std::shared_ptr<FakeDNSSDResolveHostnameQuery> resolveHostnameQuery = std::dynamic_pointer_cast<FakeDNSSDResolveHostnameQuery>(query)) {
std::map<std::string,boost::optional<HostAddress> >::const_iterator i = addresses.find(resolveHostnameQuery->hostname);
if (i != addresses.end()) {
eventLoop->postEvent(
boost::bind(
boost::ref(resolveHostnameQuery->onHostnameResolved), i->second),
shared_from_this());
}
}
}
void FakeDNSSDQuerier::removeRunningQuery(std::shared_ptr<FakeDNSSDQuery> query) {
erase(runningQueries, query);
}
void FakeDNSSDQuerier::addService(const DNSSDServiceID& id) {
services.insert(id);
- foreach(const std::shared_ptr<FakeDNSSDBrowseQuery>& query, getQueries<FakeDNSSDBrowseQuery>()) {
+ for (const auto& query : getQueries<FakeDNSSDBrowseQuery>()) {
eventLoop->postEvent(boost::bind(boost::ref(query->onServiceAdded), id), shared_from_this());
}
}
void FakeDNSSDQuerier::removeService(const DNSSDServiceID& id) {
services.erase(id);
serviceInfo.erase(id);
- foreach(const std::shared_ptr<FakeDNSSDBrowseQuery>& query, getQueries<FakeDNSSDBrowseQuery>()) {
+ for (const auto& query : getQueries<FakeDNSSDBrowseQuery>()) {
eventLoop->postEvent(boost::bind(boost::ref(query->onServiceRemoved), id), shared_from_this());
}
}
void FakeDNSSDQuerier::setServiceInfo(const DNSSDServiceID& id, const DNSSDResolveServiceQuery::Result& info) {
std::pair<ServiceInfoMap::iterator, bool> r = serviceInfo.insert(std::make_pair(id, info));
if (!r.second) {
r.first->second = info;
}
- foreach(const std::shared_ptr<FakeDNSSDResolveServiceQuery>& query, getQueries<FakeDNSSDResolveServiceQuery>()) {
+ for (const auto& query : getQueries<FakeDNSSDResolveServiceQuery>()) {
if (query->service == id) {
eventLoop->postEvent(boost::bind(boost::ref(query->onServiceResolved), info), shared_from_this());
}
}
}
bool FakeDNSSDQuerier::isServiceRegistered(const std::string& name, int port, const ByteArray& info) {
- foreach(const std::shared_ptr<FakeDNSSDRegisterQuery>& query, getQueries<FakeDNSSDRegisterQuery>()) {
+ for (const auto& query : getQueries<FakeDNSSDRegisterQuery>()) {
if (query->name == name && query->port == port && query->info == info) {
return true;
}
}
return false;
}
void FakeDNSSDQuerier::setBrowseError() {
- foreach(const std::shared_ptr<FakeDNSSDBrowseQuery>& query, getQueries<FakeDNSSDBrowseQuery>()) {
+ for (const auto& query : getQueries<FakeDNSSDBrowseQuery>()) {
eventLoop->postEvent(boost::ref(query->onError), shared_from_this());
}
}
void FakeDNSSDQuerier::setRegisterError() {
- foreach(const std::shared_ptr<FakeDNSSDRegisterQuery>& query, getQueries<FakeDNSSDRegisterQuery>()) {
+ for (const auto& query : getQueries<FakeDNSSDRegisterQuery>()) {
eventLoop->postEvent(boost::bind(boost::ref(query->onRegisterFinished), boost::optional<DNSSDServiceID>()), shared_from_this());
}
}
void FakeDNSSDQuerier::setAddress(const std::string& hostname, boost::optional<HostAddress> address) {
addresses[hostname] = address;
- foreach(const std::shared_ptr<FakeDNSSDResolveHostnameQuery>& query, getQueries<FakeDNSSDResolveHostnameQuery>()) {
+ for (const auto& query : getQueries<FakeDNSSDResolveHostnameQuery>()) {
if (query->hostname == hostname) {
eventLoop->postEvent(boost::bind(
boost::ref(query->onHostnameResolved), address), shared_from_this());
}
}
}
}
diff --git a/Swiften/LinkLocal/OutgoingLinkLocalSession.cpp b/Swiften/LinkLocal/OutgoingLinkLocalSession.cpp
index f97d9a1..a639ec5 100644
--- a/Swiften/LinkLocal/OutgoingLinkLocalSession.cpp
+++ b/Swiften/LinkLocal/OutgoingLinkLocalSession.cpp
@@ -1,53 +1,52 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/LinkLocal/OutgoingLinkLocalSession.h>
#include <boost/bind.hpp>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Elements/IQ.h>
#include <Swiften/Elements/ProtocolHeader.h>
#include <Swiften/Elements/StreamFeatures.h>
#include <Swiften/StreamStack/XMPPLayer.h>
namespace Swift {
OutgoingLinkLocalSession::OutgoingLinkLocalSession(
const JID& localJID,
const JID& remoteJID,
std::shared_ptr<Connection> connection,
PayloadParserFactoryCollection* payloadParserFactories,
PayloadSerializerCollection* payloadSerializers,
XMLParserFactory* xmlParserFactory) :
Session(connection, payloadParserFactories, payloadSerializers, xmlParserFactory) {
setLocalJID(localJID);
setRemoteJID(remoteJID);
}
void OutgoingLinkLocalSession::handleSessionStarted() {
ProtocolHeader header;
header.setFrom(getLocalJID());
getXMPPLayer()->writeHeader(header);
}
void OutgoingLinkLocalSession::handleStreamStart(const ProtocolHeader&) {
- foreach(const std::shared_ptr<ToplevelElement>& stanza, queuedElements_) {
+ for (const auto& stanza : queuedElements_) {
sendElement(stanza);
}
queuedElements_.clear();
}
void OutgoingLinkLocalSession::handleElement(std::shared_ptr<ToplevelElement> element) {
onElementReceived(element);
}
void OutgoingLinkLocalSession::queueElement(std::shared_ptr<ToplevelElement> element) {
queuedElements_.push_back(element);
}
}
diff --git a/Swiften/MUC/MUCBookmarkManager.cpp b/Swiften/MUC/MUCBookmarkManager.cpp
index a06a0a2..9f8ae77 100644
--- a/Swiften/MUC/MUCBookmarkManager.cpp
+++ b/Swiften/MUC/MUCBookmarkManager.cpp
@@ -1,120 +1,119 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/MUC/MUCBookmarkManager.h>
#include <memory>
#include <boost/bind.hpp>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Queries/IQRouter.h>
#include <Swiften/Queries/Requests/GetPrivateStorageRequest.h>
#include <Swiften/Queries/Requests/SetPrivateStorageRequest.h>
namespace Swift {
MUCBookmarkManager::MUCBookmarkManager(IQRouter* iqRouter) {
iqRouter_ = iqRouter;
ready_ = false;
GetPrivateStorageRequest<Storage>::ref request = GetPrivateStorageRequest<Storage>::create(iqRouter_);
request->onResponse.connect(boost::bind(&MUCBookmarkManager::handleBookmarksReceived, this, _1, _2));
request->send();
}
void MUCBookmarkManager::handleBookmarksReceived(std::shared_ptr<Storage> payload, ErrorPayload::ref error) {
if (error) {
return;
}
ready_ = true;
onBookmarksReady();
storage = payload;
std::vector<MUCBookmark> receivedBookmarks;
- foreach (Storage::Room room, payload->getRooms()) {
+ for (const auto& room : payload->getRooms()) {
receivedBookmarks.push_back(MUCBookmark(room));
}
std::vector<MUCBookmark> newBookmarks;
- foreach (const MUCBookmark& oldBookmark, bookmarks_) {
+ for (const auto& oldBookmark : bookmarks_) {
if (containsEquivalent(receivedBookmarks, oldBookmark)) {
newBookmarks.push_back(oldBookmark);
} else {
onBookmarkRemoved(oldBookmark);
}
}
- foreach (const MUCBookmark& newBookmark, receivedBookmarks) {
+ for (const auto& newBookmark : receivedBookmarks) {
if (!containsEquivalent(bookmarks_, newBookmark)) {
newBookmarks.push_back(newBookmark);
onBookmarkAdded(newBookmark);
}
}
bookmarks_ = newBookmarks;
}
bool MUCBookmarkManager::containsEquivalent(const std::vector<MUCBookmark>& list, const MUCBookmark& bookmark) {
return std::find(list.begin(), list.end(), bookmark) != list.end();
}
void MUCBookmarkManager::replaceBookmark(const MUCBookmark& oldBookmark, const MUCBookmark& newBookmark) {
if (!ready_) return;
for (auto& bookmark : bookmarks_) {
if (bookmark == oldBookmark) {
bookmark = newBookmark;
flush();
onBookmarkRemoved(oldBookmark);
onBookmarkAdded(newBookmark);
return;
}
}
}
void MUCBookmarkManager::addBookmark(const MUCBookmark& bookmark) {
if (!ready_) return;
bookmarks_.push_back(bookmark);
onBookmarkAdded(bookmark);
flush();
}
void MUCBookmarkManager::removeBookmark(const MUCBookmark& bookmark) {
if (!ready_) return;
std::vector<MUCBookmark>::iterator it;
for (it = bookmarks_.begin(); it != bookmarks_.end(); ++it) {
if ((*it) == bookmark) {
bookmarks_.erase(it);
onBookmarkRemoved(bookmark);
break;
}
}
flush();
}
void MUCBookmarkManager::flush() {
if (!storage) {
storage = std::make_shared<Storage>();
}
// Update the storage element
storage->clearRooms();
- foreach(const MUCBookmark& bookmark, bookmarks_) {
+ for (const auto& bookmark : bookmarks_) {
storage->addRoom(bookmark.toStorage());
}
// Send an iq to save the storage element
SetPrivateStorageRequest<Storage>::ref request = SetPrivateStorageRequest<Storage>::create(storage, iqRouter_);
// FIXME: We should care about the result
//request->onResponse.connect(boost::bind(&MUCBookmarkManager::handleBookmarksSet, this, _1, _2));
request->send();
}
const std::vector<MUCBookmark>& MUCBookmarkManager::getBookmarks() const {
return bookmarks_;
}
}
diff --git a/Swiften/Network/BOSHConnectionPool.cpp b/Swiften/Network/BOSHConnectionPool.cpp
index 9ce40d3..e4ca471 100644
--- a/Swiften/Network/BOSHConnectionPool.cpp
+++ b/Swiften/Network/BOSHConnectionPool.cpp
@@ -1,79 +1,78 @@
/*
* Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Network/BOSHConnectionPool.h>
#include <climits>
#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
#include <Swiften/Base/Log.h>
#include <Swiften/Base/SafeString.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Network/CachingDomainNameResolver.h>
#include <Swiften/Network/HTTPConnectProxiedConnectionFactory.h>
namespace Swift {
BOSHConnectionPool::BOSHConnectionPool(const URL& boshURL, DomainNameResolver* realResolver, ConnectionFactory* connectionFactoryParameter, XMLParserFactory* parserFactory, TLSContextFactory* tlsFactory, TimerFactory* timerFactory, EventLoop* eventLoop, const std::string& to, unsigned long long initialRID, const URL& boshHTTPConnectProxyURL, const SafeString& boshHTTPConnectProxyAuthID, const SafeString& boshHTTPConnectProxyAuthPassword, const TLSOptions& tlsOptions, std::shared_ptr<HTTPTrafficFilter> trafficFilter) :
boshURL(boshURL),
connectionFactory(connectionFactoryParameter),
xmlParserFactory(parserFactory),
timerFactory(timerFactory),
rid(initialRID),
pendingTerminate(false),
to(to),
requestLimit(2),
restartCount(0),
pendingRestart(false),
tlsContextFactory_(tlsFactory),
tlsOptions_(tlsOptions) {
if (!boshHTTPConnectProxyURL.isEmpty()) {
connectionFactory = new HTTPConnectProxiedConnectionFactory(realResolver, connectionFactory, timerFactory, boshHTTPConnectProxyURL.getHost(), URL::getPortOrDefaultPort(boshHTTPConnectProxyURL), boshHTTPConnectProxyAuthID, boshHTTPConnectProxyAuthPassword, trafficFilter);
}
resolver = new CachingDomainNameResolver(realResolver, eventLoop);
}
BOSHConnectionPool::~BOSHConnectionPool() {
/* Don't do a normal close here. Instead kill things forcibly, as close() or writeFooter() will already have been called */
std::vector<BOSHConnection::ref> connectionCopies = connections;
- foreach (BOSHConnection::ref connection, connectionCopies) {
+ for (auto&& connection : connectionCopies) {
if (connection) {
destroyConnection(connection);
connection->disconnect();
}
}
- foreach (ConnectionFactory* factory, myConnectionFactories) {
+ for (auto factory : myConnectionFactories) {
delete factory;
}
delete resolver;
}
void BOSHConnectionPool::write(const SafeByteArray& data) {
dataQueue.push_back(data);
tryToSendQueuedData();
}
void BOSHConnectionPool::handleDataRead(const SafeByteArray& data) {
onXMPPDataRead(data);
tryToSendQueuedData(); /* Will rebalance the connections */
}
void BOSHConnectionPool::restartStream() {
BOSHConnection::ref connection = getSuitableConnection();
if (connection) {
pendingRestart = false;
rid++;
connection->setRID(rid);
connection->restartStream();
restartCount++;
}
else {
pendingRestart = true;
}
}
void BOSHConnectionPool::setTLSCertificate(CertificateWithKey::ref certWithKey) {
@@ -89,149 +88,149 @@ Certificate::ref BOSHConnectionPool::getPeerCertificate() const {
if (!pinnedCertificateChain_.empty()) {
peerCertificate = pinnedCertificateChain_[0];
}
return peerCertificate;
}
std::vector<Certificate::ref> BOSHConnectionPool::getPeerCertificateChain() const {
return pinnedCertificateChain_;
}
std::shared_ptr<CertificateVerificationError> BOSHConnectionPool::getPeerCertificateVerificationError() const {
return lastVerificationError_;
}
void BOSHConnectionPool::writeFooter() {
pendingTerminate = true;
tryToSendQueuedData();
}
void BOSHConnectionPool::open() {
createConnection();
}
void BOSHConnectionPool::close() {
if (!sid.empty()) {
writeFooter();
}
else {
pendingTerminate = true;
std::vector<BOSHConnection::ref> connectionCopies = connections;
- foreach (BOSHConnection::ref connection, connectionCopies) {
+ for (auto&& connection : connectionCopies) {
if (connection) {
connection->disconnect();
}
}
}
}
void BOSHConnectionPool::handleSessionStarted(const std::string& sessionID, size_t requests) {
sid = sessionID;
requestLimit = requests;
onSessionStarted();
}
void BOSHConnectionPool::handleConnectFinished(bool error, BOSHConnection::ref connection) {
if (error) {
onSessionTerminated(std::make_shared<BOSHError>(BOSHError::UndefinedCondition));
/*TODO: We can probably manage to not terminate the stream here and use the rid/ack retry
* logic to just swallow the error and try again (some number of tries).
*/
}
else {
if (connection->getPeerCertificate() && pinnedCertificateChain_.empty()) {
pinnedCertificateChain_ = connection->getPeerCertificateChain();
}
if (!pinnedCertificateChain_.empty()) {
lastVerificationError_ = connection->getPeerCertificateVerificationError();
}
if (sid.empty()) {
connection->startStream(to, rid);
}
if (pendingRestart) {
restartStream();
}
tryToSendQueuedData();
}
}
BOSHConnection::ref BOSHConnectionPool::getSuitableConnection() {
BOSHConnection::ref suitableConnection;
- foreach (BOSHConnection::ref connection, connections) {
+ for (auto&& connection : connections) {
if (connection->isReadyToSend()) {
suitableConnection = connection;
break;
}
}
if (!suitableConnection && connections.size() < requestLimit) {
/* This is not a suitable connection because it won't have yet connected and added TLS if needed. */
BOSHConnection::ref newConnection = createConnection();
newConnection->setSID(sid);
}
assert(connections.size() <= requestLimit);
assert((!suitableConnection) || suitableConnection->isReadyToSend());
return suitableConnection;
}
void BOSHConnectionPool::tryToSendQueuedData() {
if (sid.empty()) {
/* If we've not got as far as stream start yet, pend */
return;
}
BOSHConnection::ref suitableConnection = getSuitableConnection();
bool toSend = !dataQueue.empty();
if (suitableConnection) {
if (toSend) {
rid++;
suitableConnection->setRID(rid);
SafeByteArray data;
- foreach (const SafeByteArray& datum, dataQueue) {
+ for (const auto& datum : dataQueue) {
data.insert(data.end(), datum.begin(), datum.end());
}
suitableConnection->write(data);
dataQueue.clear();
}
else if (pendingTerminate) {
rid++;
suitableConnection->setRID(rid);
suitableConnection->terminateStream();
sid = "";
close();
}
}
if (!pendingTerminate) {
/* Ensure there's always a session waiting to read data for us */
bool pending = false;
- foreach (BOSHConnection::ref connection, connections) {
+ for (auto&& connection : connections) {
if (connection && !connection->isReadyToSend()) {
pending = true;
}
}
if (!pending) {
if (restartCount >= 1) {
/* Don't open a second connection until we've restarted the stream twice - i.e. we've authed and resource bound.*/
if (suitableConnection) {
rid++;
suitableConnection->setRID(rid);
suitableConnection->write(createSafeByteArray(""));
}
else {
/* My thought process I went through when writing this, to aid anyone else confused why this can happen...
*
* What to do here? I think this isn't possible.
If you didn't have two connections, suitable would have made one.
If you have two connections and neither is suitable, pending would be true.
If you have a non-pending connection, it's suitable.
If I decide to do something here, remove assert above.
Ah! Yes, because there's a period between creating the connection and it being connected. */
}
}
}
}
}
void BOSHConnectionPool::handleHTTPError(const std::string& /*errorCode*/) {
diff --git a/Swiften/Network/ChainedConnector.cpp b/Swiften/Network/ChainedConnector.cpp
index fbea868..ea55db3 100644
--- a/Swiften/Network/ChainedConnector.cpp
+++ b/Swiften/Network/ChainedConnector.cpp
@@ -1,44 +1,43 @@
/*
* Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Network/ChainedConnector.h>
#include <typeinfo>
#include <boost/bind.hpp>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Network/ConnectionFactory.h>
#include <Swiften/Network/Connector.h>
using namespace Swift;
ChainedConnector::ChainedConnector(
const std::string& hostname,
int port,
const boost::optional<std::string>& serviceLookupPrefix,
DomainNameResolver* resolver,
const std::vector<ConnectionFactory*>& connectionFactories,
TimerFactory* timerFactory) :
hostname(hostname),
port(port),
serviceLookupPrefix(serviceLookupPrefix),
resolver(resolver),
connectionFactories(connectionFactories),
timerFactory(timerFactory),
timeoutMilliseconds(0) {
}
ChainedConnector::~ChainedConnector() {
if (currentConnector) {
currentConnector->onConnectFinished.disconnect(boost::bind(&ChainedConnector::handleConnectorFinished, this, _1, _2));
currentConnector->stop();
currentConnector.reset();
}
}
void ChainedConnector::setTimeoutMilliseconds(int milliseconds) {
diff --git a/Swiften/Network/DummyTimerFactory.cpp b/Swiften/Network/DummyTimerFactory.cpp
index cdc776c..0bad7be 100644
--- a/Swiften/Network/DummyTimerFactory.cpp
+++ b/Swiften/Network/DummyTimerFactory.cpp
@@ -1,60 +1,59 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Network/DummyTimerFactory.h>
#include <algorithm>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Network/Timer.h>
namespace Swift {
class DummyTimerFactory::DummyTimer : public Timer {
public:
DummyTimer(int timeout, DummyTimerFactory* factory) : timeout(timeout), factory(factory), isRunning(false), startTime(~0) {
}
virtual void start() {
isRunning = true;
startTime = factory->currentTime;
}
virtual void stop() {
isRunning = false;
}
int getAlarmTime() const {
return startTime + timeout;
}
int timeout;
DummyTimerFactory* factory;
bool isRunning;
int startTime;
};
DummyTimerFactory::DummyTimerFactory() : currentTime(0) {
}
std::shared_ptr<Timer> DummyTimerFactory::createTimer(int milliseconds) {
std::shared_ptr<DummyTimer> timer(new DummyTimer(milliseconds, this));
timers.push_back(timer);
return timer;
}
void DummyTimerFactory::setTime(int time) {
assert(time > currentTime);
- foreach(std::shared_ptr<DummyTimer> timer, timers) {
+ for (auto&& timer : timers) {
if (timer->getAlarmTime() > currentTime && timer->getAlarmTime() <= time && timer->isRunning) {
timer->onTick();
}
}
currentTime = time;
}
}
diff --git a/Swiften/Network/HTTPConnectProxiedConnection.cpp b/Swiften/Network/HTTPConnectProxiedConnection.cpp
index b9ab604..b5e521b 100644
--- a/Swiften/Network/HTTPConnectProxiedConnection.cpp
+++ b/Swiften/Network/HTTPConnectProxiedConnection.cpp
@@ -1,138 +1,135 @@
/*
* Copyright (c) 2010-2011 Thilo Cestonaro
* Licensed under the simplified BSD license.
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
/*
* Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Network/HTTPConnectProxiedConnection.h>
#include <iostream>
#include <utility>
#include <boost/algorithm/string.hpp>
#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
#include <Swiften/Base/Algorithm.h>
#include <Swiften/Base/ByteArray.h>
#include <Swiften/Base/Log.h>
#include <Swiften/Base/String.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Network/ConnectionFactory.h>
#include <Swiften/Network/HTTPTrafficFilter.h>
#include <Swiften/Network/HostAddressPort.h>
#include <Swiften/StringCodecs/Base64.h>
using namespace Swift;
HTTPConnectProxiedConnection::HTTPConnectProxiedConnection(
DomainNameResolver* resolver,
ConnectionFactory* connectionFactory,
TimerFactory* timerFactory,
const std::string& proxyHost,
int proxyPort,
const SafeString& authID,
const SafeString& authPassword) :
ProxiedConnection(resolver, connectionFactory, timerFactory, proxyHost, proxyPort),
authID_(authID),
authPassword_(authPassword) {
}
HTTPConnectProxiedConnection::~HTTPConnectProxiedConnection() {
}
void HTTPConnectProxiedConnection::setHTTPTrafficFilter(std::shared_ptr<HTTPTrafficFilter> trafficFilter) {
trafficFilter_ = trafficFilter;
}
void HTTPConnectProxiedConnection::initializeProxy() {
httpResponseBuffer_.clear();
std::stringstream connect;
connect << "CONNECT " << getServer().getAddress().toString() << ":" << getServer().getPort() << " HTTP/1.1\r\n";
SafeByteArray data = createSafeByteArray(connect.str());
if (!authID_.empty() && !authPassword_.empty()) {
append(data, createSafeByteArray("Proxy-Authorization: Basic "));
SafeByteArray credentials = authID_;
append(credentials, createSafeByteArray(":"));
append(credentials, authPassword_);
append(data, Base64::encode(credentials));
append(data, createSafeByteArray("\r\n"));
}
else if (!nextHTTPRequestHeaders_.empty()) {
- typedef std::pair<std::string, std::string> StringPair;
- foreach(const StringPair& headerField, nextHTTPRequestHeaders_) {
+ for (const auto& headerField : nextHTTPRequestHeaders_) {
append(data, createSafeByteArray(headerField.first));
append(data, createSafeByteArray(": "));
append(data, createSafeByteArray(headerField.second));
append(data, createSafeByteArray("\r\n"));
}
nextHTTPRequestHeaders_.clear();
}
append(data, createSafeByteArray("\r\n"));
SWIFT_LOG(debug) << "HTTP Proxy send headers: " << byteArrayToString(ByteArray(data.begin(), data.end())) << std::endl;
write(data);
}
void HTTPConnectProxiedConnection::parseHTTPHeader(const std::string& data, std::string& statusLine, std::vector<std::pair<std::string, std::string> >& headerFields) {
std::istringstream dataStream(data);
// parse status line
std::getline(dataStream, statusLine);
// parse fields
std::string headerLine;
std::string::size_type splitIndex;
while (std::getline(dataStream, headerLine) && headerLine != "\r") {
splitIndex = headerLine.find(':', 0);
if (splitIndex != std::string::npos) {
headerFields.push_back(std::pair<std::string, std::string>(headerLine.substr(0, splitIndex), headerLine.substr(splitIndex + 1)));
}
}
}
void HTTPConnectProxiedConnection::sendHTTPRequest(const std::string& statusLine, const std::vector<std::pair<std::string, std::string> >& headerFields) {
- typedef std::pair<std::string, std::string> HTTPHeaderField;
std::stringstream request;
request << statusLine << "\r\n";
- foreach (const HTTPHeaderField& field, headerFields) {
+ for (const auto& field : headerFields) {
request << field.first << ":" << field.second << "\r\n";
}
request << "\r\n";
write(createSafeByteArray(request.str()));
}
void HTTPConnectProxiedConnection::handleProxyInitializeData(std::shared_ptr<SafeByteArray> data) {
std::string dataString = byteArrayToString(ByteArray(data->begin(), data->end()));
SWIFT_LOG(debug) << data << std::endl;
httpResponseBuffer_.append(dataString);
std::string statusLine;
std::vector<std::pair<std::string, std::string> > headerFields;
std::string::size_type headerEnd = httpResponseBuffer_.find("\r\n\r\n", 0);
if (headerEnd == std::string::npos) {
if ((httpResponseBuffer_.size() > 4) && (httpResponseBuffer_.substr(0, 4) != "HTTP")) {
setProxyInitializeFinished(false);
}
return;
}
parseHTTPHeader(httpResponseBuffer_.substr(0, headerEnd), statusLine, headerFields);
if (trafficFilter_) {
std::vector<std::pair<std::string, std::string> > newHeaderFields = trafficFilter_->filterHTTPResponseHeader(statusLine, headerFields);
if (!newHeaderFields.empty()) {
std::stringstream statusLine;
reconnect();
nextHTTPRequestHeaders_ = newHeaderFields;
diff --git a/Swiften/Network/NetworkEnvironment.cpp b/Swiften/Network/NetworkEnvironment.cpp
index 19f727c..87883c1 100644
--- a/Swiften/Network/NetworkEnvironment.cpp
+++ b/Swiften/Network/NetworkEnvironment.cpp
@@ -1,32 +1,31 @@
/*
* Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Network/NetworkEnvironment.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Network/HostAddress.h>
#include <Swiften/Network/NetworkInterface.h>
namespace Swift {
NetworkEnvironment::~NetworkEnvironment() {
}
HostAddress NetworkEnvironment::getLocalAddress() const {
std::vector<NetworkInterface> networkInterfaces = getNetworkInterfaces();
- foreach (const NetworkInterface& iface, networkInterfaces) {
+ for (const auto& iface : networkInterfaces) {
if (!iface.isLoopback()) {
- foreach (const HostAddress& address, iface.getAddresses()) {
+ for (const auto& address : iface.getAddresses()) {
if (address.getRawAddress().is_v4()) {
return address;
}
}
}
}
return HostAddress();
}
}
diff --git a/Swiften/Network/PlatformDomainNameServiceQuery.cpp b/Swiften/Network/PlatformDomainNameServiceQuery.cpp
index 71611f5..5cffcdb 100644
--- a/Swiften/Network/PlatformDomainNameServiceQuery.cpp
+++ b/Swiften/Network/PlatformDomainNameServiceQuery.cpp
@@ -1,62 +1,61 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <boost/asio.hpp>
#include <Swiften/Network/PlatformDomainNameServiceQuery.h>
#pragma GCC diagnostic ignored "-Wold-style-cast"
#include <Swiften/Base/Platform.h>
#include <stdlib.h>
#include <boost/numeric/conversion/cast.hpp>
#ifdef SWIFTEN_PLATFORM_WINDOWS
#undef UNICODE
#include <windows.h>
#include <windns.h>
#ifndef DNS_TYPE_SRV
#define DNS_TYPE_SRV 33
#endif
#else
#include <arpa/nameser.h>
#include <arpa/nameser_compat.h>
#include <resolv.h>
#endif
#include <boost/bind.hpp>
#include <Swiften/Base/ByteArray.h>
#include <Swiften/EventLoop/EventLoop.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Base/BoostRandomGenerator.h>
#include <Swiften/Base/Log.h>
#include <Swiften/Network/PlatformDomainNameResolver.h>
using namespace Swift;
namespace Swift {
PlatformDomainNameServiceQuery::PlatformDomainNameServiceQuery(const boost::optional<std::string>& serviceName, EventLoop* eventLoop, PlatformDomainNameResolver* resolver) : PlatformDomainNameQuery(resolver), eventLoop(eventLoop), serviceValid(false) {
if (!!serviceName) {
service = *serviceName;
serviceValid = true;
}
}
PlatformDomainNameServiceQuery::~PlatformDomainNameServiceQuery() {
}
void PlatformDomainNameServiceQuery::run() {
getResolver()->addQueryToQueue(shared_from_this());
}
void PlatformDomainNameServiceQuery::runBlocking() {
if (!serviceValid) {
emitError();
return;
}
SWIFT_LOG(debug) << "Querying " << service << std::endl;
diff --git a/Swiften/Network/UnixProxyProvider.cpp b/Swiften/Network/UnixProxyProvider.cpp
index 6c23add..e6afa3d 100644
--- a/Swiften/Network/UnixProxyProvider.cpp
+++ b/Swiften/Network/UnixProxyProvider.cpp
@@ -1,45 +1,44 @@
/*
* Copyright (c) 2010-2011 Thilo Cestonaro
* 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 <Swiften/Network/UnixProxyProvider.h>
-#include <Swiften/Base/foreach.h>
#if defined(HAVE_GCONF)
# include "Swiften/Network/GConfProxyProvider.h"
#endif
namespace Swift {
UnixProxyProvider::UnixProxyProvider() :
gconfProxyProvider(nullptr),
environmentProxyProvider()
{
#if defined(HAVE_GCONF)
gconfProxyProvider = new GConfProxyProvider();
#endif
}
UnixProxyProvider::~UnixProxyProvider() {
#if defined(HAVE_GCONF)
delete gconfProxyProvider;
#endif
}
HostAddressPort UnixProxyProvider::getSOCKS5Proxy() const {
HostAddressPort proxy;
#if defined(HAVE_GCONF)
proxy = gconfProxyProvider->getSOCKS5Proxy();
if(proxy.isValid()) {
return proxy;
}
#endif
proxy = environmentProxyProvider.getSOCKS5Proxy();
diff --git a/Swiften/Network/WindowsNetworkEnvironment.cpp b/Swiften/Network/WindowsNetworkEnvironment.cpp
index 6ce41de..e90a5c6 100644
--- a/Swiften/Network/WindowsNetworkEnvironment.cpp
+++ b/Swiften/Network/WindowsNetworkEnvironment.cpp
@@ -1,74 +1,73 @@
/*
* Copyright (c) 2011 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 <Swiften/Network/WindowsNetworkEnvironment.h>
#include <map>
#include <string>
#include <vector>
#include <boost/optional.hpp>
#include <iphlpapi.h>
#include <winsock2.h>
#include <Swiften/Base/ByteArray.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Network/HostAddress.h>
#include <Swiften/Network/NetworkInterface.h>
namespace Swift {
std::vector<NetworkInterface> WindowsNetworkEnvironment::getNetworkInterfaces() const {
std::vector<NetworkInterface> result;
ByteArray adapters;
ULONG bufferSize = 0;
ULONG ret;
ULONG flags = GAA_FLAG_INCLUDE_ALL_INTERFACES | GAA_FLAG_INCLUDE_PREFIX | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER;
while ((ret = GetAdaptersAddresses(AF_UNSPEC, flags, NULL, reinterpret_cast<IP_ADAPTER_ADDRESSES*>(vecptr(adapters)), &bufferSize)) == ERROR_BUFFER_OVERFLOW) {
adapters.resize(bufferSize);
};
if (ret != ERROR_SUCCESS) {
return result;
}
std::map<std::string,NetworkInterface> interfaces;
for (IP_ADAPTER_ADDRESSES* adapter = reinterpret_cast<IP_ADAPTER_ADDRESSES*>(vecptr(adapters)); adapter; adapter = adapter->Next) {
std::string name(adapter->AdapterName);
if (adapter->OperStatus != IfOperStatusUp) {
continue;
}
for (IP_ADAPTER_UNICAST_ADDRESS* address = adapter->FirstUnicastAddress; address; address = address->Next) {
boost::optional<HostAddress> hostAddress;
if (address->Address.lpSockaddr->sa_family == PF_INET) {
sockaddr_in* sa = reinterpret_cast<sockaddr_in*>(address->Address.lpSockaddr);
hostAddress = HostAddress(reinterpret_cast<const unsigned char*>(&(sa->sin_addr)), 4);
}
else if (address->Address.lpSockaddr->sa_family == PF_INET6) {
sockaddr_in6* sa = reinterpret_cast<sockaddr_in6*>(address->Address.lpSockaddr);
hostAddress = HostAddress(reinterpret_cast<const unsigned char*>(&(sa->sin6_addr)), 16);
}
if (hostAddress && !hostAddress->isLocalhost()) {
std::map<std::string, NetworkInterface>::iterator i = interfaces.insert(std::make_pair(name, NetworkInterface(name, false))).first;
i->second.addAddress(*hostAddress);
}
}
}
- for (std::map<std::string,NetworkInterface>::const_iterator i = interfaces.begin(); i != interfaces.end(); ++i) {
- result.push_back(i->second);
+ for (const auto& interface : interfaces) {
+ result.push_back(interface.second);
}
return result;
}
}
diff --git a/Swiften/Parser/PayloadParsers/BytestreamsParser.cpp b/Swiften/Parser/PayloadParsers/BytestreamsParser.cpp
index 8a0ecd2..405c593 100644
--- a/Swiften/Parser/PayloadParsers/BytestreamsParser.cpp
+++ b/Swiften/Parser/PayloadParsers/BytestreamsParser.cpp
@@ -1,42 +1,40 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Parser/PayloadParsers/BytestreamsParser.h>
#include <boost/lexical_cast.hpp>
-#include <Swiften/Base/foreach.h>
-
namespace Swift {
BytestreamsParser::BytestreamsParser() : level(TopLevel) {
}
BytestreamsParser::~BytestreamsParser() {
}
void BytestreamsParser::handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) {
if (level == TopLevel) {
getPayloadInternal()->setStreamID(attributes.getAttribute("sid"));
}
else if (level == PayloadLevel) {
if (element == "streamhost") {
try {
getPayloadInternal()->addStreamHost(Bytestreams::StreamHost(attributes.getAttribute("host"), JID(attributes.getAttribute("jid")), boost::lexical_cast<int>(attributes.getAttribute("port"))));
}
catch (boost::bad_lexical_cast&) {
}
}
else if (element == "streamhost-used") {
getPayloadInternal()->setUsedStreamHost(JID(attributes.getAttribute("jid")));
}
}
++level;
}
void BytestreamsParser::handleEndElement(const std::string&, const std::string&) {
--level;
}
diff --git a/Swiften/Parser/PayloadParsers/FormParser.cpp b/Swiften/Parser/PayloadParsers/FormParser.cpp
index 5ea75c5..dff45df 100644
--- a/Swiften/Parser/PayloadParsers/FormParser.cpp
+++ b/Swiften/Parser/PayloadParsers/FormParser.cpp
@@ -1,41 +1,39 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Parser/PayloadParsers/FormParser.h>
#include <map>
-#include <Swiften/Base/foreach.h>
-
namespace Swift {
FormParser::FormParser() : level_(TopLevel), parsingItem_(false), parsingReported_(false), parsingOption_(false), hasReportedRef_(false){
}
void FormParser::handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) {
if (level_ == TopLevel) {
std::string type = attributes.getAttribute("type");
if (type == "form") {
getPayloadInternal()->setType(Form::FormType);
}
else if (type == "submit") {
getPayloadInternal()->setType(Form::SubmitType);
}
else if (type == "cancel") {
getPayloadInternal()->setType(Form::CancelType);
}
else if (type == "result") {
getPayloadInternal()->setType(Form::ResultType);
}
}
else if (level_ == PayloadLevel) {
if (element == "title") {
currentText_.clear();
}
else if (element == "instructions") {
currentText_.clear();
}
else if (element == "reported") {
parsingReported_ = true;
@@ -163,69 +161,69 @@ void FormParser::handleEndElement(const std::string& element, const std::string&
else if (currentField_) {
if (element == "required") {
currentField_->setRequired(true);
}
else if (element == "desc") {
currentField_->setDescription(currentText_);
}
else if (element == "option") {
currentField_->addOption(FormField::Option(currentOptionLabel_, currentOptionValue_));
parsingOption_ = false;
}
else if (element == "value") {
if (parsingOption_) {
currentOptionValue_ = currentText_;
}
else {
currentField_->addValue(currentText_);
}
}
}
if (level_ >= PayloadLevel && currentField_) {
if (element == "field") {
if (parsingReported_) {
getPayloadInternal()->addReportedField(currentField_);
}
else if (parsingItem_) {
currentFields_.push_back(currentField_);
}
else {
if (currentPages_.size() > 0) {
- foreach (std::shared_ptr<FormPage> page, currentPages_) {
- foreach (std::string pageRef, page->getFieldRefs()) {
+ for (const auto& page : currentPages_) {
+ for (const auto& pageRef : page->getFieldRefs()) {
if (pageRef == currentField_->getName()) {
page->addField(currentField_);
}
}
}
- foreach (std::shared_ptr<FormSection> section, currentSections_) {
- foreach (std::string sectionRef, section->getFieldRefs()) {
+ for (const auto& section : currentSections_) {
+ for (const auto& sectionRef : section->getFieldRefs()) {
if (sectionRef == currentField_->getName()) {
section->addField(currentField_);
}
}
}
} else {
getPayloadInternal()->addField(currentField_);
}
}
currentField_.reset();
}
}
if (level_ > PayloadLevel) {
if (element == "section") {
if (sectionStack_.size() > 1) {
// Add the section at the top of the stack to the level below
sectionStack_.at(sectionStack_.size()-2)->addChildSection(sectionStack_.at(sectionStack_.size()-1));
sectionStack_.pop_back();
}
else if (sectionStack_.size() == 1) {
// Add the remaining section on the stack to its parent page
currentPage_->addChildSection(sectionStack_.at(sectionStack_.size()-1));
sectionStack_.pop_back();
}
}
if (currentReportedRef_ && !hasReportedRef_) {
if (sectionStack_.size() > 0) {
sectionStack_.at(sectionStack_.size()-1)->addReportedRef(currentReportedRef_);
} else if (currentPage_) {
currentPage_->addReportedRef(currentReportedRef_);
diff --git a/Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.cpp b/Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.cpp
index a231397..b67556e 100644
--- a/Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.cpp
+++ b/Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.cpp
@@ -1,39 +1,38 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Elements/BlockListPayload.h>
#include <Swiften/Elements/BlockPayload.h>
#include <Swiften/Elements/UnblockPayload.h>
#include <Swiften/Parser/GenericPayloadParser.h>
#include <Swiften/Parser/GenericPayloadParserFactory.h>
#include <Swiften/Parser/GenericPayloadParserFactory2.h>
#include <Swiften/Parser/PayloadParserFactory.h>
#include <Swiften/Parser/PayloadParsers/BlockParser.h>
#include <Swiften/Parser/PayloadParsers/BodyParser.h>
#include <Swiften/Parser/PayloadParsers/BytestreamsParser.h>
#include <Swiften/Parser/PayloadParsers/CapsInfoParser.h>
#include <Swiften/Parser/PayloadParsers/CarbonsDisableParser.h>
#include <Swiften/Parser/PayloadParsers/CarbonsEnableParser.h>
#include <Swiften/Parser/PayloadParsers/CarbonsPrivateParser.h>
#include <Swiften/Parser/PayloadParsers/CarbonsReceivedParser.h>
#include <Swiften/Parser/PayloadParsers/CarbonsSentParser.h>
#include <Swiften/Parser/PayloadParsers/ChatStateParserFactory.h>
#include <Swiften/Parser/PayloadParsers/CommandParser.h>
#include <Swiften/Parser/PayloadParsers/DelayParser.h>
#include <Swiften/Parser/PayloadParsers/DeliveryReceiptParserFactory.h>
#include <Swiften/Parser/PayloadParsers/DeliveryReceiptRequestParserFactory.h>
#include <Swiften/Parser/PayloadParsers/DiscoInfoParser.h>
#include <Swiften/Parser/PayloadParsers/DiscoItemsParser.h>
#include <Swiften/Parser/PayloadParsers/ErrorParser.h>
#include <Swiften/Parser/PayloadParsers/ErrorParserFactory.h>
#include <Swiften/Parser/PayloadParsers/FormParserFactory.h>
#include <Swiften/Parser/PayloadParsers/ForwardedParser.h>
#include <Swiften/Parser/PayloadParsers/IBBParser.h>
#include <Swiften/Parser/PayloadParsers/IdleParser.h>
#include <Swiften/Parser/PayloadParsers/InBandRegistrationPayloadParser.h>
@@ -140,46 +139,46 @@ FullPayloadParserFactoryCollection::FullPayloadParserFactoryCollection() {
factories_.push_back(std::make_shared<JingleContentPayloadParserFactory>(this));
factories_.push_back(std::make_shared<GenericPayloadParserFactory<JingleIBBTransportMethodPayloadParser> >("transport", "urn:xmpp:jingle:transports:ibb:1"));
factories_.push_back(std::make_shared<GenericPayloadParserFactory<JingleS5BTransportMethodPayloadParser> >("transport", "urn:xmpp:jingle:transports:s5b:1"));
factories_.push_back(std::make_shared<JingleFileTransferDescriptionParserFactory>(this));
factories_.push_back(std::make_shared<GenericPayloadParserFactory<StreamInitiationFileInfoParser> >("file", "http://jabber.org/protocol/si/profile/file-transfer"));
factories_.push_back(std::make_shared<GenericPayloadParserFactory<JingleFileTransferFileInfoParser> >("file", "urn:xmpp:jingle:apps:file-transfer:4"));
factories_.push_back(std::make_shared<GenericPayloadParserFactory<JingleFileTransferHashParser> >("checksum"));
factories_.push_back(std::make_shared<GenericPayloadParserFactory<S5BProxyRequestParser> >("query", "http://jabber.org/protocol/bytestreams"));
factories_.push_back(std::make_shared<GenericPayloadParserFactory<WhiteboardParser> >("wb", "http://swift.im/whiteboard"));
factories_.push_back(std::make_shared<GenericPayloadParserFactory<UserLocationParser> >("geoloc", "http://jabber.org/protocol/geoloc"));
factories_.push_back(std::make_shared<GenericPayloadParserFactory<UserTuneParser> >("tune", "http://jabber.org/protocol/tune"));
factories_.push_back(std::make_shared<DeliveryReceiptParserFactory>());
factories_.push_back(std::make_shared<DeliveryReceiptRequestParserFactory>());
factories_.push_back(std::make_shared<GenericPayloadParserFactory<IdleParser> >("idle", "urn:xmpp:idle:1"));
factories_.push_back(std::make_shared<GenericPayloadParserFactory2<PubSubParser> >("pubsub", "http://jabber.org/protocol/pubsub", this));
factories_.push_back(std::make_shared<GenericPayloadParserFactory2<PubSubOwnerPubSubParser> >("pubsub", "http://jabber.org/protocol/pubsub#owner", this));
factories_.push_back(std::make_shared<GenericPayloadParserFactory2<PubSubEventParser> >("event", "http://jabber.org/protocol/pubsub#event", this));
factories_.push_back(std::make_shared<PubSubErrorParserFactory>());
factories_.push_back(std::make_shared<GenericPayloadParserFactory<ResultSetParser> >("set", "http://jabber.org/protocol/rsm"));
factories_.push_back(std::make_shared<GenericPayloadParserFactory2<ForwardedParser> >("forwarded", "urn:xmpp:forward:0", this));
factories_.push_back(std::make_shared<GenericPayloadParserFactory2<MAMResultParser> >("result", "urn:xmpp:mam:0", this));
factories_.push_back(std::make_shared<GenericPayloadParserFactory<MAMQueryParser> >("query", "urn:xmpp:mam:0"));
factories_.push_back(std::make_shared<GenericPayloadParserFactory<MAMFinParser> >("fin", "urn:xmpp:mam:0"));
factories_.push_back(std::make_shared<GenericPayloadParserFactory2<IsodeIQDelegationParser> >("delegate", "http://isode.com/iq_delegation", this));
factories_.push_back(std::make_shared<GenericPayloadParserFactory<CarbonsEnableParser> >("enable", "urn:xmpp:carbons:2"));
factories_.push_back(std::make_shared<GenericPayloadParserFactory<CarbonsDisableParser> >("disable", "urn:xmpp:carbons:2"));
factories_.push_back(std::make_shared<GenericPayloadParserFactory2<CarbonsReceivedParser> >("received", "urn:xmpp:carbons:2", this));
factories_.push_back(std::make_shared<GenericPayloadParserFactory2<CarbonsSentParser> >("sent", "urn:xmpp:carbons:2", this));
factories_.push_back(std::make_shared<GenericPayloadParserFactory<CarbonsPrivateParser> >("private", "urn:xmpp:carbons:2"));
- foreach(std::shared_ptr<PayloadParserFactory> factory, factories_) {
+ for (auto& factory : factories_) {
addFactory(factory.get());
}
defaultFactory_ = new RawXMLPayloadParserFactory();
setDefaultFactory(defaultFactory_);
}
FullPayloadParserFactoryCollection::~FullPayloadParserFactoryCollection() {
setDefaultFactory(nullptr);
delete defaultFactory_;
- foreach(std::shared_ptr<PayloadParserFactory> factory, factories_) {
+ for (auto& factory : factories_) {
removeFactory(factory.get());
}
}
}
diff --git a/Swiften/Parser/PayloadParsers/IBBParser.cpp b/Swiften/Parser/PayloadParsers/IBBParser.cpp
index 4a6b841..9b6babc 100644
--- a/Swiften/Parser/PayloadParsers/IBBParser.cpp
+++ b/Swiften/Parser/PayloadParsers/IBBParser.cpp
@@ -1,41 +1,40 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Parser/PayloadParsers/IBBParser.h>
#include <boost/lexical_cast.hpp>
-#include <Swiften/Base/foreach.h>
#include <Swiften/StringCodecs/Base64.h>
namespace Swift {
IBBParser::IBBParser() : level(TopLevel) {
}
IBBParser::~IBBParser() {
}
void IBBParser::handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) {
if (level == TopLevel) {
if (element == "data") {
getPayloadInternal()->setAction(IBB::Data);
getPayloadInternal()->setStreamID(attributes.getAttribute("sid"));
try {
getPayloadInternal()->setSequenceNumber(boost::lexical_cast<int>(attributes.getAttribute("seq")));
}
catch (boost::bad_lexical_cast&) {
}
}
else if (element == "open") {
getPayloadInternal()->setAction(IBB::Open);
getPayloadInternal()->setStreamID(attributes.getAttribute("sid"));
if (attributes.getAttribute("stanza") == "message") {
getPayloadInternal()->setStanzaType(IBB::MessageStanza);
}
else {
getPayloadInternal()->setStanzaType(IBB::IQStanza);
}
diff --git a/Swiften/Parser/PayloadParsers/MUCAdminPayloadParser.cpp b/Swiften/Parser/PayloadParsers/MUCAdminPayloadParser.cpp
index 1fbff1c..bac2a78 100644
--- a/Swiften/Parser/PayloadParsers/MUCAdminPayloadParser.cpp
+++ b/Swiften/Parser/PayloadParsers/MUCAdminPayloadParser.cpp
@@ -1,23 +1,22 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Parser/PayloadParsers/MUCAdminPayloadParser.h>
#include <boost/lexical_cast.hpp>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Elements/MUCOccupant.h>
namespace Swift {
void MUCAdminPayloadParser::handleTree(ParserElement::ref root) {
- foreach (ParserElement::ref itemElement, root->getChildren("item", "http://jabber.org/protocol/muc#admin")) {
+ for (const auto& itemElement : root->getChildren("item", "http://jabber.org/protocol/muc#admin")) {
MUCItem item = MUCItemParser::itemFromTree(itemElement);
getPayloadInternal()->addItem(item);
}
}
}
diff --git a/Swiften/Parser/PayloadParsers/MUCDestroyPayloadParser.cpp b/Swiften/Parser/PayloadParsers/MUCDestroyPayloadParser.cpp
index 95ff8c5..46bc9c5 100644
--- a/Swiften/Parser/PayloadParsers/MUCDestroyPayloadParser.cpp
+++ b/Swiften/Parser/PayloadParsers/MUCDestroyPayloadParser.cpp
@@ -1,22 +1,20 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Parser/PayloadParsers/MUCDestroyPayloadParser.h>
-#include <Swiften/Base/foreach.h>
-
namespace Swift {
void MUCDestroyPayloadParser::handleTree(ParserElement::ref root) {
std::string ns = root->getNamespace();
std::string jid = root->getAttributes().getAttribute("jid");
if (!jid.empty()) {
getPayloadInternal()->setNewVenue(JID(jid));
}
getPayloadInternal()->setReason(root->getChild("reason", ns)->getText());
}
}
diff --git a/Swiften/Parser/PayloadParsers/MUCUserPayloadParser.cpp b/Swiften/Parser/PayloadParsers/MUCUserPayloadParser.cpp
index 00a5d4f..b1bf78e 100644
--- a/Swiften/Parser/PayloadParsers/MUCUserPayloadParser.cpp
+++ b/Swiften/Parser/PayloadParsers/MUCUserPayloadParser.cpp
@@ -1,50 +1,49 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Parser/PayloadParsers/MUCUserPayloadParser.h>
#include <boost/lexical_cast.hpp>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Elements/MUCOccupant.h>
#include <Swiften/Parser/PayloadParserFactory.h>
#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/Tree/TreeReparser.h>
namespace Swift {
void MUCUserPayloadParser::handleTree(ParserElement::ref root) {
- foreach (ParserElement::ref child, root->getAllChildren()) {
+ for (const auto& child : root->getAllChildren()) {
if (child->getName() == "item" && child->getNamespace() == root->getNamespace()) {
MUCItem item = MUCItemParser::itemFromTree(child);
getPayloadInternal()->addItem(item);
}
else if (child->getName() == "password" && child->getNamespace() == root->getNamespace()) {
getPayloadInternal()->setPassword(child->getText());
}
else if (child->getName() == "invite" && child->getNamespace() == root->getNamespace()) {
MUCUserPayload::Invite invite;
std::string to = child->getAttributes().getAttribute("to");
if (!to.empty()) {
invite.to = to;
}
std::string from = child->getAttributes().getAttribute("from");
if (!from.empty()) {
invite.from = from;
}
ParserElement::ref reason = child->getChild("reason", root->getNamespace());
if (reason) {
invite.reason = reason->getText();
}
getPayloadInternal()->setInvite(invite);
}
else if (child->getName() == "status" && child->getNamespace() == root->getNamespace()) {
MUCUserPayload::StatusCode status;
try {
status.code = boost::lexical_cast<int>(child->getAttributes().getAttribute("code").c_str());
getPayloadInternal()->addStatusCode(status);
} catch (boost::bad_lexical_cast&) {
}
diff --git a/Swiften/Parser/PayloadParsers/StreamInitiationParser.cpp b/Swiften/Parser/PayloadParsers/StreamInitiationParser.cpp
index 1b0c95d..ad66b3f 100644
--- a/Swiften/Parser/PayloadParsers/StreamInitiationParser.cpp
+++ b/Swiften/Parser/PayloadParsers/StreamInitiationParser.cpp
@@ -1,47 +1,45 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Parser/PayloadParsers/StreamInitiationParser.h>
#include <boost/lexical_cast.hpp>
#include <boost/cast.hpp>
#include <cassert>
#include <Swiften/Parser/PayloadParsers/FormParserFactory.h>
#include <Swiften/Parser/PayloadParsers/FormParser.h>
-#include <Swiften/Base/foreach.h>
-
#define FILE_TRANSFER_NS "http://jabber.org/protocol/si/profile/file-transfer"
#define FEATURE_NEG_NS "http://jabber.org/protocol/feature-neg"
namespace Swift {
StreamInitiationParser::StreamInitiationParser() : level(TopLevel), formParser(nullptr), inFile(false), inFeature(false) {
formParserFactory = new FormParserFactory();
}
StreamInitiationParser::~StreamInitiationParser() {
delete formParserFactory;
}
void StreamInitiationParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
if (level == TopLevel) {
getPayloadInternal()->setID(attributes.getAttribute("id"));
if (!attributes.getAttribute("profile").empty()) {
getPayloadInternal()->setIsFileTransfer(attributes.getAttribute("profile") == FILE_TRANSFER_NS);
}
}
else if (level == PayloadLevel) {
if (element == "file") {
inFile = true;
currentFile = StreamInitiationFileInfo();
currentFile.setName(attributes.getAttribute("name"));
try {
currentFile.setSize(boost::lexical_cast<unsigned long long>(attributes.getAttribute("size")));
}
catch (boost::bad_lexical_cast&) {
@@ -66,58 +64,58 @@ void StreamInitiationParser::handleStartElement(const std::string& element, cons
}
++level;
}
void StreamInitiationParser::handleEndElement(const std::string& element, const std::string& ns) {
--level;
if (formParser) {
formParser->handleEndElement(element, ns);
}
if (level == TopLevel) {
}
else if (level == PayloadLevel) {
if (element == "file") {
getPayloadInternal()->setFileInfo(currentFile);
inFile = false;
}
else if (element == "feature" && ns == FEATURE_NEG_NS) {
inFeature = false;
}
}
else if (level == FileOrFeatureLevel) {
if (inFile && element == "desc") {
currentFile.setDescription(currentText);
}
else if (formParser) {
Form::ref form = formParser->getPayloadInternal();
if (form) {
FormField::ref field = std::dynamic_pointer_cast<FormField>(form->getField("stream-method"));
if (field) {
if (form->getType() == Form::FormType) {
- foreach (const FormField::Option& option, field->getOptions()) {
+ for (const auto& option : field->getOptions()) {
getPayloadInternal()->addProvidedMethod(option.value);
}
}
else if (form->getType() == Form::SubmitType) {
if (!field->getValues().empty()) {
getPayloadInternal()->setRequestedMethod(field->getValues()[0]);
}
}
}
}
delete formParser;
formParser = nullptr;
}
}
}
void StreamInitiationParser::handleCharacterData(const std::string& data) {
if (formParser) {
formParser->handleCharacterData(data);
}
else {
currentText += data;
}
}
}
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/MUCUserPayloadParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/MUCUserPayloadParserTest.cpp
index 18597bd..f0cf68d 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/MUCUserPayloadParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/MUCUserPayloadParserTest.cpp
@@ -1,69 +1,68 @@
/*
* Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Elements/MUCDestroyPayload.h>
#include <Swiften/Parser/PayloadParsers/MUCUserPayloadParser.h>
#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h>
using namespace Swift;
class MUCUserPayloadParserTest : public CppUnit::TestFixture
{
CPPUNIT_TEST_SUITE(MUCUserPayloadParserTest);
CPPUNIT_TEST(testParseEmpty);
CPPUNIT_TEST(testParse);
CPPUNIT_TEST(testParseDestroy);
CPPUNIT_TEST(testParseInvite);
CPPUNIT_TEST_SUITE_END();
public:
MUCUserPayloadParserTest() {}
void testParse() {
PayloadsParserTester parser;
CPPUNIT_ASSERT(parser.parse("<x xmlns=\"http://jabber.org/protocol/muc#user\"><status code='110'/><item affiliation=\"owner\" role=\"visitor\"><actor jid=\"kev@tester.lit\"/><reason>malice</reason></item><status code='210'/></x>"));
bool found110 = false;
bool found210 = false;
MUCUserPayload::ref payload = std::dynamic_pointer_cast<MUCUserPayload>(parser.getPayload());
- foreach (MUCUserPayload::StatusCode status, payload->getStatusCodes()) {
+ for (const auto& status : payload->getStatusCodes()) {
if (status.code == 110) found110 = true;
if (status.code == 210) found210 = true;
}
MUCItem item = payload->getItems()[0];
CPPUNIT_ASSERT_EQUAL(MUCOccupant::Owner, item.affiliation.get());
CPPUNIT_ASSERT_EQUAL(MUCOccupant::Visitor, item.role.get());
CPPUNIT_ASSERT_EQUAL(JID("kev@tester.lit"), item.actor.get());
CPPUNIT_ASSERT_EQUAL(std::string("malice"), item.reason.get());
CPPUNIT_ASSERT(found110);
CPPUNIT_ASSERT(found210);
}
void testParseEmpty() {
PayloadsParserTester parser;
CPPUNIT_ASSERT(parser.parse("<x xmlns=\"http://jabber.org/protocol/muc#user\"/>"));
MUCUserPayload::ref payload = std::dynamic_pointer_cast<MUCUserPayload>(parser.getPayload());
CPPUNIT_ASSERT(payload);
CPPUNIT_ASSERT(payload->getItems().empty());
}
void testParseDestroy() {
PayloadsParserTester parser;
CPPUNIT_ASSERT(parser.parse("<x xmlns=\"http://jabber.org/protocol/muc#user\"><destroy jid='alice@wonderland.lit'><reason>bert</reason></destroy></x>"));
MUCUserPayload::ref payload = std::dynamic_pointer_cast<MUCUserPayload>(parser.getPayload());
CPPUNIT_ASSERT(payload);
diff --git a/Swiften/Parser/PayloadParsers/VCardParser.cpp b/Swiften/Parser/PayloadParsers/VCardParser.cpp
index 7867b2c..f8779d1 100644
--- a/Swiften/Parser/PayloadParsers/VCardParser.cpp
+++ b/Swiften/Parser/PayloadParsers/VCardParser.cpp
@@ -1,42 +1,41 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Parser/PayloadParsers/VCardParser.h>
#include <cassert>
#include <Swiften/Base/DateTime.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Parser/SerializingParser.h>
#include <Swiften/StringCodecs/Base64.h>
namespace Swift {
VCardParser::VCardParser() : unknownContentParser_(nullptr) {
}
void VCardParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
elementStack_.push_back(element);
std::string elementHierarchy = getElementHierarchy();
if (elementHierarchy == "/vCard/EMAIL") {
currentEMailAddress_ = VCard::EMailAddress();
}
if (elementHierarchy == "/vCard/TEL") {
currentTelephone_ = VCard::Telephone();
}
if (elementHierarchy == "/vCard/ADR") {
currentAddress_ = VCard::Address();
}
if (elementHierarchy == "/vCard/LABEL") {
currentAddressLabel_ = VCard::AddressLabel();
}
if (elementHierarchy == "/vCard/ORG") {
currentOrganization_ = VCard::Organization();
}
if (elementStack_.size() == 2) {
assert(!unknownContentParser_);
unknownContentParser_ = new SerializingParser();
unknownContentParser_->handleStartElement(element, ns, attributes);
@@ -255,37 +254,37 @@ void VCardParser::handleEndElement(const std::string& element, const std::string
}
else if (elementHierarchy == "/vCard/TITLE" && !currentText_.empty()) {
getPayloadInternal()->addTitle(currentText_);
}
else if (elementHierarchy == "/vCard/ROLE" && !currentText_.empty()) {
getPayloadInternal()->addRole(currentText_);
}
else if (elementHierarchy == "/vCard/URL" && !currentText_.empty()) {
getPayloadInternal()->addURL(currentText_);
}
else if (elementStack_.size() == 2 && unknownContentParser_) {
getPayloadInternal()->addUnknownContent(unknownContentParser_->getResult());
}
if (elementStack_.size() == 2 && unknownContentParser_) {
delete unknownContentParser_;
unknownContentParser_ = nullptr;
}
elementStack_.pop_back();
}
void VCardParser::handleCharacterData(const std::string& text) {
if (unknownContentParser_) {
unknownContentParser_->handleCharacterData(text);
}
currentText_ += text;
}
std::string VCardParser::getElementHierarchy() const {
std::string result;
- foreach(const std::string& element, elementStack_) {
+ for (const auto& element : elementStack_) {
result += "/" + element;
}
return result;
}
}
diff --git a/Swiften/Parser/SerializingParser.cpp b/Swiften/Parser/SerializingParser.cpp
index ad794aa..85b0dd4 100644
--- a/Swiften/Parser/SerializingParser.cpp
+++ b/Swiften/Parser/SerializingParser.cpp
@@ -1,51 +1,50 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Parser/SerializingParser.h>
#include <cassert>
#include <memory>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
namespace Swift {
SerializingParser::SerializingParser() {
}
void SerializingParser::handleStartElement(const std::string& tag, const std::string& ns, const AttributeMap& attributes) {
std::shared_ptr<XMLElement> element = std::make_shared<XMLElement>(tag, ns);
// FIXME: Ignoring attribute namespace
- foreach (const AttributeMap::Entry& e, attributes.getEntries()) {
+ for (const auto& e : attributes.getEntries()) {
element->setAttribute(e.getAttribute().getName(), e.getValue());
}
if (elementStack_.empty()) {
rootElement_ = element;
}
else {
(*(elementStack_.end() - 1))->addNode(element);
}
elementStack_.push_back(element);
}
void SerializingParser::handleEndElement(const std::string&, const std::string&) {
assert(!elementStack_.empty());
elementStack_.pop_back();
}
void SerializingParser::handleCharacterData(const std::string& data) {
if (!elementStack_.empty()) {
(*(elementStack_.end()-1))->addNode(std::make_shared<XMLTextNode>(data));
}
}
std::string SerializingParser::getResult() const {
return (rootElement_ ? rootElement_->serialize() : "");
}
}
diff --git a/Swiften/Parser/Tree/TreeReparser.cpp b/Swiften/Parser/Tree/TreeReparser.cpp
index 7fc74cf..6993d73 100644
--- a/Swiften/Parser/Tree/TreeReparser.cpp
+++ b/Swiften/Parser/Tree/TreeReparser.cpp
@@ -1,49 +1,48 @@
/*
* Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Parser/Tree/TreeReparser.h>
#include <deque>
#include <utility>
#include <boost/lexical_cast.hpp>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Elements/MUCOccupant.h>
#include <Swiften/Parser/PayloadParser.h>
#include <Swiften/Parser/PayloadParserFactory.h>
#include <Swiften/Parser/PayloadParserFactoryCollection.h>
namespace Swift {
typedef std::pair<ParserElement::ref, bool> ElementState;
std::shared_ptr<Payload> TreeReparser::parseTree(ParserElement::ref root, PayloadParserFactoryCollection* collection) {
PayloadParser* parser = collection->getPayloadParserFactory(root->getName(), root->getNamespace(), root->getAttributes())->createPayloadParser();
std::deque<ElementState > stack;
stack.push_back(ElementState(root, true));
while (!stack.empty()) {
ElementState current = stack.back();
stack.pop_back();
if (current.second) {
stack.push_back(ElementState(current.first, false));
parser->handleStartElement(current.first->getName(), current.first->getNamespace(), current.first->getAttributes());
- foreach(ParserElement::ref child, current.first->getAllChildren()) {
+ for (const auto& child : current.first->getAllChildren()) {
stack.push_back(ElementState(child, true));
}
} else {
parser->handleCharacterData(current.first->getText());
parser->handleEndElement(current.first->getName(), current.first->getNamespace());
}
}
std::shared_ptr<Payload> payload = parser->getPayload();
delete parser;
return payload;
}
}
diff --git a/Swiften/Presence/DirectedPresenceSender.cpp b/Swiften/Presence/DirectedPresenceSender.cpp
index c1ce3a0..c1134c7 100644
--- a/Swiften/Presence/DirectedPresenceSender.cpp
+++ b/Swiften/Presence/DirectedPresenceSender.cpp
@@ -1,55 +1,53 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Presence/DirectedPresenceSender.h>
-#include <Swiften/Base/foreach.h>
-
namespace Swift {
DirectedPresenceSender::DirectedPresenceSender(PresenceSender* sender) : sender(sender) {
}
void DirectedPresenceSender::sendPresence(std::shared_ptr<Presence> presence) {
if (!sender->isAvailable()) {
return;
}
sender->sendPresence(presence);
if (!presence->getTo().isValid()) {
std::shared_ptr<Presence> presenceCopy(new Presence(*presence));
- foreach(const JID& jid, directedPresenceReceivers) {
+ for (const auto& jid : directedPresenceReceivers) {
presenceCopy->setTo(jid);
sender->sendPresence(presenceCopy);
}
lastSentUndirectedPresence = presence;
}
}
/**
* Gets the last broadcast presence, if none has been send the returned optional is not set.
*/
boost::optional<Presence::ref> DirectedPresenceSender::getLastSentUndirectedPresence() const {
boost::optional<Presence::ref> presenceCopy = lastSentUndirectedPresence ? boost::optional<Presence::ref>((*lastSentUndirectedPresence)->clone()) : boost::optional<Presence::ref>();
return presenceCopy;
}
/**
* Send future broadcast presence also to this JID.
* @param jid Non-roster JID to receive global presence updates.
* @param sendPresence Also send the current global presence immediately.
*/
void DirectedPresenceSender::addDirectedPresenceReceiver(const JID& jid, SendPresence sendPresence) {
directedPresenceReceivers.insert(jid);
if (sendPresence == AndSendPresence && sender->isAvailable()) {
if (lastSentUndirectedPresence && (*lastSentUndirectedPresence)->getType() == Presence::Available) {
std::shared_ptr<Presence> presenceCopy((*lastSentUndirectedPresence)->clone());
presenceCopy->setTo(jid);
sender->sendPresence(presenceCopy);
}
}
diff --git a/Swiften/Presence/SubscriptionManager.cpp b/Swiften/Presence/SubscriptionManager.cpp
index 8de152c..83009e9 100644
--- a/Swiften/Presence/SubscriptionManager.cpp
+++ b/Swiften/Presence/SubscriptionManager.cpp
@@ -1,41 +1,40 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Presence/SubscriptionManager.h>
#include <boost/bind.hpp>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Client/StanzaChannel.h>
namespace Swift {
SubscriptionManager::SubscriptionManager(StanzaChannel* channel) : stanzaChannel(channel) {
stanzaChannel->onPresenceReceived.connect(boost::bind(&SubscriptionManager::handleIncomingPresence, this, _1));
}
SubscriptionManager::~SubscriptionManager() {
stanzaChannel->onPresenceReceived.disconnect(boost::bind(&SubscriptionManager::handleIncomingPresence, this, _1));
}
void SubscriptionManager::cancelSubscription(const JID& jid) {
Presence::ref stanza(new Presence());
stanza->setType(Presence::Unsubscribed);
stanza->setTo(jid);
stanzaChannel->sendPresence(stanza);
}
void SubscriptionManager::confirmSubscription(const JID& jid) {
Presence::ref stanza(new Presence());
stanza->setType(Presence::Subscribed);
stanza->setTo(jid);
stanzaChannel->sendPresence(stanza);
}
void SubscriptionManager::requestSubscription(const JID& jid) {
Presence::ref stanza(new Presence());
stanza->setType(Presence::Subscribe);
diff --git a/Swiften/QA/ConcurrentFileTransferTest/ConcurrentFileTransferTest.cpp b/Swiften/QA/ConcurrentFileTransferTest/ConcurrentFileTransferTest.cpp
index 8122c63..664a87b 100644
--- a/Swiften/QA/ConcurrentFileTransferTest/ConcurrentFileTransferTest.cpp
+++ b/Swiften/QA/ConcurrentFileTransferTest/ConcurrentFileTransferTest.cpp
@@ -1,47 +1,46 @@
/*
* Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <fstream>
#include <map>
#include <string>
#include <boost/filesystem.hpp>
#include <boost/numeric/conversion/cast.hpp>
#include <Swiften/Base/BoostRandomGenerator.h>
#include <Swiften/Base/Debug.h>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Base/sleep.h>
#include <Swiften/Client/Client.h>
#include <Swiften/Client/ClientXMLTracer.h>
#include <Swiften/Disco/ClientDiscoManager.h>
#include <Swiften/Disco/EntityCapsProvider.h>
#include <Swiften/Elements/Presence.h>
#include <Swiften/EventLoop/SimpleEventLoop.h>
#include <Swiften/FileTransfer/FileReadBytestream.h>
#include <Swiften/FileTransfer/FileTransferManager.h>
#include <Swiften/FileTransfer/FileWriteBytestream.h>
#include <Swiften/FileTransfer/OutgoingFileTransfer.h>
#include <Swiften/FileTransfer/ReadBytestream.h>
#include <Swiften/Network/BoostNetworkFactories.h>
#include <Swiften/Network/Timer.h>
#include <Swiften/Network/TimerFactory.h>
using namespace Swift;
static const std::string CLIENT_NAME = "Swiften FT Test";
static const std::string CLIENT_NODE = "http://swift.im";
static std::shared_ptr<SimpleEventLoop> eventLoop;
static std::shared_ptr<BoostNetworkFactories> networkFactories;
BoostRandomGenerator randGen;
enum Candidate {
InBandBytestream = 1,
S5B_Direct = 2,
S5B_Proxied = 4,
diff --git a/Swiften/QA/FileTransferTest/FileTransferTest.cpp b/Swiften/QA/FileTransferTest/FileTransferTest.cpp
index 4cf4048..b627b30 100644
--- a/Swiften/QA/FileTransferTest/FileTransferTest.cpp
+++ b/Swiften/QA/FileTransferTest/FileTransferTest.cpp
@@ -1,46 +1,45 @@
/*
* Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <fstream>
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <boost/numeric/conversion/cast.hpp>
#include <Swiften/Base/BoostRandomGenerator.h>
#include <Swiften/Base/Debug.h>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Base/sleep.h>
#include <Swiften/Client/Client.h>
#include <Swiften/Client/ClientXMLTracer.h>
#include <Swiften/Disco/ClientDiscoManager.h>
#include <Swiften/Disco/EntityCapsProvider.h>
#include <Swiften/Elements/Presence.h>
#include <Swiften/EventLoop/SimpleEventLoop.h>
#include <Swiften/FileTransfer/FileReadBytestream.h>
#include <Swiften/FileTransfer/FileTransferManager.h>
#include <Swiften/FileTransfer/FileWriteBytestream.h>
#include <Swiften/FileTransfer/OutgoingFileTransfer.h>
#include <Swiften/FileTransfer/ReadBytestream.h>
#include <Swiften/Network/BoostNetworkFactories.h>
#include <Swiften/Network/Timer.h>
#include <Swiften/Network/TimerFactory.h>
using namespace Swift;
static const std::string CLIENT_NAME = "Swiften FT Test";
static const std::string CLIENT_NODE = "http://swift.im";
static std::shared_ptr<SimpleEventLoop> eventLoop;
static std::shared_ptr<BoostNetworkFactories> networkFactories;
BoostRandomGenerator randGen;
enum Candidate {
InBandBytestream = 1,
S5B_Direct = 2,
S5B_Proxied = 4,
@@ -319,82 +318,80 @@ static bool runTest(int senderCandidates, int receiverCandidates) {
}
}
std::cout << "expected success: " << expectSuccess << ", wasSuccessful: " << wasSuccessful << std::endl;
testRun.reset();
networkFactories.reset();
eventLoop->runUntilEvents();
eventLoop->stop();
eventLoop.reset();
return success;
}
/**
* This program test file-transfer interop between Swift and itself with various connection candidates.
* The all combinations of the candidates, IBB, S5B (direct) and S5B (proxied), on sender and receiver side are tested.
*/
int main(int argc, char** argv) {
int failedTests = 0;
std::vector<std::pair<int, int> > failedTestPairs;
std::cout << "Swiften File-Transfer Connectivity Test Suite" << std::endl;
if (argc == 1) {
if (getenv("SWIFT_FILETRANSFERTEST_CONFIG")) {
// test configuration described in SWIFT_FILETRANSFERTEST_CONFIG environment variable, e.g. "1:1|2:2"
std::vector<std::string> configurations;
std::string configs_env = std::string(getenv("SWIFT_FILETRANSFERTEST_CONFIG"));
boost::split(configurations, configs_env, boost::is_any_of("|"));
- foreach(const std::string& config, configurations) {
+ for (const auto& config : configurations) {
std::vector<std::string> split_config;
boost::split(split_config, config, boost::is_any_of(":"));
assert(split_config.size() == 2);
int senderCandidates = atoi(split_config[0].c_str());
int receiverCandidates = atoi(split_config[1].c_str());
if (!runTest(senderCandidates, receiverCandidates)) {
failedTests++;
failedTestPairs.push_back(std::pair<int, int>(senderCandidates, receiverCandidates));
}
}
- typedef std::pair<int, int> IntPair;
- foreach(IntPair failedTest, failedTestPairs) {
+ for (auto&& failedTest : failedTestPairs) {
std::cout << "Failed test: " << "( " << failedTest.first << ", " << failedTest.second << ") " << std::endl;
}
}
else {
// test all configurations
for (int n = 0; n < (1 << 7); n++) {
int senderCandidates = n & 0xF;
int receiverCandidates = (n >> 4) & 0xF;
std::cout << "Run test " << n + 1 << " of " << (1 << 7) << ", (" << senderCandidates << ", " << receiverCandidates << ")" << std::endl;
if (!runTest(senderCandidates, receiverCandidates)) {
failedTests++;
failedTestPairs.push_back(std::pair<int, int>(senderCandidates, receiverCandidates));
}
}
- typedef std::pair<int, int> IntPair;
- foreach(IntPair failedTest, failedTestPairs) {
+ for (auto&& failedTest : failedTestPairs) {
std::cout << "Failed test: " << "( " << failedTest.first << ", " << failedTest.second << ") " << std::endl;
}
}
}
else if (argc == 3) {
Log::setLogLevel(Log::debug);
int senderCandidates = atoi(argv[1]);
int receiverCandidates = atoi(argv[2]);
if (!runTest(senderCandidates, receiverCandidates)) {
failedTests++;
}
}
else {
std::cout << "Usage:" << std::endl;
std::cout << "\t- to test all combinations pass no arguments" << std::endl;
std::cout << "\t- to test a specific combination pass two integers describing sender and receiver candidates" << std::endl;
}
return failedTests;
}
diff --git a/Swiften/QA/ProxyProviderTest/ProxyProviderTest.cpp b/Swiften/QA/ProxyProviderTest/ProxyProviderTest.cpp
index 2b6bfa8..53f9e60 100644
--- a/Swiften/QA/ProxyProviderTest/ProxyProviderTest.cpp
+++ b/Swiften/QA/ProxyProviderTest/ProxyProviderTest.cpp
@@ -1,41 +1,40 @@
/*
* Copyright (c) 2010 Thilo Cestonaro
* Licensed under the BSD License.
* See Documentation/Licenses/BSD.txt for more information.
*/
/*
* Copyright (c) 2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <iostream>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Network/PlatformProxyProvider.h>
using namespace Swift;
int main(void)
{
int ret = 0;
HostAddressPort hap;
std::cout << "constructing PlatfromProxyProvider instance ..." << std::endl;
PlatformProxyProvider ppp;
hap = ppp.getSOCKS5Proxy();
std::cout << "SOCKS5 Proxy configured: " << hap.isValid() << std::endl;
if(hap.isValid()) {
std::cout << "SOCKS5 Proxy: " << hap.getAddress().toString() << ":" << hap.getPort() << std::endl;
}
hap = ppp.getHTTPConnectProxy();
std::cout << "HTTPConnect Proxy configured: " << hap.isValid() << std::endl;
if(hap.isValid()) {
std::cout << "HTTPConnect Proxy: " << hap.getAddress().toString() << ":" << hap.getPort() << std::endl;
}
return ret;
}
diff --git a/Swiften/Queries/IQRouter.cpp b/Swiften/Queries/IQRouter.cpp
index e28c2f4..286b65f 100644
--- a/Swiften/Queries/IQRouter.cpp
+++ b/Swiften/Queries/IQRouter.cpp
@@ -1,86 +1,85 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Queries/IQRouter.h>
#include <boost/bind.hpp>
#include <Swiften/Base/Algorithm.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Elements/ErrorPayload.h>
#include <Swiften/Queries/IQChannel.h>
#include <Swiften/Queries/IQHandler.h>
namespace Swift {
static void noop(IQHandler*) {}
IQRouter::IQRouter(IQChannel* channel) : channel_(channel), queueRemoves_(false) {
channel->onIQReceived.connect(boost::bind(&IQRouter::handleIQ, this, _1));
}
IQRouter::~IQRouter() {
channel_->onIQReceived.disconnect(boost::bind(&IQRouter::handleIQ, this, _1));
}
bool IQRouter::isAvailable() {
return channel_->isAvailable();
}
void IQRouter::handleIQ(std::shared_ptr<IQ> iq) {
queueRemoves_ = true;
bool handled = false;
// Go through the handlers in reverse order, to give precedence to the last added handler
std::vector<std::shared_ptr<IQHandler> >::const_reverse_iterator i = handlers_.rbegin();
std::vector<std::shared_ptr<IQHandler> >::const_reverse_iterator rend = handlers_.rend();
for (; i != rend; ++i) {
handled |= (*i)->handleIQ(iq);
if (handled) {
break;
}
}
if (!handled && (iq->getType() == IQ::Get || iq->getType() == IQ::Set) ) {
sendIQ(IQ::createError(iq->getFrom(), iq->getID(), ErrorPayload::FeatureNotImplemented, ErrorPayload::Cancel));
}
processPendingRemoves();
queueRemoves_ = false;
}
void IQRouter::processPendingRemoves() {
- foreach(std::shared_ptr<IQHandler> handler, queuedRemoves_) {
+ for (auto&& handler : queuedRemoves_) {
erase(handlers_, handler);
}
queuedRemoves_.clear();
}
void IQRouter::addHandler(IQHandler* handler) {
addHandler(std::shared_ptr<IQHandler>(handler, noop));
}
void IQRouter::removeHandler(IQHandler* handler) {
removeHandler(std::shared_ptr<IQHandler>(handler, noop));
}
void IQRouter::addHandler(std::shared_ptr<IQHandler> handler) {
handlers_.push_back(handler);
}
void IQRouter::removeHandler(std::shared_ptr<IQHandler> handler) {
if (queueRemoves_) {
queuedRemoves_.push_back(handler);
}
else {
erase(handlers_, handler);
}
}
void IQRouter::sendIQ(std::shared_ptr<IQ> iq) {
if (from_.isValid() && !iq->getFrom().isValid()) {
iq->setFrom(from_);
}
diff --git a/Swiften/Roster/XMPPRosterController.cpp b/Swiften/Roster/XMPPRosterController.cpp
index 57b0645..8ee9755 100644
--- a/Swiften/Roster/XMPPRosterController.cpp
+++ b/Swiften/Roster/XMPPRosterController.cpp
@@ -1,92 +1,91 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Roster/XMPPRosterController.h>
#include <boost/bind.hpp>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Elements/RosterItemPayload.h>
#include <Swiften/Queries/IQRouter.h>
#include <Swiften/Roster/GetRosterRequest.h>
#include <Swiften/Roster/RosterStorage.h>
#include <Swiften/Roster/XMPPRosterImpl.h>
namespace Swift {
/**
* The controller does not gain ownership of these parameters.
*/
XMPPRosterController::XMPPRosterController(IQRouter* iqRouter, XMPPRosterImpl* xmppRoster, RosterStorage* rosterStorage) : iqRouter_(iqRouter), rosterPushResponder_(iqRouter), xmppRoster_(xmppRoster), rosterStorage_(rosterStorage), useVersioning(false) {
rosterPushResponder_.onRosterReceived.connect(boost::bind(&XMPPRosterController::handleRosterReceived, this, _1, false, std::shared_ptr<RosterPayload>()));
rosterPushResponder_.start();
}
XMPPRosterController::~XMPPRosterController() {
rosterPushResponder_.stop();
}
void XMPPRosterController::requestRoster() {
xmppRoster_->clear();
std::shared_ptr<RosterPayload> storedRoster = rosterStorage_->getRoster();
GetRosterRequest::ref rosterRequest;
if (useVersioning) {
std::string version = "";
if (storedRoster && storedRoster->getVersion()) {
version = *storedRoster->getVersion();
}
rosterRequest = GetRosterRequest::create(iqRouter_, version);
}
else {
rosterRequest = GetRosterRequest::create(iqRouter_);
}
rosterRequest->onResponse.connect(boost::bind(&XMPPRosterController::handleRosterReceived, this, _1, true, storedRoster));
rosterRequest->send();
}
void XMPPRosterController::handleRosterReceived(std::shared_ptr<RosterPayload> rosterPayload, bool initial, std::shared_ptr<RosterPayload> previousRoster) {
if (rosterPayload) {
- foreach(const RosterItemPayload& item, rosterPayload->getItems()) {
+ for (const auto& item : rosterPayload->getItems()) {
//Don't worry about the updated case, the XMPPRoster sorts that out.
if (item.getSubscription() == RosterItemPayload::Remove) {
xmppRoster_->removeContact(item.getJID());
} else {
xmppRoster_->addContact(item.getJID(), item.getName(), item.getGroups(), item.getSubscription());
}
}
}
else if (previousRoster) {
// The cached version hasn't changed; emit all items
- foreach(const RosterItemPayload& item, previousRoster->getItems()) {
+ for (const auto& item : previousRoster->getItems()) {
if (item.getSubscription() != RosterItemPayload::Remove) {
xmppRoster_->addContact(item.getJID(), item.getName(), item.getGroups(), item.getSubscription());
}
else {
SWIFT_LOG(error) << "Stored invalid roster item" << std::endl;
}
}
}
if (initial) {
xmppRoster_->onInitialRosterPopulated();
}
if (rosterPayload && rosterPayload->getVersion() && useVersioning) {
saveRoster(*rosterPayload->getVersion());
}
}
void XMPPRosterController::saveRoster(const std::string& version) {
std::vector<XMPPRosterItem> items = xmppRoster_->getItems();
std::shared_ptr<RosterPayload> roster(new RosterPayload());
roster->setVersion(version);
- foreach(const XMPPRosterItem& item, items) {
+ for (const auto& item : items) {
roster->addItem(RosterItemPayload(item.getJID(), item.getName(), item.getSubscription(), item.getGroups()));
}
rosterStorage_->setRoster(roster);
}
}
diff --git a/Swiften/Roster/XMPPRosterImpl.cpp b/Swiften/Roster/XMPPRosterImpl.cpp
index 9a2ea7a..74f634f 100644
--- a/Swiften/Roster/XMPPRosterImpl.cpp
+++ b/Swiften/Roster/XMPPRosterImpl.cpp
@@ -1,40 +1,38 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Roster/XMPPRosterImpl.h>
-#include <Swiften/Base/foreach.h>
-
namespace Swift {
XMPPRosterImpl::XMPPRosterImpl() {
}
XMPPRosterImpl::~XMPPRosterImpl() {
}
void XMPPRosterImpl::addContact(const JID& jid, const std::string& name, const std::vector<std::string>& groups, RosterItemPayload::Subscription subscription) {
JID bareJID(jid.toBare());
std::map<JID, XMPPRosterItem>::iterator i = entries_.find(bareJID);
if (i != entries_.end()) {
std::string oldName = i->second.getName();
std::vector<std::string> oldGroups = i->second.getGroups();
i->second = XMPPRosterItem(jid, name, groups, subscription);
onJIDUpdated(bareJID, oldName, oldGroups);
}
else {
entries_.insert(std::make_pair(bareJID, XMPPRosterItem(jid, name, groups, subscription)));
onJIDAdded(bareJID);
}
}
void XMPPRosterImpl::removeContact(const JID& jid) {
entries_.erase(JID(jid.toBare()));
onJIDRemoved(jid);
}
void XMPPRosterImpl::clear() {
@@ -51,57 +49,57 @@ std::string XMPPRosterImpl::getNameForJID(const JID& jid) const {
if (i != entries_.end()) {
return i->second.getName();
}
else {
return "";
}
}
std::vector<std::string> XMPPRosterImpl::getGroupsForJID(const JID& jid) {
std::map<JID, XMPPRosterItem>::iterator i = entries_.find(jid.toBare());
if (i != entries_.end()) {
return i->second.getGroups();
}
else {
return std::vector<std::string>();
}
}
RosterItemPayload::Subscription XMPPRosterImpl::getSubscriptionStateForJID(const JID& jid) {
std::map<JID, XMPPRosterItem>::iterator i = entries_.find(jid.toBare());
if (i != entries_.end()) {
return i->second.getSubscription();
}
else {
return RosterItemPayload::None;
}
}
std::vector<XMPPRosterItem> XMPPRosterImpl::getItems() const {
std::vector<XMPPRosterItem> result;
- foreach(const RosterMap::value_type& entry, entries_) {
+ for (const auto& entry : entries_) {
result.push_back(entry.second);
}
return result;
}
boost::optional<XMPPRosterItem> XMPPRosterImpl::getItem(const JID& jid) const {
std::map<JID, XMPPRosterItem>::const_iterator i = entries_.find(jid.toBare());
if (i != entries_.end()) {
return i->second;
}
else {
return boost::optional<XMPPRosterItem>();
}
}
std::set<std::string> XMPPRosterImpl::getGroups() const {
std::set<std::string> result;
- foreach(const RosterMap::value_type& entry, entries_) {
+ for (const auto& entry : entries_) {
std::vector<std::string> groups = entry.second.getGroups();
result.insert(groups.begin(), groups.end());
}
return result;
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/BytestreamsSerializer.cpp b/Swiften/Serializer/PayloadSerializers/BytestreamsSerializer.cpp
index 93eab75..78bb0eb 100644
--- a/Swiften/Serializer/PayloadSerializers/BytestreamsSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/BytestreamsSerializer.cpp
@@ -1,41 +1,40 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/BytestreamsSerializer.h>
#include <memory>
#include <boost/lexical_cast.hpp>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/PayloadSerializerCollection.h>
#include <Swiften/Serializer/XML/XMLElement.h>
namespace Swift {
BytestreamsSerializer::BytestreamsSerializer() {
}
std::string BytestreamsSerializer::serializePayload(std::shared_ptr<Bytestreams> bytestreams) const {
XMLElement queryElement("query", "http://jabber.org/protocol/bytestreams");
queryElement.setAttribute("sid", bytestreams->getStreamID());
- foreach(const Bytestreams::StreamHost& streamHost, bytestreams->getStreamHosts()) {
+ for (const auto& streamHost : bytestreams->getStreamHosts()) {
std::shared_ptr<XMLElement> streamHostElement(new XMLElement("streamhost"));
streamHostElement->setAttribute("host", streamHost.host);
streamHostElement->setAttribute("jid", streamHost.jid.toString());
streamHostElement->setAttribute("port", boost::lexical_cast<std::string>(streamHost.port));
queryElement.addNode(streamHostElement);
}
if (bytestreams->getUsedStreamHost()) {
std::shared_ptr<XMLElement> streamHostElement(new XMLElement("streamhost-used"));
streamHostElement->setAttribute("jid", *bytestreams->getUsedStreamHost());
queryElement.addNode(streamHostElement);
}
return queryElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/CommandSerializer.cpp b/Swiften/Serializer/PayloadSerializers/CommandSerializer.cpp
index e1dd6ed..25a70f6 100644
--- a/Swiften/Serializer/PayloadSerializers/CommandSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/CommandSerializer.cpp
@@ -1,90 +1,89 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/CommandSerializer.h>
#include <memory>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/PayloadSerializers/FormSerializer.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
namespace Swift {
CommandSerializer::CommandSerializer() {
}
std::string CommandSerializer::serializePayload(std::shared_ptr<Command> command) const {
XMLElement commandElement("command", "http://jabber.org/protocol/commands");
commandElement.setAttribute("node", command->getNode());
if (!command->getSessionID().empty()) {
commandElement.setAttribute("sessionid", command->getSessionID());
}
std::string action = actionToString(command->getAction());
if (!action.empty()) {
commandElement.setAttribute("action", action);
}
std::string status;
switch (command->getStatus()) {
case Command::Executing: status = "executing";break;
case Command::Completed: status = "completed";break;
case Command::Canceled: status = "canceled";break;
case Command::NoStatus: break;
}
if (!status.empty()) {
commandElement.setAttribute("status", status);
}
if (command->getAvailableActions().size() > 0) {
std::string actions = "<actions";
std::string executeAction = actionToString(command->getExecuteAction());
if (!executeAction.empty()) {
actions += " execute='" + executeAction + "'";
}
actions += ">";
- foreach (Command::Action action, command->getAvailableActions()) {
+ for (const auto& action : command->getAvailableActions()) {
actions += "<" + actionToString(action) + "/>";
}
actions += "</actions>";
commandElement.addNode(std::make_shared<XMLRawTextNode>(actions));
}
- foreach (Command::Note note, command->getNotes()) {
+ for (const auto& note : command->getNotes()) {
std::shared_ptr<XMLElement> noteElement(new XMLElement("note"));
std::string type;
switch (note.type) {
case Command::Note::Info: type = "info"; break;
case Command::Note::Warn: type = "warn"; break;
case Command::Note::Error: type = "error"; break;
}
if (!type.empty()) {
noteElement->setAttribute("type", type);
}
noteElement->addNode(std::make_shared<XMLTextNode>(note.note));
commandElement.addNode(noteElement);
}
Form::ref form = command->getForm();
if (form) {
commandElement.addNode(std::make_shared<XMLRawTextNode>(FormSerializer().serialize(form)));
}
return commandElement.serialize();
}
std::string CommandSerializer::actionToString(Command::Action action) const {
std::string string;
switch (action) {
case Command::Cancel: string = "cancel"; break;
case Command::Execute: string = "execute"; break;
case Command::Complete: string = "complete"; break;
case Command::Prev: string = "prev"; break;
case Command::Next: string = "next"; break;
case Command::NoAction: break;
diff --git a/Swiften/Serializer/PayloadSerializers/DiscoInfoSerializer.cpp b/Swiften/Serializer/PayloadSerializers/DiscoInfoSerializer.cpp
index 73e2585..06cad2b 100644
--- a/Swiften/Serializer/PayloadSerializers/DiscoInfoSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/DiscoInfoSerializer.cpp
@@ -1,47 +1,46 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/DiscoInfoSerializer.h>
#include <memory>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/PayloadSerializers/FormSerializer.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
namespace Swift {
DiscoInfoSerializer::DiscoInfoSerializer() : GenericPayloadSerializer<DiscoInfo>() {
}
std::string DiscoInfoSerializer::serializePayload(std::shared_ptr<DiscoInfo> discoInfo) const {
XMLElement queryElement("query", "http://jabber.org/protocol/disco#info");
if (!discoInfo->getNode().empty()) {
queryElement.setAttribute("node", discoInfo->getNode());
}
- foreach(const DiscoInfo::Identity& identity, discoInfo->getIdentities()) {
+ for (const auto& identity : discoInfo->getIdentities()) {
std::shared_ptr<XMLElement> identityElement(new XMLElement("identity"));
if (!identity.getLanguage().empty()) {
identityElement->setAttribute("xml:lang", identity.getLanguage());
}
identityElement->setAttribute("category", identity.getCategory());
identityElement->setAttribute("name", identity.getName());
identityElement->setAttribute("type", identity.getType());
queryElement.addNode(identityElement);
}
- foreach(const std::string& feature, discoInfo->getFeatures()) {
+ for (const auto& feature : discoInfo->getFeatures()) {
std::shared_ptr<XMLElement> featureElement(new XMLElement("feature"));
featureElement->setAttribute("var", feature);
queryElement.addNode(featureElement);
}
- foreach(const Form::ref extension, discoInfo->getExtensions()) {
+ for (const auto& extension : discoInfo->getExtensions()) {
queryElement.addNode(std::make_shared<XMLRawTextNode>(FormSerializer().serialize(extension)));
}
return queryElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/DiscoItemsSerializer.cpp b/Swiften/Serializer/PayloadSerializers/DiscoItemsSerializer.cpp
index 1b734dc..a8eafef 100644
--- a/Swiften/Serializer/PayloadSerializers/DiscoItemsSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/DiscoItemsSerializer.cpp
@@ -1,36 +1,35 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/DiscoItemsSerializer.h>
#include <memory>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/XML/XMLElement.h>
namespace Swift {
DiscoItemsSerializer::DiscoItemsSerializer() : GenericPayloadSerializer<DiscoItems>() {
}
std::string DiscoItemsSerializer::serializePayload(std::shared_ptr<DiscoItems> discoItems) const {
XMLElement queryElement("query", "http://jabber.org/protocol/disco#items");
if (!discoItems->getNode().empty()) {
queryElement.setAttribute("node", discoItems->getNode());
}
- foreach(const DiscoItems::Item& item, discoItems->getItems()) {
+ for (const auto& item : discoItems->getItems()) {
std::shared_ptr<XMLElement> itemElement(new XMLElement("item"));
itemElement->setAttribute("name", item.getName());
itemElement->setAttribute("jid", item.getJID());
if (!item.getNode().empty()) {
itemElement->setAttribute("node", item.getNode());
}
queryElement.addNode(itemElement);
}
return queryElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/FormSerializer.cpp b/Swiften/Serializer/PayloadSerializers/FormSerializer.cpp
index ed010b4..f723ead 100644
--- a/Swiften/Serializer/PayloadSerializers/FormSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/FormSerializer.cpp
@@ -1,208 +1,209 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/FormSerializer.h>
#include <memory>
#include <string>
#include <Swiften/Base/Algorithm.h>
#include <Swiften/Base/String.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
using namespace Swift;
namespace {
template<typename T> void serializeValueAsString(std::shared_ptr<FormField> field, std::shared_ptr<XMLElement> parent) {
std::string value = std::dynamic_pointer_cast<T>(field)->getValue();
if (!value.empty()) {
std::shared_ptr<XMLElement> valueElement(new XMLElement("value"));
valueElement->addNode(XMLTextNode::create(value));
parent->addNode(valueElement);
}
}
}
namespace Swift {
FormSerializer::FormSerializer() : GenericPayloadSerializer<Form>() {}
std::string FormSerializer::serializePayload(std::shared_ptr<Form> form) const {
if (!form) {
return "";
}
std::shared_ptr<XMLElement> formElement(new XMLElement("x", "jabber:x:data"));
std::string type;
switch (form->getType()) {
case Form::FormType: type = "form"; break;
case Form::SubmitType: type = "submit"; break;
case Form::CancelType: type = "cancel"; break;
case Form::ResultType: type = "result"; break;
}
formElement->setAttribute("type", type);
if (!form->getTitle().empty()) {
multiLineify(form->getTitle(), "title", formElement);
}
if (!form->getInstructions().empty()) {
multiLineify(form->getInstructions(), "instructions", formElement);
}
- foreach(std::shared_ptr<FormPage> page, form->getPages()) {
+ for (const auto& page : form->getPages()) {
formElement->addNode(pageToXML(page));
}
- foreach(std::shared_ptr<FormField> field, form->getFields()) {
+ for (const auto& field : form->getFields()) {
formElement->addNode(fieldToXML(field, true));
}
if (!form->getReportedFields().empty()) {
std::shared_ptr<XMLElement> reportedElement(new XMLElement("reported"));
- foreach(FormField::ref field, form->getReportedFields()) {
+ for (const auto& field : form->getReportedFields()) {
reportedElement->addNode(fieldToXML(field, true));
}
formElement->addNode(reportedElement);
}
- foreach(Form::FormItem item, form->getItems()) {
+ for (const auto& item : form->getItems()) {
std::shared_ptr<XMLElement> itemElement(new XMLElement("item"));
- foreach(FormField::ref field, item) {
+ for (const auto& field : item) {
itemElement->addNode(fieldToXML(field, false));
}
formElement->addNode(itemElement);
}
- foreach(const FormText::text text, form->getTextElements()) {
+ for (const auto& text : form->getTextElements()) {
formElement->addNode(textToXML(text));
}
- foreach (std::shared_ptr<FormField> field, fields_) {
+ for (const auto& field : fields_) {
formElement->addNode(fieldToXML(field,true));
}
return formElement->serialize();
}
std::shared_ptr<XMLElement> FormSerializer::textToXML(std::shared_ptr<FormText> text) const {
std::shared_ptr<XMLElement> textElement (new XMLElement("text"));
textElement->addNode(std::make_shared<XMLTextNode>(text->getTextString()));
return textElement;
}
std::shared_ptr<XMLElement> FormSerializer::fieldRefToXML(const std::string& ref) const {
std::shared_ptr<XMLElement> fieldRefElement(new XMLElement("fieldref"));
fieldRefElement->setAttribute("var", ref);
return fieldRefElement;
}
std::shared_ptr<XMLElement> FormSerializer::pageToXML(std::shared_ptr<FormPage> page) const {
std::shared_ptr<XMLElement> pageElement(new XMLElement("page"));
pageElement->setAttribute("xmlns", "http://jabber.org/protocol/xdata-layout");
if (!page->getLabel().empty()) {
pageElement->setAttribute("label", page->getLabel());
}
- foreach(const FormText::text text, page->getTextElements()) {
+ for (const auto& text : page->getTextElements()) {
pageElement->addNode(textToXML(text));
}
- foreach (const std::shared_ptr<FormField> field, page->getFields()) {
+ for (const auto& field : page->getFields()) {
pageElement->addNode(fieldRefToXML(field->getName()));
fields_.push_back(field);
}
- foreach(const FormReportedRef::ref reportedRef, page->getReportedRefs()) {
+ for (const auto& reportedRef: page->getReportedRefs()) {
+ (void)reportedRef;
pageElement->addNode(std::make_shared<XMLElement>("reportedref"));
}
- foreach(const FormSection::section section, page->getChildSections()) {
+ for (const auto& section : page->getChildSections()) {
pageElement->addNode(sectionToXML(section));
}
return pageElement;
}
std::shared_ptr<XMLElement> FormSerializer::sectionToXML(std::shared_ptr<FormSection> section) const {
std::shared_ptr<XMLElement> sectionElement(new XMLElement("section"));
if (!section->getLabel().empty()) {
sectionElement->setAttribute("label", section->getLabel());
}
- foreach(const FormText::text text, section->getTextElements()) {
+ for (const auto& text : section->getTextElements()) {
sectionElement->addNode(textToXML(text));
}
- foreach(const std::shared_ptr<FormField> field, section->getFields()) {
+ for (const auto& field : section->getFields()) {
sectionElement->addNode(fieldRefToXML(field->getName()));
fields_.push_back(field);
}
- foreach(const FormReportedRef::ref reportedRef, section->getReportedRefs()) {
+ for (const auto& reportedRef : section->getReportedRefs()) {
+ (void)reportedRef;
sectionElement->addNode(std::make_shared<XMLElement>("reportedref"));
}
- foreach(const FormSection::section childSection, section->getChildSections()) {
+ for (const auto& childSection : section->getChildSections()) {
sectionElement->addNode(sectionToXML(childSection));
}
return sectionElement;
}
std::shared_ptr<XMLElement> FormSerializer::fieldToXML(std::shared_ptr<FormField> field, bool withTypeAttribute) const {
std::shared_ptr<XMLElement> fieldElement(new XMLElement("field"));
if (!field->getName().empty()) {
fieldElement->setAttribute("var", field->getName());
}
if (!field->getLabel().empty()) {
fieldElement->setAttribute("label", field->getLabel());
}
if (field->getRequired()) {
fieldElement->addNode(std::make_shared<XMLElement>("required"));
}
if (!field->getDescription().empty()) {
std::shared_ptr<XMLElement> descriptionElement(new XMLElement("desc"));
descriptionElement->addNode(std::make_shared<XMLTextNode>(field->getDescription()));
fieldElement->addNode(descriptionElement);
}
// Set the value and type
std::string fieldType;
switch (field->getType()) {
case FormField::UnknownType: fieldType = ""; break;
case FormField::BooleanType: fieldType = "boolean"; break;
case FormField::FixedType: fieldType = "fixed"; break;
case FormField::HiddenType: fieldType = "hidden"; break;
case FormField::ListSingleType: fieldType = "list-single"; break;
case FormField::TextMultiType: fieldType = "text-multi"; break;
case FormField::TextPrivateType: fieldType = "text-private"; break;
case FormField::TextSingleType: fieldType = "text-single"; break;
case FormField::JIDSingleType: fieldType = "jid-single"; break;
case FormField::JIDMultiType: fieldType = "jid-multi"; break;
case FormField::ListMultiType: fieldType = "list-multi"; break;
}
if (!fieldType.empty() && withTypeAttribute) {
fieldElement->setAttribute("type", fieldType);
}
- foreach (const std::string& value, field->getValues()) {
+ for (const auto& value : field->getValues()) {
std::shared_ptr<XMLElement> valueElement = std::make_shared<XMLElement>("value");
valueElement->addNode(std::make_shared<XMLTextNode>(value));
fieldElement->addNode(valueElement);
}
- foreach (const FormField::Option& option, field->getOptions()) {
+ for (const auto& option : field->getOptions()) {
std::shared_ptr<XMLElement> optionElement(new XMLElement("option"));
if (!option.label.empty()) {
optionElement->setAttribute("label", option.label);
}
std::shared_ptr<XMLElement> valueElement(new XMLElement("value"));
valueElement->addNode(XMLTextNode::create(option.value));
optionElement->addNode(valueElement);
fieldElement->addNode(optionElement);
}
return fieldElement;
}
void FormSerializer::multiLineify(const std::string& text, const std::string& elementName, std::shared_ptr<XMLElement> element) const {
std::string unRdText(text);
erase(unRdText, '\r');
std::vector<std::string> lines = String::split(unRdText, '\n');
- foreach (std::string line, lines) {
+ for (const auto& line : lines) {
std::shared_ptr<XMLElement> lineElement(new XMLElement(elementName));
lineElement->addNode(std::make_shared<XMLTextNode>(line));
element->addNode(lineElement);
}
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.cpp b/Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.cpp
index 175de1e..cf0b54c 100644
--- a/Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.cpp
+++ b/Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.cpp
@@ -1,39 +1,38 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Elements/BlockListPayload.h>
#include <Swiften/Elements/BlockPayload.h>
#include <Swiften/Elements/UnblockPayload.h>
#include <Swiften/Serializer/PayloadSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/BlockSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/BodySerializer.h>
#include <Swiften/Serializer/PayloadSerializers/BytestreamsSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/CapsInfoSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/CarbonsDisableSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/CarbonsEnableSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/CarbonsPrivateSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/CarbonsReceivedSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/CarbonsSentSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/ChatStateSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/CommandSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/DelaySerializer.h>
#include <Swiften/Serializer/PayloadSerializers/DeliveryReceiptRequestSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/DeliveryReceiptSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/DiscoInfoSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/DiscoItemsSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/ErrorSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/FormSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/ForwardedSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/IBBSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/IdleSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/InBandRegistrationPayloadSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/IsodeIQDelegationSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/JingleContentPayloadSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/JingleFileTransferDescriptionSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/JingleFileTransferFileInfoSerializer.h>
@@ -138,44 +137,44 @@ FullPayloadSerializerCollection::FullPayloadSerializerCollection() {
serializers_.push_back(new JingleFileTransferFileInfoSerializer());
serializers_.push_back(new JingleContentPayloadSerializer());
serializers_.push_back(new JingleFileTransferDescriptionSerializer());
serializers_.push_back(new JingleFileTransferHashSerializer());
serializers_.push_back(new JingleIBBTransportPayloadSerializer());
serializers_.push_back(new JingleS5BTransportPayloadSerializer());
serializers_.push_back(new JinglePayloadSerializer(this));
serializers_.push_back(new S5BProxyRequestSerializer());
serializers_.push_back(new DeliveryReceiptSerializer());
serializers_.push_back(new DeliveryReceiptRequestSerializer());
serializers_.push_back(new PubSubSerializer(this));
serializers_.push_back(new PubSubEventSerializer(this));
serializers_.push_back(new PubSubOwnerPubSubSerializer(this));
serializers_.push_back(new PubSubErrorSerializer());
serializers_.push_back(new ResultSetSerializer());
serializers_.push_back(new ForwardedSerializer(this));
serializers_.push_back(new MAMResultSerializer(this));
serializers_.push_back(new MAMQuerySerializer());
serializers_.push_back(new MAMFinSerializer());
serializers_.push_back(new CarbonsDisableSerializer());
serializers_.push_back(new CarbonsEnableSerializer());
serializers_.push_back(new CarbonsPrivateSerializer());
serializers_.push_back(new CarbonsReceivedSerializer(this));
serializers_.push_back(new CarbonsSentSerializer(this));
serializers_.push_back(new IsodeIQDelegationSerializer(this));
- foreach(PayloadSerializer* serializer, serializers_) {
+ for (auto serializer : serializers_) {
addSerializer(serializer);
}
}
FullPayloadSerializerCollection::~FullPayloadSerializerCollection() {
- foreach(PayloadSerializer* serializer, serializers_) {
+ for (auto serializer : serializers_) {
removeSerializer(serializer);
delete serializer;
}
serializers_.clear();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/IBBSerializer.cpp b/Swiften/Serializer/PayloadSerializers/IBBSerializer.cpp
index 36d82a2..e41ff8c 100644
--- a/Swiften/Serializer/PayloadSerializers/IBBSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/IBBSerializer.cpp
@@ -1,44 +1,43 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/IBBSerializer.h>
#include <cassert>
#include <memory>
#include <boost/lexical_cast.hpp>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
#include <Swiften/StringCodecs/Base64.h>
namespace Swift {
IBBSerializer::IBBSerializer() {
}
std::string IBBSerializer::serializePayload(std::shared_ptr<IBB> ibb) const {
switch(ibb->getAction()) {
case IBB::Data: {
XMLElement ibbElement("data", "http://jabber.org/protocol/ibb");
ibbElement.setAttribute("sid", ibb->getStreamID());
if (ibb->getSequenceNumber() >= 0) {
ibbElement.setAttribute("seq", boost::lexical_cast<std::string>(ibb->getSequenceNumber()));
}
ibbElement.addNode(std::make_shared<XMLTextNode>(Base64::encode(ibb->getData())));
return ibbElement.serialize();
}
case IBB::Open: {
XMLElement ibbElement("open", "http://jabber.org/protocol/ibb");
ibbElement.setAttribute("sid", ibb->getStreamID());
switch (ibb->getStanzaType()) {
case IBB::IQStanza: ibbElement.setAttribute("stanza", "iq"); break;
case IBB::MessageStanza: ibbElement.setAttribute("stanza", "message"); break;
}
assert(ibb->getBlockSize() > 0);
ibbElement.setAttribute("block-size", boost::lexical_cast<std::string>(ibb->getBlockSize()));
return ibbElement.serialize();
diff --git a/Swiften/Serializer/PayloadSerializers/InBandRegistrationPayloadSerializer.cpp b/Swiften/Serializer/PayloadSerializers/InBandRegistrationPayloadSerializer.cpp
index 31b023f..04b7c56 100644
--- a/Swiften/Serializer/PayloadSerializers/InBandRegistrationPayloadSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/InBandRegistrationPayloadSerializer.cpp
@@ -1,41 +1,40 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/InBandRegistrationPayloadSerializer.h>
#include <memory>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/PayloadSerializers/FormSerializer.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
namespace Swift {
InBandRegistrationPayloadSerializer::InBandRegistrationPayloadSerializer() {
}
std::string InBandRegistrationPayloadSerializer::serializePayload(std::shared_ptr<InBandRegistrationPayload> registration) const {
XMLElement registerElement("query", "jabber:iq:register");
if (registration->isRegistered()) {
registerElement.addNode(XMLElement::ref(new XMLElement("registered")));
}
if (registration->isRemove()) {
registerElement.addNode(XMLElement::ref(new XMLElement("remove")));
}
if (registration->getInstructions()) {
registerElement.addNode(XMLElement::ref(new XMLElement("instructions", "", *registration->getInstructions())));
}
if (registration->getUsername()) {
registerElement.addNode(XMLElement::ref(new XMLElement("username", "", *registration->getUsername())));
}
if (registration->getNick()) {
diff --git a/Swiften/Serializer/PayloadSerializers/JingleContentPayloadSerializer.cpp b/Swiften/Serializer/PayloadSerializers/JingleContentPayloadSerializer.cpp
index 02e0f2a..39eb149 100644
--- a/Swiften/Serializer/PayloadSerializers/JingleContentPayloadSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/JingleContentPayloadSerializer.cpp
@@ -1,81 +1,80 @@
/*
* Copyright (c) 2011 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 <Swiften/Serializer/PayloadSerializers/JingleContentPayloadSerializer.h>
#include <memory>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/PayloadSerializers/JingleFileTransferDescriptionSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/JingleS5BTransportPayloadSerializer.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLNode.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
namespace Swift {
JingleContentPayloadSerializer::JingleContentPayloadSerializer() {
}
std::string JingleContentPayloadSerializer::serializePayload(std::shared_ptr<JingleContentPayload> payload) const {
XMLElement payloadXML("content");
payloadXML.setAttribute("creator", creatorToString(payload->getCreator()));
payloadXML.setAttribute("name", payload->getName());
if (!payload->getDescriptions().empty()) {
// JingleFileTransferDescription
JingleFileTransferDescriptionSerializer ftSerializer;
JingleFileTransferDescription::ref filetransfer;
- foreach(JingleDescription::ref desc, payload->getDescriptions()) {
+ for (auto&& desc : payload->getDescriptions()) {
if ((filetransfer = std::dynamic_pointer_cast<JingleFileTransferDescription>(desc))) {
payloadXML.addNode(std::make_shared<XMLRawTextNode>(ftSerializer.serializePayload(filetransfer)));
}
}
}
if (!payload->getTransports().empty()) {
// JingleIBBTransportPayload
JingleIBBTransportPayloadSerializer ibbSerializer;
JingleIBBTransportPayload::ref ibb;
// JingleS5BTransportPayload
JingleS5BTransportPayloadSerializer s5bSerializer;
JingleS5BTransportPayload::ref s5b;
- foreach(JingleTransportPayload::ref transport, payload->getTransports()) {
+ for (auto&& transport : payload->getTransports()) {
if ((ibb = std::dynamic_pointer_cast<JingleIBBTransportPayload>(transport))) {
payloadXML.addNode(std::make_shared<XMLRawTextNode>(ibbSerializer.serializePayload(ibb)));
} else if ((s5b = std::dynamic_pointer_cast<JingleS5BTransportPayload>(transport))) {
payloadXML.addNode(std::make_shared<XMLRawTextNode>(s5bSerializer.serializePayload(s5b)));
}
}
}
return payloadXML.serialize();
}
std::string JingleContentPayloadSerializer::creatorToString(JingleContentPayload::Creator creator) const {
switch(creator) {
case JingleContentPayload::InitiatorCreator:
return "initiator";
case JingleContentPayload::ResponderCreator:
return "responder";
case JingleContentPayload::UnknownCreator:
SWIFT_LOG(error) << "Serializing unknown creator value.";
return "ERROR ERROR ERROR";
}
assert(false);
return "";
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/JingleFileTransferDescriptionSerializer.cpp b/Swiften/Serializer/PayloadSerializers/JingleFileTransferDescriptionSerializer.cpp
index b002482..27e3b33 100644
--- a/Swiften/Serializer/PayloadSerializers/JingleFileTransferDescriptionSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/JingleFileTransferDescriptionSerializer.cpp
@@ -1,41 +1,40 @@
/*
* 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 <Swiften/Serializer/PayloadSerializers/JingleFileTransferDescriptionSerializer.h>
#include <memory>
#include <boost/lexical_cast.hpp>
#include <Swiften/Base/DateTime.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/PayloadSerializers/JingleFileTransferFileInfoSerializer.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLNode.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
#include <Swiften/StringCodecs/Base64.h>
namespace Swift {
JingleFileTransferDescriptionSerializer::JingleFileTransferDescriptionSerializer() {
}
std::string JingleFileTransferDescriptionSerializer::serializePayload(std::shared_ptr<JingleFileTransferDescription> payload) const {
XMLElement description("description", "urn:xmpp:jingle:apps:file-transfer:4");
JingleFileTransferFileInfoSerializer fileInfoSerializer;
std::shared_ptr<XMLRawTextNode> fileInfoXML = std::make_shared<XMLRawTextNode>(fileInfoSerializer.serialize(std::make_shared<JingleFileTransferFileInfo>(payload->getFileInfo())));
description.addNode(fileInfoXML);
return description.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/JingleFileTransferFileInfoSerializer.cpp b/Swiften/Serializer/PayloadSerializers/JingleFileTransferFileInfoSerializer.cpp
index d78d7df..35a0a6e 100644
--- a/Swiften/Serializer/PayloadSerializers/JingleFileTransferFileInfoSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/JingleFileTransferFileInfoSerializer.cpp
@@ -1,66 +1,65 @@
/*
* Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/JingleFileTransferFileInfoSerializer.h>
#include <memory>
#include <boost/lexical_cast.hpp>
#include <Swiften/Base/DateTime.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
#include <Swiften/StringCodecs/Base64.h>
namespace Swift {
JingleFileTransferFileInfoSerializer::JingleFileTransferFileInfoSerializer() {
}
std::string JingleFileTransferFileInfoSerializer::serializePayload(std::shared_ptr<JingleFileTransferFileInfo> fileInfo) const {
XMLElement fileElement("file", "");
if (fileInfo->getDate() != stringToDateTime("")) {
fileElement.addNode(std::make_shared<XMLElement>("date", "", dateTimeToString(fileInfo->getDate())));
}
if (!fileInfo->getDescription().empty()) {
fileElement.addNode(std::make_shared<XMLElement>("desc", "", fileInfo->getDescription()));
}
if (!fileInfo->getMediaType().empty()) {
fileElement.addNode(std::make_shared<XMLElement>("media-type", "", fileInfo->getMediaType()));
}
if (!fileInfo->getName().empty()) {
fileElement.addNode(std::make_shared<XMLElement>("name", "", fileInfo->getName()));
}
if (fileInfo->getSupportsRangeRequests()) {
std::shared_ptr<XMLElement> range = std::make_shared<XMLElement>("range");
if (fileInfo->getRangeOffset() != 0) {
range->setAttribute("offset", boost::lexical_cast<std::string>(fileInfo->getRangeOffset()));
}
fileElement.addNode(range);
}
if (fileInfo->getSize() > 0) {
fileElement.addNode(std::make_shared<XMLElement>("size", "", boost::lexical_cast<std::string>(fileInfo->getSize())));
}
- foreach (JingleFileTransferFileInfo::HashElementMap::value_type hashElement, fileInfo->getHashes()) {
+ for (const auto& hashElement : fileInfo->getHashes()) {
std::shared_ptr<XMLElement> hash = std::make_shared<XMLElement>("hash", "urn:xmpp:hashes:1", Base64::encode(hashElement.second));
hash->setAttribute("algo", hashElement.first);
fileElement.addNode(hash);
}
return fileElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/JingleFileTransferHashSerializer.cpp b/Swiften/Serializer/PayloadSerializers/JingleFileTransferHashSerializer.cpp
index 1f6ead7..7629721 100644
--- a/Swiften/Serializer/PayloadSerializers/JingleFileTransferHashSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/JingleFileTransferHashSerializer.cpp
@@ -1,46 +1,45 @@
/*
* 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 <Swiften/Serializer/PayloadSerializers/JingleFileTransferHashSerializer.h>
#include <map>
#include <memory>
#include <string>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/PayloadSerializers/JingleFileTransferFileInfoSerializer.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLNode.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
namespace Swift {
JingleFileTransferHashSerializer::JingleFileTransferHashSerializer() {
}
std::string JingleFileTransferHashSerializer::serializePayload(std::shared_ptr<JingleFileTransferHash> payload) const {
// code for version urn:xmpp:jingle:apps:file-transfer:2
//XMLElement hash("hash", "urn:xmpp:jingle:apps:file-transfer:info:2", payload->getHash());
// code for version urn:xmpp:jingle:apps:file-transfer:4
XMLElement checksum("checksum", "urn:xmpp:jingle:apps:file-transfer:4");
JingleFileTransferFileInfoSerializer fileSerializer;
std::shared_ptr<XMLRawTextNode> file = std::make_shared<XMLRawTextNode>(fileSerializer.serialize(std::make_shared<JingleFileTransferFileInfo>(payload->getFileInfo())));
checksum.addNode(file);
return checksum.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.cpp b/Swiften/Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.cpp
index 52e6c16..9930e44 100644
--- a/Swiften/Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.cpp
@@ -1,39 +1,38 @@
/*
* Copyright (c) 2011 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 <Swiften/Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.h>
#include <memory>
#include <boost/lexical_cast.hpp>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLNode.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
namespace Swift {
JingleIBBTransportPayloadSerializer::JingleIBBTransportPayloadSerializer() {
}
std::string JingleIBBTransportPayloadSerializer::serializePayload(std::shared_ptr<JingleIBBTransportPayload> payload) const {
XMLElement payloadXML("transport", "urn:xmpp:jingle:transports:ibb:1");
if (payload->getBlockSize()) {
payloadXML.setAttribute("block-size", boost::lexical_cast<std::string>(*payload->getBlockSize()));
}
payloadXML.setAttribute("sid", payload->getSessionID());
return payloadXML.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.cpp b/Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.cpp
index 8b37929..aaac757 100644
--- a/Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.cpp
@@ -1,74 +1,73 @@
/*
* 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 <Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.h>
#include <memory>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Elements/JingleContentPayload.h>
#include <Swiften/Elements/JingleFileTransferDescription.h>
#include <Swiften/Elements/JingleFileTransferHash.h>
#include <Swiften/Elements/JingleIBBTransportPayload.h>
#include <Swiften/Elements/JinglePayload.h>
#include <Swiften/Serializer/PayloadSerializerCollection.h>
#include <Swiften/Serializer/PayloadSerializers/JingleContentPayloadSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/JingleFileTransferHashSerializer.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLNode.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
namespace Swift {
JinglePayloadSerializer::JinglePayloadSerializer(PayloadSerializerCollection* serializers) : serializers(serializers) {
}
std::string JinglePayloadSerializer::serializePayload(std::shared_ptr<JinglePayload> payload) const {
XMLElement jinglePayload("jingle", "urn:xmpp:jingle:1");
jinglePayload.setAttribute("action", actionToString(payload->getAction()));
jinglePayload.setAttribute("initiator", payload->getInitiator());
jinglePayload.setAttribute("sid", payload->getSessionID());
std::vector<std::shared_ptr<Payload> > payloads = payload->getPayloads();
if (!payloads.empty()) {
- foreach(std::shared_ptr<Payload> subPayload, payloads) {
+ for (auto&& subPayload : payloads) {
PayloadSerializer* serializer = serializers->getPayloadSerializer(subPayload);
if (serializer) {
jinglePayload.addNode(std::make_shared<XMLRawTextNode>(serializer->serialize(subPayload)));
}
}
}
if (payload->getReason().is_initialized()) {
std::shared_ptr<XMLElement> reason = std::make_shared<XMLElement>("reason");
reason->addNode(std::make_shared<XMLElement>(reasonTypeToString(payload->getReason()->type)));
if (!payload->getReason()->text.empty()) {
reason->addNode(std::make_shared<XMLElement>("desc", "", payload->getReason()->text));
}
jinglePayload.addNode(reason);
}
return jinglePayload.serialize();
}
std::string JinglePayloadSerializer::actionToString(JinglePayload::Action action) const {
switch(action) {
case JinglePayload::ContentAccept:
return "content-accept";
case JinglePayload::ContentAdd:
return "content-add";
case JinglePayload::ContentModify:
return "content-modify";
case JinglePayload::ContentReject:
return "content-reject";
case JinglePayload::ContentRemove:
diff --git a/Swiften/Serializer/PayloadSerializers/JingleS5BTransportPayloadSerializer.cpp b/Swiften/Serializer/PayloadSerializers/JingleS5BTransportPayloadSerializer.cpp
index 61447cd..5e74d8e 100644
--- a/Swiften/Serializer/PayloadSerializers/JingleS5BTransportPayloadSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/JingleS5BTransportPayloadSerializer.cpp
@@ -1,68 +1,67 @@
/*
* 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 <Swiften/Serializer/PayloadSerializers/JingleS5BTransportPayloadSerializer.h>
#include <memory>
#include <boost/lexical_cast.hpp>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLNode.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
namespace Swift {
JingleS5BTransportPayloadSerializer::JingleS5BTransportPayloadSerializer() {
}
std::string JingleS5BTransportPayloadSerializer::serializePayload(std::shared_ptr<JingleS5BTransportPayload> payload) const {
XMLElement payloadXML("transport", "urn:xmpp:jingle:transports:s5b:1");
payloadXML.setAttribute("sid", payload->getSessionID());
payloadXML.setAttribute("mode", modeToString(payload->getMode()));
if (!payload->getDstAddr().empty()) {
payloadXML.setAttribute("dstaddr", payload->getDstAddr());
}
- foreach(JingleS5BTransportPayload::Candidate candidate, payload->getCandidates()) {
+ for (const auto& candidate : payload->getCandidates()) {
std::shared_ptr<XMLElement> candidateXML = std::make_shared<XMLElement>("candidate");
candidateXML->setAttribute("cid", candidate.cid);
candidateXML->setAttribute("host", candidate.hostPort.getAddress().toString());
candidateXML->setAttribute("jid", candidate.jid.toString());
candidateXML->setAttribute("port", boost::lexical_cast<std::string>(candidate.hostPort.getPort()));
candidateXML->setAttribute("priority", boost::lexical_cast<std::string>(candidate.priority));
candidateXML->setAttribute("type", typeToString(candidate.type));
payloadXML.addNode(candidateXML);
}
if (payload->hasCandidateError()) {
payloadXML.addNode(std::make_shared<XMLElement>("candidate-error"));
}
if (payload->hasProxyError()) {
payloadXML.addNode(std::make_shared<XMLElement>("proxy-error"));
}
if (!payload->getActivated().empty()) {
std::shared_ptr<XMLElement> activatedXML = std::make_shared<XMLElement>("activated");
activatedXML->setAttribute("cid", payload->getActivated());
payloadXML.addNode(activatedXML);
}
if (!payload->getCandidateUsed().empty()) {
std::shared_ptr<XMLElement> candusedXML = std::make_shared<XMLElement>("candidate-used");
candusedXML->setAttribute("cid", payload->getCandidateUsed());
payloadXML.addNode(candusedXML);
}
return payloadXML.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/MUCAdminPayloadSerializer.cpp b/Swiften/Serializer/PayloadSerializers/MUCAdminPayloadSerializer.cpp
index 385c181..157c99e 100644
--- a/Swiften/Serializer/PayloadSerializers/MUCAdminPayloadSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/MUCAdminPayloadSerializer.cpp
@@ -1,31 +1,30 @@
/*
* Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/MUCAdminPayloadSerializer.h>
#include <memory>
#include <sstream>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/PayloadSerializers/MUCItemSerializer.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
namespace Swift {
MUCAdminPayloadSerializer::MUCAdminPayloadSerializer() : GenericPayloadSerializer<MUCAdminPayload>() {
}
std::string MUCAdminPayloadSerializer::serializePayload(std::shared_ptr<MUCAdminPayload> payload) const {
XMLElement mucElement("query", "http://jabber.org/protocol/muc#admin");
- foreach (const MUCItem& item, payload->getItems()) {
+ for (const auto& item : payload->getItems()) {
mucElement.addNode(MUCItemSerializer::itemToElement(item));
}
return mucElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/MUCDestroyPayloadSerializer.cpp b/Swiften/Serializer/PayloadSerializers/MUCDestroyPayloadSerializer.cpp
index 3d807be..96116c7 100644
--- a/Swiften/Serializer/PayloadSerializers/MUCDestroyPayloadSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/MUCDestroyPayloadSerializer.cpp
@@ -1,36 +1,35 @@
/*
* Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/MUCDestroyPayloadSerializer.h>
#include <memory>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
namespace Swift {
MUCDestroyPayloadSerializer::MUCDestroyPayloadSerializer() : GenericPayloadSerializer<MUCDestroyPayload>() {
}
std::string MUCDestroyPayloadSerializer::serializePayload(std::shared_ptr<MUCDestroyPayload> payload) const {
XMLElement mucElement("destroy", "");
if (!payload->getReason().empty()) {
XMLElement::ref reason = std::make_shared<XMLElement>("reason", "");
reason->addNode(std::make_shared<XMLTextNode>(payload->getReason()));
mucElement.addNode(reason);
}
if (payload->getNewVenue().isValid()) {
mucElement.setAttribute("jid", payload->getNewVenue().toString());
}
return mucElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/MUCInvitationPayloadSerializer.cpp b/Swiften/Serializer/PayloadSerializers/MUCInvitationPayloadSerializer.cpp
index 4b978af..2004f4c 100644
--- a/Swiften/Serializer/PayloadSerializers/MUCInvitationPayloadSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/MUCInvitationPayloadSerializer.cpp
@@ -1,41 +1,40 @@
/*
* Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/MUCInvitationPayloadSerializer.h>
#include <memory>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/PayloadSerializers/MUCItemSerializer.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
namespace Swift {
MUCInvitationPayloadSerializer::MUCInvitationPayloadSerializer() : GenericPayloadSerializer<MUCInvitationPayload>() {
}
std::string MUCInvitationPayloadSerializer::serializePayload(std::shared_ptr<MUCInvitationPayload> payload) const {
XMLElement mucElement("x", "jabber:x:conference");
if (payload->getIsContinuation()) {
mucElement.setAttribute("continue", "true");
}
if (payload->getJID().isValid()) {
mucElement.setAttribute("jid", payload->getJID().toString());
}
if (!payload->getPassword().empty()) {
mucElement.setAttribute("password", payload->getPassword());
}
if (!payload->getReason().empty()) {
mucElement.setAttribute("reason", payload->getReason());
}
if (!payload->getThread().empty()) {
mucElement.setAttribute("thread", payload->getThread());
}
if (payload->getIsImpromptu()) {
mucElement.addNode(std::make_shared<XMLElement>("impromptu", "http://swift.im/impromptu"));
}
return mucElement.serialize();
diff --git a/Swiften/Serializer/PayloadSerializers/MUCUserPayloadSerializer.cpp b/Swiften/Serializer/PayloadSerializers/MUCUserPayloadSerializer.cpp
index 52ab489..f0f3cfa 100644
--- a/Swiften/Serializer/PayloadSerializers/MUCUserPayloadSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/MUCUserPayloadSerializer.cpp
@@ -1,63 +1,62 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/MUCUserPayloadSerializer.h>
#include <memory>
#include <sstream>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/PayloadSerializerCollection.h>
#include <Swiften/Serializer/PayloadSerializers/MUCItemSerializer.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
namespace Swift {
MUCUserPayloadSerializer::MUCUserPayloadSerializer(PayloadSerializerCollection* serializers) : GenericPayloadSerializer<MUCUserPayload>(), serializers(serializers) {
}
std::string MUCUserPayloadSerializer::serializePayload(std::shared_ptr<MUCUserPayload> payload) const {
XMLElement mucElement("x", "http://jabber.org/protocol/muc#user");
- foreach (const MUCUserPayload::StatusCode statusCode, payload->getStatusCodes()) {
+ for (const auto& statusCode : payload->getStatusCodes()) {
std::shared_ptr<XMLElement> statusElement(new XMLElement("status"));
std::ostringstream code;
code << statusCode.code;
statusElement->setAttribute("code", code.str());
mucElement.addNode(statusElement);
}
- foreach (const MUCItem& item, payload->getItems()) {
+ for (const auto& item : payload->getItems()) {
mucElement.addNode(MUCItemSerializer::itemToElement(item));
}
if (payload->getPassword()) {
std::shared_ptr<XMLElement> passwordElement = std::make_shared<XMLElement>("password");
passwordElement->addNode(std::make_shared<XMLTextNode>(*payload->getPassword()));
}
if (payload->getInvite()) {
MUCUserPayload::Invite invite = *payload->getInvite();
std::shared_ptr<XMLElement> inviteElement = std::make_shared<XMLElement>("invite");
if (invite.to.isValid()) {
inviteElement->setAttribute("to", invite.to.toString());
}
if (invite.from.isValid()) {
inviteElement->setAttribute("from", invite.from.toString());
}
if (!invite.reason.empty()) {
std::shared_ptr<XMLElement> reasonElement = std::make_shared<XMLElement>("reason");
reasonElement->addNode(std::make_shared<XMLTextNode>(invite.reason));
}
mucElement.addNode(inviteElement);
}
std::shared_ptr<Payload> childPayload = payload->getPayload();
if (childPayload) {
PayloadSerializer* serializer = serializers->getPayloadSerializer(childPayload);
if (serializer) {
mucElement.addNode(std::make_shared<XMLRawTextNode>(serializer->serialize(childPayload)));
}
diff --git a/Swiften/Serializer/PayloadSerializers/PrivateStorageSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PrivateStorageSerializer.cpp
index 87a2eeb..fc410fb 100644
--- a/Swiften/Serializer/PayloadSerializers/PrivateStorageSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PrivateStorageSerializer.cpp
@@ -1,34 +1,33 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/PrivateStorageSerializer.h>
#include <memory>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/PayloadSerializerCollection.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
namespace Swift {
PrivateStorageSerializer::PrivateStorageSerializer(PayloadSerializerCollection* serializers) : serializers(serializers) {
}
std::string PrivateStorageSerializer::serializePayload(std::shared_ptr<PrivateStorage> storage) const {
XMLElement storageElement("query", "jabber:iq:private");
std::shared_ptr<Payload> payload = storage->getPayload();
if (payload) {
PayloadSerializer* serializer = serializers->getPayloadSerializer(payload);
if (serializer) {
storageElement.addNode(std::make_shared<XMLRawTextNode>(serializer->serialize(payload)));
}
}
return storageElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubAffiliationsSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubAffiliationsSerializer.cpp
index 07b427c..9c810da 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubAffiliationsSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubAffiliationsSerializer.cpp
@@ -1,41 +1,38 @@
/*
* Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-
-
#include <Swiften/Serializer/PayloadSerializers/PubSubAffiliationsSerializer.h>
#include <memory>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/PayloadSerializerCollection.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubAffiliationSerializer.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
using namespace Swift;
PubSubAffiliationsSerializer::PubSubAffiliationsSerializer(PayloadSerializerCollection* serializers) : serializers(serializers) {
}
PubSubAffiliationsSerializer::~PubSubAffiliationsSerializer() {
}
std::string PubSubAffiliationsSerializer::serializePayload(std::shared_ptr<PubSubAffiliations> payload) const {
if (!payload) {
return "";
}
XMLElement element("affiliations", "http://jabber.org/protocol/pubsub");
if (payload->getNode()) {
element.setAttribute("node", *payload->getNode());
}
- foreach(std::shared_ptr<PubSubAffiliation> item, payload->getAffiliations()) {
+ for (const auto& item : payload->getAffiliations()) {
element.addNode(std::make_shared<XMLRawTextNode>(PubSubAffiliationSerializer(serializers).serialize(item)));
}
return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventItemSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubEventItemSerializer.cpp
index 61b6cb5..2743ff6 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventItemSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventItemSerializer.cpp
@@ -1,46 +1,43 @@
/*
* Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-
-
#include <Swiften/Serializer/PayloadSerializers/PubSubEventItemSerializer.h>
#include <memory>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/PayloadSerializerCollection.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
using namespace Swift;
PubSubEventItemSerializer::PubSubEventItemSerializer(PayloadSerializerCollection* serializers) : serializers(serializers) {
}
PubSubEventItemSerializer::~PubSubEventItemSerializer() {
}
std::string PubSubEventItemSerializer::serializePayload(std::shared_ptr<PubSubEventItem> payload) const {
if (!payload) {
return "";
}
XMLElement element("item", "http://jabber.org/protocol/pubsub#event");
if (payload->getNode()) {
element.setAttribute("node", *payload->getNode());
}
if (payload->getPublisher()) {
element.setAttribute("publisher", *payload->getPublisher());
}
- foreach(std::shared_ptr<Payload> item, payload->getData()) {
+ for (const auto& item : payload->getData()) {
element.addNode(std::make_shared<XMLRawTextNode>(serializers->getPayloadSerializer(item)->serialize(item)));
}
if (payload->getID()) {
element.setAttribute("id", *payload->getID());
}
return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventItemsSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubEventItemsSerializer.cpp
index c8704ea..67d611b 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventItemsSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventItemsSerializer.cpp
@@ -1,43 +1,40 @@
/*
* Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-
-
#include <Swiften/Serializer/PayloadSerializers/PubSubEventItemsSerializer.h>
#include <memory>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/PayloadSerializerCollection.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubEventItemSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubEventRetractSerializer.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
using namespace Swift;
PubSubEventItemsSerializer::PubSubEventItemsSerializer(PayloadSerializerCollection* serializers) : serializers(serializers) {
}
PubSubEventItemsSerializer::~PubSubEventItemsSerializer() {
}
std::string PubSubEventItemsSerializer::serializePayload(std::shared_ptr<PubSubEventItems> payload) const {
if (!payload) {
return "";
}
XMLElement element("items", "http://jabber.org/protocol/pubsub#event");
element.setAttribute("node", payload->getNode());
- foreach(std::shared_ptr<PubSubEventItem> item, payload->getItems()) {
+ for (const auto& item : payload->getItems()) {
element.addNode(std::make_shared<XMLRawTextNode>(PubSubEventItemSerializer(serializers).serialize(item)));
}
- foreach(std::shared_ptr<PubSubEventRetract> item, payload->getRetracts()) {
+ for (const auto& item : payload->getRetracts()) {
element.addNode(std::make_shared<XMLRawTextNode>(PubSubEventRetractSerializer(serializers).serialize(item)));
}
return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubEventSerializer.cpp
index d0b14ae..51b8b46 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventSerializer.cpp
@@ -1,49 +1,48 @@
/*
* Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/PubSubEventSerializer.h>
#include <memory>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubEventCollectionSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubEventConfigurationSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubEventDeleteSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubEventItemsSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubEventPurgeSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubEventSubscriptionSerializer.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
using namespace Swift;
PubSubEventSerializer::PubSubEventSerializer(PayloadSerializerCollection* serializers) {
pubsubSerializers.push_back(std::make_shared<PubSubEventSubscriptionSerializer>(serializers));
pubsubSerializers.push_back(std::make_shared<PubSubEventPurgeSerializer>(serializers));
pubsubSerializers.push_back(std::make_shared<PubSubEventCollectionSerializer>(serializers));
pubsubSerializers.push_back(std::make_shared<PubSubEventDeleteSerializer>(serializers));
pubsubSerializers.push_back(std::make_shared<PubSubEventItemsSerializer>(serializers));
pubsubSerializers.push_back(std::make_shared<PubSubEventConfigurationSerializer>(serializers));
}
PubSubEventSerializer::~PubSubEventSerializer() {
}
std::string PubSubEventSerializer::serializePayload(std::shared_ptr<PubSubEvent> payload) const {
if (!payload) {
return "";
}
XMLElement element("event", "http://jabber.org/protocol/pubsub#event");
std::shared_ptr<PubSubEventPayload> p = payload->getPayload();
- foreach(std::shared_ptr<PayloadSerializer> serializer, pubsubSerializers) {
+ for (const auto& serializer : pubsubSerializers) {
if (serializer->canSerialize(p)) {
element.addNode(std::make_shared<XMLRawTextNode>(serializer->serialize(p)));
}
}
return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubItemSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubItemSerializer.cpp
index d2e5977..a202c88 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubItemSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubItemSerializer.cpp
@@ -1,40 +1,37 @@
/*
* Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-
-
#include <Swiften/Serializer/PayloadSerializers/PubSubItemSerializer.h>
#include <memory>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/PayloadSerializerCollection.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
using namespace Swift;
PubSubItemSerializer::PubSubItemSerializer(PayloadSerializerCollection* serializers) : serializers(serializers) {
}
PubSubItemSerializer::~PubSubItemSerializer() {
}
std::string PubSubItemSerializer::serializePayload(std::shared_ptr<PubSubItem> payload) const {
if (!payload) {
return "";
}
XMLElement element("item", "http://jabber.org/protocol/pubsub");
- foreach(std::shared_ptr<Payload> item, payload->getData()) {
+ for (const auto& item : payload->getData()) {
element.addNode(std::make_shared<XMLRawTextNode>(serializers->getPayloadSerializer(item)->serialize(item)));
}
if (!payload->getID().empty()) {
element.setAttribute("id", payload->getID());
}
return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubItemsSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubItemsSerializer.cpp
index ae6433a..9786f51 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubItemsSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubItemsSerializer.cpp
@@ -1,51 +1,48 @@
/*
* Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-
-
#include <Swiften/Serializer/PayloadSerializers/PubSubItemsSerializer.h>
#include <memory>
#include <boost/lexical_cast.hpp>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/PayloadSerializerCollection.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubItemSerializer.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
using namespace Swift;
PubSubItemsSerializer::PubSubItemsSerializer(PayloadSerializerCollection* serializers) : serializers(serializers) {
}
PubSubItemsSerializer::~PubSubItemsSerializer() {
}
std::string PubSubItemsSerializer::serializePayload(std::shared_ptr<PubSubItems> payload) const {
if (!payload) {
return "";
}
XMLElement element("items", "http://jabber.org/protocol/pubsub");
if (payload->getNode().empty()) {
SWIFT_LOG(warning) << "Serializing PubSubItems with empty node attribute";
}
element.setAttribute("node", payload->getNode());
- foreach(std::shared_ptr<PubSubItem> item, payload->getItems()) {
+ for (const auto& item : payload->getItems()) {
element.addNode(std::make_shared<XMLRawTextNode>(PubSubItemSerializer(serializers).serialize(item)));
}
if (payload->getMaximumItems()) {
element.setAttribute("max_items", boost::lexical_cast<std::string>(*payload->getMaximumItems()));
}
if (payload->getSubscriptionID()) {
element.setAttribute("subid", *payload->getSubscriptionID());
}
return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationsSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationsSerializer.cpp
index 7810e2f..b9f6bcc 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationsSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationsSerializer.cpp
@@ -1,38 +1,36 @@
/*
* Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationsSerializer.h>
-#include <cassert>
#include <memory>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/PayloadSerializerCollection.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationSerializer.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
using namespace Swift;
PubSubOwnerAffiliationsSerializer::PubSubOwnerAffiliationsSerializer(PayloadSerializerCollection* serializers) : serializers(serializers) {
}
PubSubOwnerAffiliationsSerializer::~PubSubOwnerAffiliationsSerializer() {
}
std::string PubSubOwnerAffiliationsSerializer::serializePayload(std::shared_ptr<PubSubOwnerAffiliations> payload) const {
if (!payload) {
return "";
}
XMLElement element("affiliations", "http://jabber.org/protocol/pubsub#owner");
element.setAttribute("node", payload->getNode());
- foreach(std::shared_ptr<PubSubOwnerAffiliation> item, payload->getAffiliations()) {
+ for (const auto& item : payload->getAffiliations()) {
element.addNode(std::make_shared<XMLRawTextNode>(PubSubOwnerAffiliationSerializer(serializers).serialize(item)));
}
return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOwnerPubSubSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubOwnerPubSubSerializer.cpp
index cacd8d9..b2dfd21 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerPubSubSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerPubSubSerializer.cpp
@@ -1,49 +1,48 @@
/*
* Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/PubSubOwnerPubSubSerializer.h>
#include <memory>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationsSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubOwnerConfigureSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubOwnerDefaultSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubOwnerDeleteSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubOwnerPurgeSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionsSerializer.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
using namespace Swift;
PubSubOwnerPubSubSerializer::PubSubOwnerPubSubSerializer(PayloadSerializerCollection* serializers) {
pubsubSerializers.push_back(std::make_shared<PubSubOwnerConfigureSerializer>(serializers));
pubsubSerializers.push_back(std::make_shared<PubSubOwnerSubscriptionsSerializer>(serializers));
pubsubSerializers.push_back(std::make_shared<PubSubOwnerDefaultSerializer>(serializers));
pubsubSerializers.push_back(std::make_shared<PubSubOwnerPurgeSerializer>(serializers));
pubsubSerializers.push_back(std::make_shared<PubSubOwnerAffiliationsSerializer>(serializers));
pubsubSerializers.push_back(std::make_shared<PubSubOwnerDeleteSerializer>(serializers));
}
PubSubOwnerPubSubSerializer::~PubSubOwnerPubSubSerializer() {
}
std::string PubSubOwnerPubSubSerializer::serializePayload(std::shared_ptr<PubSubOwnerPubSub> payload) const {
if (!payload) {
return "";
}
XMLElement element("pubsub", "http://jabber.org/protocol/pubsub#owner");
std::shared_ptr<PubSubOwnerPayload> p = payload->getPayload();
- foreach(std::shared_ptr<PayloadSerializer> serializer, pubsubSerializers) {
+ for (const auto& serializer : pubsubSerializers) {
if (serializer->canSerialize(p)) {
element.addNode(std::make_shared<XMLRawTextNode>(serializer->serialize(p)));
}
}
return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionsSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionsSerializer.cpp
index 9a6ca32..a5940f6 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionsSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionsSerializer.cpp
@@ -1,38 +1,36 @@
/*
* Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionsSerializer.h>
-#include <cassert>
#include <memory>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/PayloadSerializerCollection.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionSerializer.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
using namespace Swift;
PubSubOwnerSubscriptionsSerializer::PubSubOwnerSubscriptionsSerializer(PayloadSerializerCollection* serializers) : serializers(serializers) {
}
PubSubOwnerSubscriptionsSerializer::~PubSubOwnerSubscriptionsSerializer() {
}
std::string PubSubOwnerSubscriptionsSerializer::serializePayload(std::shared_ptr<PubSubOwnerSubscriptions> payload) const {
if (!payload) {
return "";
}
XMLElement element("subscriptions", "http://jabber.org/protocol/pubsub#owner");
element.setAttribute("node", payload->getNode());
- foreach(std::shared_ptr<PubSubOwnerSubscription> item, payload->getSubscriptions()) {
+ for (const auto& item : payload->getSubscriptions()) {
element.addNode(std::make_shared<XMLRawTextNode>(PubSubOwnerSubscriptionSerializer(serializers).serialize(item)));
}
return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubPublishSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubPublishSerializer.cpp
index 871845f..ce8706d 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubPublishSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubPublishSerializer.cpp
@@ -1,39 +1,36 @@
/*
* Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-
-
#include <Swiften/Serializer/PayloadSerializers/PubSubPublishSerializer.h>
#include <memory>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/PayloadSerializerCollection.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubItemSerializer.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
using namespace Swift;
PubSubPublishSerializer::PubSubPublishSerializer(PayloadSerializerCollection* serializers) : serializers(serializers) {
}
PubSubPublishSerializer::~PubSubPublishSerializer() {
}
std::string PubSubPublishSerializer::serializePayload(std::shared_ptr<PubSubPublish> payload) const {
if (!payload) {
return "";
}
XMLElement element("publish", "http://jabber.org/protocol/pubsub");
element.setAttribute("node", payload->getNode());
- foreach(std::shared_ptr<PubSubItem> item, payload->getItems()) {
+ for (const auto& item : payload->getItems()) {
element.addNode(std::make_shared<XMLRawTextNode>(PubSubItemSerializer(serializers).serialize(item)));
}
return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubRetractSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubRetractSerializer.cpp
index 99b425e..c82089a 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubRetractSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubRetractSerializer.cpp
@@ -1,40 +1,39 @@
/*
* Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/PubSubRetractSerializer.h>
#include <memory>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/PayloadSerializerCollection.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubItemSerializer.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
using namespace Swift;
PubSubRetractSerializer::PubSubRetractSerializer(PayloadSerializerCollection* serializers) : serializers(serializers) {
}
PubSubRetractSerializer::~PubSubRetractSerializer() {
}
std::string PubSubRetractSerializer::serializePayload(std::shared_ptr<PubSubRetract> payload) const {
if (!payload) {
return "";
}
XMLElement element("retract", "http://jabber.org/protocol/pubsub");
element.setAttribute("node", payload->getNode());
- foreach(std::shared_ptr<PubSubItem> item, payload->getItems()) {
+ for (const auto& item : payload->getItems()) {
element.addNode(std::make_shared<XMLRawTextNode>(PubSubItemSerializer(serializers).serialize(item)));
}
if (payload->isNotify().is_initialized()) {
element.setAttribute("notify", payload->isNotify().get() ? "true" : "false");
}
return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubSerializer.cpp
index dbef36e..648c5a3 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubSerializer.cpp
@@ -1,69 +1,66 @@
/*
* Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-
-
#include <Swiften/Serializer/PayloadSerializers/PubSubSerializer.h>
#include <memory>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/PayloadSerializerCollection.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubAffiliationsSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubConfigureSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubCreateSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubDefaultSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubItemsSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubOptionsSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubPublishSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubRetractSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubSubscribeSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubSubscriptionSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubSubscriptionsSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubUnsubscribeSerializer.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
using namespace Swift;
PubSubSerializer::PubSubSerializer(PayloadSerializerCollection* serializers) : serializers(serializers) {
pubsubSerializers.push_back(std::make_shared<PubSubItemsSerializer>(serializers));
pubsubSerializers.push_back(std::make_shared<PubSubCreateSerializer>(serializers));
pubsubSerializers.push_back(std::make_shared<PubSubPublishSerializer>(serializers));
pubsubSerializers.push_back(std::make_shared<PubSubOptionsSerializer>(serializers));
pubsubSerializers.push_back(std::make_shared<PubSubAffiliationsSerializer>(serializers));
pubsubSerializers.push_back(std::make_shared<PubSubRetractSerializer>(serializers));
pubsubSerializers.push_back(std::make_shared<PubSubDefaultSerializer>(serializers));
pubsubSerializers.push_back(std::make_shared<PubSubSubscriptionsSerializer>(serializers));
pubsubSerializers.push_back(std::make_shared<PubSubSubscribeSerializer>(serializers));
pubsubSerializers.push_back(std::make_shared<PubSubUnsubscribeSerializer>(serializers));
pubsubSerializers.push_back(std::make_shared<PubSubSubscriptionSerializer>(serializers));
}
PubSubSerializer::~PubSubSerializer() {
}
std::string PubSubSerializer::serializePayload(std::shared_ptr<PubSub> payload) const {
if (!payload) {
return "";
}
XMLElement element("pubsub", "http://jabber.org/protocol/pubsub");
std::shared_ptr<PubSubPayload> p = payload->getPayload();
- foreach(std::shared_ptr<PayloadSerializer> serializer, pubsubSerializers) {
+ for (const auto& serializer : pubsubSerializers) {
if (serializer->canSerialize(p)) {
element.addNode(std::make_shared<XMLRawTextNode>(serializer->serialize(p)));
if (std::shared_ptr<PubSubCreate> create = std::dynamic_pointer_cast<PubSubCreate>(p)) {
element.addNode(std::make_shared<XMLRawTextNode>(std::make_shared<PubSubConfigureSerializer>(serializers)->serialize(create->getConfigure())));
}
if (std::shared_ptr<PubSubSubscribe> subscribe = std::dynamic_pointer_cast<PubSubSubscribe>(p)) {
element.addNode(std::make_shared<XMLRawTextNode>(std::make_shared<PubSubConfigureSerializer>(serializers)->serialize(subscribe->getOptions())));
}
}
}
return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubSubscriptionsSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubSubscriptionsSerializer.cpp
index e154109..6e01881 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubSubscriptionsSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubSubscriptionsSerializer.cpp
@@ -1,39 +1,38 @@
/*
* Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/PubSubSubscriptionsSerializer.h>
#include <memory>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/PayloadSerializerCollection.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubSubscriptionSerializer.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
using namespace Swift;
PubSubSubscriptionsSerializer::PubSubSubscriptionsSerializer(PayloadSerializerCollection* serializers) : serializers(serializers) {
}
PubSubSubscriptionsSerializer::~PubSubSubscriptionsSerializer() {
}
std::string PubSubSubscriptionsSerializer::serializePayload(std::shared_ptr<PubSubSubscriptions> payload) const {
if (!payload) {
return "";
}
XMLElement element("subscriptions", "http://jabber.org/protocol/pubsub");
if (payload->getNode()) {
element.setAttribute("node", *payload->getNode());
}
- foreach(std::shared_ptr<PubSubSubscription> item, payload->getSubscriptions()) {
+ for (const auto& item : payload->getSubscriptions()) {
element.addNode(std::make_shared<XMLRawTextNode>(PubSubSubscriptionSerializer(serializers).serialize(item)));
}
return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/RosterItemExchangeSerializer.cpp b/Swiften/Serializer/PayloadSerializers/RosterItemExchangeSerializer.cpp
index 24cc301..c7fdc5b 100644
--- a/Swiften/Serializer/PayloadSerializers/RosterItemExchangeSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/RosterItemExchangeSerializer.cpp
@@ -1,52 +1,51 @@
/*
* Copyright (c) 2011 Jan Kaluza
* 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 <Swiften/Serializer/PayloadSerializers/RosterItemExchangeSerializer.h>
#include <memory>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
namespace Swift {
RosterItemExchangeSerializer::RosterItemExchangeSerializer() : GenericPayloadSerializer<RosterItemExchangePayload>() {
}
std::string RosterItemExchangeSerializer::serializePayload(std::shared_ptr<RosterItemExchangePayload> roster) const {
XMLElement queryElement("x", "http://jabber.org/protocol/rosterx");
- foreach(const RosterItemExchangePayload::Item& item, roster->getItems()) {
+ for (const auto& item : roster->getItems()) {
std::shared_ptr<XMLElement> itemElement(new XMLElement("item"));
itemElement->setAttribute("jid", item.getJID());
itemElement->setAttribute("name", item.getName());
switch (item.getAction()) {
case RosterItemExchangePayload::Item::Add: itemElement->setAttribute("action", "add"); break;
case RosterItemExchangePayload::Item::Modify: itemElement->setAttribute("action", "modify"); break;
case RosterItemExchangePayload::Item::Delete: itemElement->setAttribute("action", "delete"); break;
}
- foreach(const std::string& group, item.getGroups()) {
+ for (const auto& group : item.getGroups()) {
std::shared_ptr<XMLElement> groupElement(new XMLElement("group"));
groupElement->addNode(std::make_shared<XMLTextNode>(group));
itemElement->addNode(groupElement);
}
queryElement.addNode(itemElement);
}
return queryElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/RosterSerializer.cpp b/Swiften/Serializer/PayloadSerializers/RosterSerializer.cpp
index 8c857ab..e706542 100644
--- a/Swiften/Serializer/PayloadSerializers/RosterSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/RosterSerializer.cpp
@@ -1,60 +1,59 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/RosterSerializer.h>
#include <memory>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
namespace Swift {
RosterSerializer::RosterSerializer() : GenericPayloadSerializer<RosterPayload>() {
}
std::string RosterSerializer::serializePayload(std::shared_ptr<RosterPayload> roster) const {
XMLElement queryElement("query", "jabber:iq:roster");
if (roster->getVersion()) {
queryElement.setAttribute("ver", *roster->getVersion());
}
- foreach(const RosterItemPayload& item, roster->getItems()) {
+ for (const auto& item : roster->getItems()) {
std::shared_ptr<XMLElement> itemElement(new XMLElement("item"));
itemElement->setAttribute("jid", item.getJID());
itemElement->setAttribute("name", item.getName());
switch (item.getSubscription()) {
case RosterItemPayload::To: itemElement->setAttribute("subscription", "to"); break;
case RosterItemPayload::From: itemElement->setAttribute("subscription", "from"); break;
case RosterItemPayload::Both: itemElement->setAttribute("subscription", "both"); break;
case RosterItemPayload::Remove: itemElement->setAttribute("subscription", "remove"); break;
case RosterItemPayload::None: itemElement->setAttribute("subscription", "none"); break;
}
if (item.getSubscriptionRequested()) {
itemElement->setAttribute("ask", "subscribe");
}
- foreach(const std::string& group, item.getGroups()) {
+ for (const auto& group : item.getGroups()) {
std::shared_ptr<XMLElement> groupElement(new XMLElement("group"));
groupElement->addNode(std::make_shared<XMLTextNode>(group));
itemElement->addNode(groupElement);
}
if (!item.getUnknownContent().empty()) {
itemElement->addNode(std::make_shared<XMLRawTextNode>(item.getUnknownContent()));
}
queryElement.addNode(itemElement);
}
return queryElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/SearchPayloadSerializer.cpp b/Swiften/Serializer/PayloadSerializers/SearchPayloadSerializer.cpp
index 6e55f46..befd76d 100644
--- a/Swiften/Serializer/PayloadSerializers/SearchPayloadSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/SearchPayloadSerializer.cpp
@@ -1,62 +1,61 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/SearchPayloadSerializer.h>
#include <memory>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/PayloadSerializers/FormSerializer.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
namespace Swift {
SearchPayloadSerializer::SearchPayloadSerializer() {
}
std::string SearchPayloadSerializer::serializePayload(std::shared_ptr<SearchPayload> searchPayload) const {
XMLElement searchElement("query", "jabber:iq:search");
if (searchPayload->getInstructions()) {
searchElement.addNode(XMLElement::ref(new XMLElement("instructions", "", *searchPayload->getInstructions())));
}
if (searchPayload->getNick()) {
searchElement.addNode(XMLElement::ref(new XMLElement("nick", "", *searchPayload->getNick())));
}
if (searchPayload->getFirst()) {
searchElement.addNode(XMLElement::ref(new XMLElement("first", "", *searchPayload->getFirst())));
}
if (searchPayload->getLast()) {
searchElement.addNode(XMLElement::ref(new XMLElement("last", "", *searchPayload->getLast())));
}
if (searchPayload->getEMail()) {
searchElement.addNode(XMLElement::ref(new XMLElement("email", "", *searchPayload->getEMail())));
}
- foreach(const SearchPayload::Item& item, searchPayload->getItems()) {
+ for (const auto& item : searchPayload->getItems()) {
XMLElement::ref itemElement(new XMLElement("item"));
itemElement->setAttribute("jid", item.jid);
itemElement->addNode(XMLElement::ref(new XMLElement("first", "", item.first)));
itemElement->addNode(XMLElement::ref(new XMLElement("last", "", item.last)));
itemElement->addNode(XMLElement::ref(new XMLElement("nick", "", item.nick)));
itemElement->addNode(XMLElement::ref(new XMLElement("email", "", item.email)));
searchElement.addNode(itemElement);
}
if (Form::ref form = searchPayload->getForm()) {
searchElement.addNode(std::make_shared<XMLRawTextNode>(FormSerializer().serialize(form)));
}
return searchElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/SecurityLabelSerializer.cpp b/Swiften/Serializer/PayloadSerializers/SecurityLabelSerializer.cpp
index 97c5411..b8faf73 100644
--- a/Swiften/Serializer/PayloadSerializers/SecurityLabelSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/SecurityLabelSerializer.cpp
@@ -1,47 +1,46 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/SecurityLabelSerializer.h>
#include <memory>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
namespace Swift {
SecurityLabelSerializer::SecurityLabelSerializer() : GenericPayloadSerializer<SecurityLabel>() {
}
std::string SecurityLabelSerializer::serializePayload(std::shared_ptr<SecurityLabel> label) const {
XMLElement element("securitylabel", "urn:xmpp:sec-label:0");
if (!label->getDisplayMarking().empty()) {
std::shared_ptr<XMLElement> displayMarking(new XMLElement("displaymarking"));
if (!label->getForegroundColor().empty()) {
displayMarking->setAttribute("fgcolor", label->getForegroundColor());
}
if (!label->getBackgroundColor().empty()) {
displayMarking->setAttribute("bgcolor", label->getBackgroundColor());
}
displayMarking->addNode(std::make_shared<XMLTextNode>(label->getDisplayMarking()));
element.addNode(displayMarking);
}
std::shared_ptr<XMLElement> labelElement(new XMLElement("label"));
labelElement->addNode(std::make_shared<XMLRawTextNode>(label->getLabel()));
element.addNode(labelElement);
- foreach(const std::string& equivalentLabel, label->getEquivalentLabels()) {
+ for (const auto& equivalentLabel : label->getEquivalentLabels()) {
std::shared_ptr<XMLElement> equivalentLabelElement(new XMLElement("equivalentlabel"));
equivalentLabelElement->addNode(std::make_shared<XMLRawTextNode>(equivalentLabel));
element.addNode(equivalentLabelElement);
}
return element.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/SecurityLabelsCatalogSerializer.cpp b/Swiften/Serializer/PayloadSerializers/SecurityLabelsCatalogSerializer.cpp
index e8d2a1b..36401a6 100644
--- a/Swiften/Serializer/PayloadSerializers/SecurityLabelsCatalogSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/SecurityLabelsCatalogSerializer.cpp
@@ -1,47 +1,46 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/SecurityLabelsCatalogSerializer.h>
#include <memory>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/PayloadSerializers/SecurityLabelSerializer.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
namespace Swift {
SecurityLabelsCatalogSerializer::SecurityLabelsCatalogSerializer() : GenericPayloadSerializer<SecurityLabelsCatalog>() {
}
std::string SecurityLabelsCatalogSerializer::serializePayload(std::shared_ptr<SecurityLabelsCatalog> catalog) const {
XMLElement element("catalog", "urn:xmpp:sec-label:catalog:2");
if (!catalog->getName().empty()) {
element.setAttribute("name", catalog->getName());
}
if (catalog->getTo().isValid()) {
element.setAttribute("to", catalog->getTo());
}
if (!catalog->getDescription().empty()) {
element.setAttribute("desc", catalog->getDescription());
}
- foreach (const SecurityLabelsCatalog::Item& item, catalog->getItems()) {
+ for (const auto& item : catalog->getItems()) {
std::shared_ptr<XMLElement> itemElement(new XMLElement("item"));
itemElement->setAttribute("selector", item.getSelector());
if (item.getIsDefault()) {
itemElement->setAttribute("default", "true");
}
if (item.getLabel()) {
std::string serializedLabel = SecurityLabelSerializer().serialize(item.getLabel());
itemElement->addNode(std::make_shared<XMLRawTextNode>(serializedLabel));
}
element.addNode(itemElement);
}
return element.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/StorageSerializer.cpp b/Swiften/Serializer/PayloadSerializers/StorageSerializer.cpp
index 31720f7..ffebcf4 100644
--- a/Swiften/Serializer/PayloadSerializers/StorageSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/StorageSerializer.cpp
@@ -1,51 +1,50 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/StorageSerializer.h>
#include <memory>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
namespace Swift {
StorageSerializer::StorageSerializer() : GenericPayloadSerializer<Storage>() {
}
std::string StorageSerializer::serializePayload(std::shared_ptr<Storage> storage) const {
XMLElement storageElement("storage", "storage:bookmarks");
- foreach(const Storage::Room& room, storage->getRooms()) {
+ for (const auto& room : storage->getRooms()) {
std::shared_ptr<XMLElement> conferenceElement(new XMLElement("conference"));
conferenceElement->setAttribute("name", room.name);
conferenceElement->setAttribute("jid", room.jid);
conferenceElement->setAttribute("autojoin", room.autoJoin ? "1" : "0");
if (!room.nick.empty()) {
std::shared_ptr<XMLElement> nickElement(new XMLElement("nick"));
nickElement->addNode(std::make_shared<XMLTextNode>(room.nick));
conferenceElement->addNode(nickElement);
}
if (room.password) {
std::shared_ptr<XMLElement> passwordElement(new XMLElement("password"));
passwordElement->addNode(std::make_shared<XMLTextNode>(*room.password));
conferenceElement->addNode(passwordElement);
}
storageElement.addNode(conferenceElement);
}
- foreach(const Storage::URL& url, storage->getURLs()) {
+ for (const auto& url : storage->getURLs()) {
std::shared_ptr<XMLElement> urlElement(new XMLElement("url"));
urlElement->setAttribute("name", url.name);
urlElement->setAttribute("url", url.url);
storageElement.addNode(urlElement);
}
return storageElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/StreamInitiationFileInfoSerializer.cpp b/Swiften/Serializer/PayloadSerializers/StreamInitiationFileInfoSerializer.cpp
index e15ab77..ba296f9 100644
--- a/Swiften/Serializer/PayloadSerializers/StreamInitiationFileInfoSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/StreamInitiationFileInfoSerializer.cpp
@@ -1,50 +1,49 @@
/*
* Copyright (c) 2011 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 <Swiften/Serializer/PayloadSerializers/StreamInitiationFileInfoSerializer.h>
#include <memory>
#include <boost/lexical_cast.hpp>
#include <Swiften/Base/DateTime.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
namespace Swift {
StreamInitiationFileInfoSerializer::StreamInitiationFileInfoSerializer() {
}
std::string StreamInitiationFileInfoSerializer::serializePayload(std::shared_ptr<StreamInitiationFileInfo> fileInfo) const {
XMLElement fileElement("file", "http://jabber.org/protocol/si/profile/file-transfer");
if (fileInfo->getDate() != stringToDateTime("")) {
fileElement.setAttribute("date", dateTimeToString(fileInfo->getDate()));
}
fileElement.setAttribute("hash", fileInfo->getHash());
if (fileInfo->getAlgo() != "md5") {
fileElement.setAttribute("algo", fileInfo->getAlgo());
}
if (!fileInfo->getName().empty()) {
fileElement.setAttribute("name", fileInfo->getName());
}
if (fileInfo->getSize() != 0) {
fileElement.setAttribute("size", boost::lexical_cast<std::string>(fileInfo->getSize()));
}
if (!fileInfo->getDescription().empty()) {
std::shared_ptr<XMLElement> desc = std::make_shared<XMLElement>("desc", "", fileInfo->getDescription());
fileElement.addNode(desc);
}
if (fileInfo->getSupportsRangeRequests()) {
diff --git a/Swiften/Serializer/PayloadSerializers/StreamInitiationSerializer.cpp b/Swiften/Serializer/PayloadSerializers/StreamInitiationSerializer.cpp
index fcfb063..3faa5b7 100644
--- a/Swiften/Serializer/PayloadSerializers/StreamInitiationSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/StreamInitiationSerializer.cpp
@@ -1,75 +1,74 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/StreamInitiationSerializer.h>
#include <memory>
#include <memory>
#include <boost/lexical_cast.hpp>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
#include <Swiften/Serializer/PayloadSerializers/FormSerializer.h>
#define FILE_TRANSFER_NS "http://jabber.org/protocol/si/profile/file-transfer"
#define FEATURE_NEG_NS "http://jabber.org/protocol/feature-neg"
namespace Swift {
StreamInitiationSerializer::StreamInitiationSerializer() {
}
std::string StreamInitiationSerializer::serializePayload(std::shared_ptr<StreamInitiation> streamInitiation) const {
assert(streamInitiation->getIsFileTransfer());
XMLElement siElement("si", "http://jabber.org/protocol/si");
if (!streamInitiation->getID().empty()) {
siElement.setAttribute("id", streamInitiation->getID());
}
siElement.setAttribute("profile", FILE_TRANSFER_NS);
if (streamInitiation->getFileInfo()) {
StreamInitiationFileInfo file = *streamInitiation->getFileInfo();
std::shared_ptr<XMLElement> fileElement(new XMLElement("file", "http://jabber.org/protocol/si/profile/file-transfer"));
fileElement->setAttribute("name", file.getName());
if (file.getSize() != 0) {
fileElement->setAttribute("size", boost::lexical_cast<std::string>(file.getSize()));
}
if (!file.getDescription().empty()) {
std::shared_ptr<XMLElement> descElement(new XMLElement("desc"));
descElement->addNode(std::make_shared<XMLTextNode>(file.getDescription()));
fileElement->addNode(descElement);
}
siElement.addNode(fileElement);
}
std::shared_ptr<XMLElement> featureElement(new XMLElement("feature", FEATURE_NEG_NS));
if (streamInitiation->getProvidedMethods().size() > 0) {
Form::ref form(new Form(Form::FormType));
FormField::ref field = std::make_shared<FormField>(FormField::ListSingleType);
field->setName("stream-method");
- foreach(const std::string& method, streamInitiation->getProvidedMethods()) {
+ for (const auto& method : streamInitiation->getProvidedMethods()) {
field->addOption(FormField::Option("", method));
}
form->addField(field);
featureElement->addNode(std::make_shared<XMLRawTextNode>(FormSerializer().serialize(form)));
}
else if (!streamInitiation->getRequestedMethod().empty()) {
Form::ref form(new Form(Form::SubmitType));
FormField::ref field = std::make_shared<FormField>(FormField::ListSingleType);
field->addValue(streamInitiation->getRequestedMethod());
field->setName("stream-method");
form->addField(field);
featureElement->addNode(std::make_shared<XMLRawTextNode>(FormSerializer().serialize(form)));
}
siElement.addNode(featureElement);
return siElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/VCardSerializer.cpp b/Swiften/Serializer/PayloadSerializers/VCardSerializer.cpp
index a1393cb..725d125 100644
--- a/Swiften/Serializer/PayloadSerializers/VCardSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/VCardSerializer.cpp
@@ -1,250 +1,249 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/VCardSerializer.h>
#include <memory>
#include <Swiften/Base/DateTime.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
#include <Swiften/StringCodecs/Base64.h>
namespace Swift {
VCardSerializer::VCardSerializer() : GenericPayloadSerializer<VCard>() {
}
std::string VCardSerializer::serializePayload(std::shared_ptr<VCard> vcard) const {
XMLElement queryElement("vCard", "vcard-temp");
if (!vcard->getVersion().empty()) {
queryElement.addNode(std::make_shared<XMLElement>("VERSION", "", vcard->getVersion()));
}
if (!vcard->getFullName().empty()) {
queryElement.addNode(std::make_shared<XMLElement>("FN", "", vcard->getFullName()));
}
if (!vcard->getGivenName().empty() || !vcard->getFamilyName().empty() || !vcard->getMiddleName().empty() || !vcard->getPrefix().empty() || !vcard->getSuffix().empty()) {
std::shared_ptr<XMLElement> nameElement(new XMLElement("N"));
if (!vcard->getFamilyName().empty()) {
nameElement->addNode(std::make_shared<XMLElement>("FAMILY", "", vcard->getFamilyName()));
}
if (!vcard->getGivenName().empty()) {
nameElement->addNode(std::make_shared<XMLElement>("GIVEN", "", vcard->getGivenName()));
}
if (!vcard->getMiddleName().empty()) {
nameElement->addNode(std::make_shared<XMLElement>("MIDDLE", "", vcard->getMiddleName()));
}
if (!vcard->getPrefix().empty()) {
nameElement->addNode(std::make_shared<XMLElement>("PREFIX", "", vcard->getPrefix()));
}
if (!vcard->getSuffix().empty()) {
nameElement->addNode(std::make_shared<XMLElement>("SUFFIX", "", vcard->getSuffix()));
}
queryElement.addNode(nameElement);
}
- foreach(const VCard::EMailAddress& emailAddress, vcard->getEMailAddresses()) {
+ for (const auto& emailAddress : vcard->getEMailAddresses()) {
std::shared_ptr<XMLElement> emailElement(new XMLElement("EMAIL"));
emailElement->addNode(std::make_shared<XMLElement>("USERID", "", emailAddress.address));
if (emailAddress.isHome) {
emailElement->addNode(std::make_shared<XMLElement>("HOME"));
}
if (emailAddress.isWork) {
emailElement->addNode(std::make_shared<XMLElement>("WORK"));
}
if (emailAddress.isInternet) {
emailElement->addNode(std::make_shared<XMLElement>("INTERNET"));
}
if (emailAddress.isPreferred) {
emailElement->addNode(std::make_shared<XMLElement>("PREF"));
}
if (emailAddress.isX400) {
emailElement->addNode(std::make_shared<XMLElement>("X400"));
}
queryElement.addNode(emailElement);
}
if (!vcard->getNickname().empty()) {
queryElement.addNode(std::make_shared<XMLElement>("NICKNAME", "", vcard->getNickname()));
}
if (!vcard->getPhoto().empty() || !vcard->getPhotoType().empty()) {
XMLElement::ref photoElement(new XMLElement("PHOTO"));
if (!vcard->getPhotoType().empty()) {
photoElement->addNode(std::make_shared<XMLElement>("TYPE", "", vcard->getPhotoType()));
}
if (!vcard->getPhoto().empty()) {
photoElement->addNode(std::make_shared<XMLElement>("BINVAL", "", Base64::encode(vcard->getPhoto())));
}
queryElement.addNode(photoElement);
}
if (!vcard->getBirthday().is_not_a_date_time()) {
queryElement.addNode(std::make_shared<XMLElement>("BDAY", "", dateTimeToString(vcard->getBirthday())));
}
- foreach(const VCard::Telephone& telephone, vcard->getTelephones()) {
+ for (const auto& telephone : vcard->getTelephones()) {
std::shared_ptr<XMLElement> telElement(new XMLElement("TEL"));
telElement->addNode(std::make_shared<XMLElement>("NUMBER", "", telephone.number));
if (telephone.isHome) {
telElement->addNode(std::make_shared<XMLElement>("HOME"));
}
if (telephone.isWork) {
telElement->addNode(std::make_shared<XMLElement>("WORK"));
}
if (telephone.isVoice) {
telElement->addNode(std::make_shared<XMLElement>("VOICE"));
}
if (telephone.isFax) {
telElement->addNode(std::make_shared<XMLElement>("FAX"));
}
if (telephone.isPager) {
telElement->addNode(std::make_shared<XMLElement>("PAGER"));
}
if (telephone.isMSG) {
telElement->addNode(std::make_shared<XMLElement>("MSG"));
}
if (telephone.isCell) {
telElement->addNode(std::make_shared<XMLElement>("CELL"));
}
if (telephone.isVideo) {
telElement->addNode(std::make_shared<XMLElement>("VIDEO"));
}
if (telephone.isBBS) {
telElement->addNode(std::make_shared<XMLElement>("BBS"));
}
if (telephone.isModem) {
telElement->addNode(std::make_shared<XMLElement>("MODEM"));
}
if (telephone.isISDN) {
telElement->addNode(std::make_shared<XMLElement>("ISDN"));
}
if (telephone.isPCS) {
telElement->addNode(std::make_shared<XMLElement>("PCS"));
}
if (telephone.isPreferred) {
telElement->addNode(std::make_shared<XMLElement>("PREF"));
}
queryElement.addNode(telElement);
}
- foreach(const VCard::Address& address, vcard->getAddresses()) {
+ for (const auto& address : vcard->getAddresses()) {
std::shared_ptr<XMLElement> adrElement = std::make_shared<XMLElement>("ADR");
if (!address.poBox.empty()) {
adrElement->addNode(std::make_shared<XMLElement>("POBOX", "", address.poBox));
}
if (!address.addressExtension.empty()) {
adrElement->addNode(std::make_shared<XMLElement>("EXTADD", "", address.addressExtension));
}
if (!address.street.empty()) {
adrElement->addNode(std::make_shared<XMLElement>("STREET", "", address.street));
}
if (!address.locality.empty()) {
adrElement->addNode(std::make_shared<XMLElement>("LOCALITY", "", address.locality));
}
if (!address.region.empty()) {
adrElement->addNode(std::make_shared<XMLElement>("REGION", "", address.region));
}
if (!address.postalCode.empty()) {
adrElement->addNode(std::make_shared<XMLElement>("PCODE", "", address.postalCode));
}
if (!address.country.empty()) {
adrElement->addNode(std::make_shared<XMLElement>("CTRY", "", address.country));
}
if (address.isHome) {
adrElement->addNode(std::make_shared<XMLElement>("HOME"));
}
if (address.isWork) {
adrElement->addNode(std::make_shared<XMLElement>("WORK"));
}
if (address.isPostal) {
adrElement->addNode(std::make_shared<XMLElement>("POSTAL"));
}
if (address.isParcel) {
adrElement->addNode(std::make_shared<XMLElement>("PARCEL"));
}
if (address.deliveryType == VCard::DomesticDelivery) {
adrElement->addNode(std::make_shared<XMLElement>("DOM"));
}
if (address.deliveryType == VCard::InternationalDelivery) {
adrElement->addNode(std::make_shared<XMLElement>("INTL"));
}
if (address.isPreferred) {
adrElement->addNode(std::make_shared<XMLElement>("PREF"));
}
queryElement.addNode(adrElement);
}
- foreach(const VCard::AddressLabel& addressLabel, vcard->getAddressLabels()) {
+ for (const auto& addressLabel : vcard->getAddressLabels()) {
std::shared_ptr<XMLElement> labelElement = std::make_shared<XMLElement>("LABEL");
- foreach(const std::string& line, addressLabel.lines) {
+ for (const auto& line : addressLabel.lines) {
labelElement->addNode(std::make_shared<XMLElement>("LINE", "", line));
}
if (addressLabel.isHome) {
labelElement->addNode(std::make_shared<XMLElement>("HOME"));
}
if (addressLabel.isWork) {
labelElement->addNode(std::make_shared<XMLElement>("WORK"));
}
if (addressLabel.isPostal) {
labelElement->addNode(std::make_shared<XMLElement>("POSTAL"));
}
if (addressLabel.isParcel) {
labelElement->addNode(std::make_shared<XMLElement>("PARCEL"));
}
if (addressLabel.deliveryType == VCard::DomesticDelivery) {
labelElement->addNode(std::make_shared<XMLElement>("DOM"));
}
if (addressLabel.deliveryType == VCard::InternationalDelivery) {
labelElement->addNode(std::make_shared<XMLElement>("INTL"));
}
if (addressLabel.isPreferred) {
labelElement->addNode(std::make_shared<XMLElement>("PREF"));
}
queryElement.addNode(labelElement);
}
- foreach(const JID& jid, vcard->getJIDs()) {
+ for (const auto& jid : vcard->getJIDs()) {
queryElement.addNode(std::make_shared<XMLElement>("JID", "", jid.toString()));
}
if (!vcard->getDescription().empty()) {
queryElement.addNode(std::make_shared<XMLElement>("DESC", "", vcard->getDescription()));
}
- foreach(const VCard::Organization& org, vcard->getOrganizations()) {
+ for (const auto& org : vcard->getOrganizations()) {
std::shared_ptr<XMLElement> orgElement = std::make_shared<XMLElement>("ORG");
if (!org.name.empty()) {
orgElement->addNode(std::make_shared<XMLElement>("ORGNAME", "", org.name));
}
if (!org.units.empty()) {
- foreach(const std::string& unit, org.units) {
+ for (const auto& unit : org.units) {
orgElement->addNode(std::make_shared<XMLElement>("ORGUNIT", "", unit));
}
}
queryElement.addNode(orgElement);
}
- foreach(const std::string& title, vcard->getTitles()) {
+ for (const auto& title : vcard->getTitles()) {
queryElement.addNode(std::make_shared<XMLElement>("TITLE", "", title));
}
- foreach(const std::string& role, vcard->getRoles()) {
+ for (const auto& role : vcard->getRoles()) {
queryElement.addNode(std::make_shared<XMLElement>("ROLE", "", role));
}
- foreach(const std::string& url, vcard->getURLs()) {
+ for (const auto& url : vcard->getURLs()) {
queryElement.addNode(std::make_shared<XMLElement>("URL", "", url));
}
if (!vcard->getUnknownContent().empty()) {
queryElement.addNode(std::make_shared<XMLRawTextNode>(vcard->getUnknownContent()));
}
return queryElement.serialize();
}
}
diff --git a/Swiften/Serializer/StanzaSerializer.cpp b/Swiften/Serializer/StanzaSerializer.cpp
index 6440fbb..f2f5529 100644
--- a/Swiften/Serializer/StanzaSerializer.cpp
+++ b/Swiften/Serializer/StanzaSerializer.cpp
@@ -1,66 +1,65 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/StanzaSerializer.h>
#include <sstream>
#include <typeinfo>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Elements/Stanza.h>
#include <Swiften/Serializer/PayloadSerializer.h>
#include <Swiften/Serializer/PayloadSerializerCollection.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
namespace Swift {
StanzaSerializer::StanzaSerializer(const std::string& tag, PayloadSerializerCollection* payloadSerializers, const boost::optional<std::string>& explicitNS) : tag_(tag), payloadSerializers_(payloadSerializers), explicitDefaultNS_(explicitNS) {
}
SafeByteArray StanzaSerializer::serialize(std::shared_ptr<ToplevelElement> element) const {
if (explicitDefaultNS_) {
return serialize(element, explicitDefaultNS_.get());
}
else {
return serialize(element, "");
}
}
SafeByteArray StanzaSerializer::serialize(std::shared_ptr<ToplevelElement> element, const std::string& xmlns) const {
std::shared_ptr<Stanza> stanza(std::dynamic_pointer_cast<Stanza>(element));
XMLElement stanzaElement(tag_, explicitDefaultNS_ ? explicitDefaultNS_.get() : xmlns);
if (stanza->getFrom().isValid()) {
stanzaElement.setAttribute("from", stanza->getFrom());
}
if (stanza->getTo().isValid()) {
stanzaElement.setAttribute("to", stanza->getTo());
}
if (!stanza->getID().empty()) {
stanzaElement.setAttribute("id", stanza->getID());
}
setStanzaSpecificAttributes(stanza, stanzaElement);
std::string serializedPayloads;
- foreach (const std::shared_ptr<Payload>& payload, stanza->getPayloads()) {
+ for (const auto& payload : stanza->getPayloads()) {
PayloadSerializer* serializer = payloadSerializers_->getPayloadSerializer(payload);
if (serializer) {
serializedPayloads += serializer->serialize(payload);
}
else {
SWIFT_LOG(warning) << "Could not find serializer for " << typeid(*(payload.get())).name() << std::endl;
}
}
if (!serializedPayloads.empty()) {
stanzaElement.addNode(std::make_shared<XMLRawTextNode>(serializedPayloads));
}
return createSafeByteArray(stanzaElement.serialize());
}
}
diff --git a/Swiften/Serializer/StreamFeaturesSerializer.cpp b/Swiften/Serializer/StreamFeaturesSerializer.cpp
index 820b96c..2534db0 100644
--- a/Swiften/Serializer/StreamFeaturesSerializer.cpp
+++ b/Swiften/Serializer/StreamFeaturesSerializer.cpp
@@ -1,60 +1,59 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/StreamFeaturesSerializer.h>
#include <memory>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
namespace Swift {
StreamFeaturesSerializer::StreamFeaturesSerializer() {
}
SafeByteArray StreamFeaturesSerializer::serialize(std::shared_ptr<ToplevelElement> element) const {
std::shared_ptr<StreamFeatures> streamFeatures(std::dynamic_pointer_cast<StreamFeatures>(element));
XMLElement streamFeaturesElement("stream:features");
if (streamFeatures->hasStartTLS()) {
streamFeaturesElement.addNode(std::make_shared<XMLElement>("starttls", "urn:ietf:params:xml:ns:xmpp-tls"));
}
if (!streamFeatures->getCompressionMethods().empty()) {
std::shared_ptr<XMLElement> compressionElement(new XMLElement("compression", "http://jabber.org/features/compress"));
- foreach(const std::string& method, streamFeatures->getCompressionMethods()) {
+ for (const auto& method : streamFeatures->getCompressionMethods()) {
std::shared_ptr<XMLElement> methodElement(new XMLElement("method"));
methodElement->addNode(std::make_shared<XMLTextNode>(method));
compressionElement->addNode(methodElement);
}
streamFeaturesElement.addNode(compressionElement);
}
if (!streamFeatures->getAuthenticationMechanisms().empty()) {
std::shared_ptr<XMLElement> mechanismsElement(new XMLElement("mechanisms", "urn:ietf:params:xml:ns:xmpp-sasl"));
- foreach(const std::string& mechanism, streamFeatures->getAuthenticationMechanisms()) {
+ for (const auto& mechanism : streamFeatures->getAuthenticationMechanisms()) {
std::shared_ptr<XMLElement> mechanismElement(new XMLElement("mechanism"));
mechanismElement->addNode(std::make_shared<XMLTextNode>(mechanism));
mechanismsElement->addNode(mechanismElement);
}
streamFeaturesElement.addNode(mechanismsElement);
}
if (streamFeatures->hasResourceBind()) {
streamFeaturesElement.addNode(std::make_shared<XMLElement>("bind", "urn:ietf:params:xml:ns:xmpp-bind"));
}
if (streamFeatures->hasSession()) {
streamFeaturesElement.addNode(std::make_shared<XMLElement>("session", "urn:ietf:params:xml:ns:xmpp-session"));
}
if (streamFeatures->hasStreamManagement()) {
streamFeaturesElement.addNode(std::make_shared<XMLElement>("sm", "urn:xmpp:sm:2"));
}
if (streamFeatures->hasRosterVersioning()) {
streamFeaturesElement.addNode(std::make_shared<XMLElement>("ver", "urn:xmpp:features:rosterver"));
}
return createSafeByteArray(streamFeaturesElement.serialize());
}
}
diff --git a/Swiften/Serializer/XML/XMLElement.cpp b/Swiften/Serializer/XML/XMLElement.cpp
index 4a874ab..f2397ca 100644
--- a/Swiften/Serializer/XML/XMLElement.cpp
+++ b/Swiften/Serializer/XML/XMLElement.cpp
@@ -1,60 +1,58 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/XML/XMLElement.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
namespace Swift {
XMLElement::XMLElement(const std::string& tag, const std::string& xmlns, const std::string& text) : tag_(tag) {
if (!xmlns.empty()) {
setAttribute("xmlns", xmlns);
}
if (!text.empty()) {
addNode(XMLTextNode::ref(new XMLTextNode(text)));
}
}
std::string XMLElement::serialize() {
std::string result;
result += "<" + tag_;
- typedef std::pair<std::string,std::string> Pair;
- foreach(const Pair& p, attributes_) {
+ for (const auto& p : attributes_) {
result += " " + p.first + "=\"" + p.second + "\"";
}
if (!childNodes_.empty()) {
result += ">";
- foreach (std::shared_ptr<XMLNode> node, childNodes_) {
+ for (auto& node : childNodes_) {
result += node->serialize();
}
result += "</" + tag_ + ">";
}
else {
result += "/>";
}
return result;
}
void XMLElement::setAttribute(const std::string& attribute, const std::string& value) {
std::string escapedValue(value);
String::replaceAll(escapedValue, '&', "&amp;");
String::replaceAll(escapedValue, '<', "&lt;");
String::replaceAll(escapedValue, '>', "&gt;");
String::replaceAll(escapedValue, '\'', "&apos;");
String::replaceAll(escapedValue, '"', "&quot;");
attributes_[attribute] = escapedValue;
}
void XMLElement::addNode(std::shared_ptr<XMLNode> node) {
if (node) {
childNodes_.push_back(node);
}
}
}
diff --git a/Swiften/Serializer/XMPPSerializer.cpp b/Swiften/Serializer/XMPPSerializer.cpp
index 08b5485..9cde777 100644
--- a/Swiften/Serializer/XMPPSerializer.cpp
+++ b/Swiften/Serializer/XMPPSerializer.cpp
@@ -1,45 +1,44 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/XMPPSerializer.h>
#include <cassert>
#include <memory>
#include <boost/bind.hpp>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Elements/ProtocolHeader.h>
#include <Swiften/Serializer/AuthChallengeSerializer.h>
#include <Swiften/Serializer/AuthFailureSerializer.h>
#include <Swiften/Serializer/AuthRequestSerializer.h>
#include <Swiften/Serializer/AuthResponseSerializer.h>
#include <Swiften/Serializer/AuthSuccessSerializer.h>
#include <Swiften/Serializer/ComponentHandshakeSerializer.h>
#include <Swiften/Serializer/CompressFailureSerializer.h>
#include <Swiften/Serializer/CompressRequestSerializer.h>
#include <Swiften/Serializer/EnableStreamManagementSerializer.h>
#include <Swiften/Serializer/IQSerializer.h>
#include <Swiften/Serializer/MessageSerializer.h>
#include <Swiften/Serializer/PresenceSerializer.h>
#include <Swiften/Serializer/StanzaAckRequestSerializer.h>
#include <Swiften/Serializer/StanzaAckSerializer.h>
#include <Swiften/Serializer/StartTLSFailureSerializer.h>
#include <Swiften/Serializer/StartTLSRequestSerializer.h>
#include <Swiften/Serializer/StreamErrorSerializer.h>
#include <Swiften/Serializer/StreamFeaturesSerializer.h>
#include <Swiften/Serializer/StreamManagementEnabledSerializer.h>
#include <Swiften/Serializer/StreamManagementFailedSerializer.h>
#include <Swiften/Serializer/StreamResumeSerializer.h>
#include <Swiften/Serializer/StreamResumedSerializer.h>
#include <Swiften/Serializer/TLSProceedSerializer.h>
namespace Swift {
XMPPSerializer::XMPPSerializer(PayloadSerializerCollection* payloadSerializers, StreamType type, bool setExplictNSonTopLevelElements) : type_(type) {
serializers_.push_back(std::make_shared<PresenceSerializer>(payloadSerializers, setExplictNSonTopLevelElements ? getDefaultNamespace() : boost::optional<std::string>()));
serializers_.push_back(std::make_shared<IQSerializer>(payloadSerializers, setExplictNSonTopLevelElements ? getDefaultNamespace() : boost::optional<std::string>()));
diff --git a/Swiften/Session/BOSHSessionStream.cpp b/Swiften/Session/BOSHSessionStream.cpp
index 635fd69..4c7bdee 100644
--- a/Swiften/Session/BOSHSessionStream.cpp
+++ b/Swiften/Session/BOSHSessionStream.cpp
@@ -1,45 +1,44 @@
/*
* Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Session/BOSHSessionStream.h>
#include <boost/bind.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int.hpp>
#include <boost/random/variate_generator.hpp>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Elements/StreamType.h>
#include <Swiften/EventLoop/EventLoop.h>
#include <Swiften/StreamStack/CompressionLayer.h>
#include <Swiften/StreamStack/ConnectionLayer.h>
#include <Swiften/StreamStack/StreamStack.h>
#include <Swiften/StreamStack/TLSLayer.h>
#include <Swiften/StreamStack/WhitespacePingLayer.h>
#include <Swiften/StreamStack/XMPPLayer.h>
#include <Swiften/TLS/TLSContext.h>
#include <Swiften/TLS/TLSContextFactory.h>
namespace Swift {
BOSHSessionStream::BOSHSessionStream(const URL& boshURL,
PayloadParserFactoryCollection* payloadParserFactories,
PayloadSerializerCollection* payloadSerializers,
ConnectionFactory* connectionFactory,
TLSContextFactory* tlsContextFactory,
TimerFactory* timerFactory,
XMLParserFactory* xmlParserFactory,
EventLoop* eventLoop,
DomainNameResolver* resolver,
const std::string& to,
const URL& boshHTTPConnectProxyURL,
const SafeString& boshHTTPConnectProxyAuthID,
const SafeString& boshHTTPConnectProxyAuthPassword,
const TLSOptions& tlsOptions,
std::shared_ptr<HTTPTrafficFilter> trafficFilter) :
available(false),
eventLoop(eventLoop),
diff --git a/Swiften/StreamStack/StreamStack.cpp b/Swiften/StreamStack/StreamStack.cpp
index 0bcd1b3..44a018d 100644
--- a/Swiften/StreamStack/StreamStack.cpp
+++ b/Swiften/StreamStack/StreamStack.cpp
@@ -1,38 +1,37 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/StreamStack/StreamStack.h>
#include <boost/bind.hpp>
-#include <Swiften/Base/foreach.h>
#include <Swiften/StreamStack/LowLayer.h>
#include <Swiften/StreamStack/StreamLayer.h>
#include <Swiften/StreamStack/XMPPLayer.h>
namespace Swift {
StreamStack::StreamStack(XMPPLayer* xmppLayer, LowLayer* physicalLayer) : xmppLayer_(xmppLayer), physicalLayer_(physicalLayer) {
physicalLayer_->setParentLayer(xmppLayer_);
xmppLayer_->setChildLayer(physicalLayer_);
}
StreamStack::~StreamStack() {
}
void StreamStack::addLayer(StreamLayer* newLayer) {
LowLayer* lowLayer = layers_.empty() ? physicalLayer_ : *layers_.rbegin();
xmppLayer_->setChildLayer(newLayer);
newLayer->setParentLayer(xmppLayer_);
lowLayer->setParentLayer(newLayer);
newLayer->setChildLayer(lowLayer);
layers_.push_back(newLayer);
}
}
diff --git a/Swiften/TLS/ServerIdentityVerifier.cpp b/Swiften/TLS/ServerIdentityVerifier.cpp
index 872717b..226e94b 100644
--- a/Swiften/TLS/ServerIdentityVerifier.cpp
+++ b/Swiften/TLS/ServerIdentityVerifier.cpp
@@ -1,93 +1,92 @@
/*
* Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/TLS/ServerIdentityVerifier.h>
#include <boost/algorithm/string.hpp>
-#include <Swiften/Base/foreach.h>
#include <Swiften/IDN/IDNConverter.h>
namespace Swift {
ServerIdentityVerifier::ServerIdentityVerifier(const JID& jid, IDNConverter* idnConverter) : domainValid(false) {
domain = jid.getDomain();
boost::optional<std::string> domainResult = idnConverter->getIDNAEncoded(domain);
if (!!domainResult) {
encodedDomain = *domainResult;
domainValid = true;
}
}
bool ServerIdentityVerifier::certificateVerifies(Certificate::ref certificate) {
bool hasSAN = false;
if (certificate == nullptr) {
return false;
}
// DNS names
std::vector<std::string> dnsNames = certificate->getDNSNames();
- foreach (const std::string& dnsName, dnsNames) {
+ for (const auto& dnsName : dnsNames) {
if (matchesDomain(dnsName)) {
return true;
}
}
hasSAN |= !dnsNames.empty();
// SRV names
std::vector<std::string> srvNames = certificate->getSRVNames();
- foreach (const std::string& srvName, srvNames) {
+ for (const auto& srvName : srvNames) {
// Only match SRV names that begin with the service; this isn't required per
// spec, but we're being purist about this.
if (boost::starts_with(srvName, "_xmpp-client.") && matchesDomain(srvName.substr(std::string("_xmpp-client.").size(), srvName.npos))) {
return true;
}
}
hasSAN |= !srvNames.empty();
// XmppAddr
std::vector<std::string> xmppAddresses = certificate->getXMPPAddresses();
- foreach (const std::string& xmppAddress, xmppAddresses) {
+ for (const auto& xmppAddress : xmppAddresses) {
if (matchesAddress(xmppAddress)) {
return true;
}
}
hasSAN |= !xmppAddresses.empty();
// CommonNames. Only check this if there was no SAN (according to spec).
if (!hasSAN) {
std::vector<std::string> commonNames = certificate->getCommonNames();
- foreach (const std::string& commonName, commonNames) {
+ for (const auto& commonName : commonNames) {
if (matchesDomain(commonName)) {
return true;
}
}
}
return false;
}
bool ServerIdentityVerifier::matchesDomain(const std::string& s) const {
if (!domainValid) {
return false;
}
if (boost::starts_with(s, "*.")) {
std::string matchString(s.substr(2, s.npos));
std::string matchDomain = encodedDomain;
size_t dotIndex = matchDomain.find('.');
if (dotIndex != matchDomain.npos) {
matchDomain = matchDomain.substr(dotIndex + 1, matchDomain.npos);
}
return matchString == matchDomain;
}
else {
return s == encodedDomain;
}
}
bool ServerIdentityVerifier::matchesAddress(const std::string& s) const {
return s == domain;
}
diff --git a/Swiften/Whiteboard/WhiteboardSessionManager.cpp b/Swiften/Whiteboard/WhiteboardSessionManager.cpp
index 66b5ef8..59f6c47 100644
--- a/Swiften/Whiteboard/WhiteboardSessionManager.cpp
+++ b/Swiften/Whiteboard/WhiteboardSessionManager.cpp
@@ -1,50 +1,49 @@
/*
* 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 <Swiften/Whiteboard/WhiteboardSessionManager.h>
#include <memory>
#include <boost/bind.hpp>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Disco/EntityCapsProvider.h>
#include <Swiften/Presence/PresenceOracle.h>
#include <Swiften/Queries/IQRouter.h>
#include <Swiften/Whiteboard/WhiteboardResponder.h>
namespace Swift {
WhiteboardSessionManager::WhiteboardSessionManager(IQRouter* router, StanzaChannel* stanzaChannel, PresenceOracle* presenceOracle, EntityCapsProvider* capsProvider) : router_(router), stanzaChannel_(stanzaChannel), presenceOracle_(presenceOracle), capsProvider_(capsProvider) {
responder = new WhiteboardResponder(this, router);
responder->start();
stanzaChannel_->onPresenceReceived.connect(boost::bind(&WhiteboardSessionManager::handlePresenceReceived, this, _1));
stanzaChannel_->onAvailableChanged.connect(boost::bind(&WhiteboardSessionManager::handleAvailableChanged, this, _1));
}
WhiteboardSessionManager::~WhiteboardSessionManager() {
responder->stop();
delete responder;
}
WhiteboardSession::ref WhiteboardSessionManager::getSession(const JID& to) {
if (sessions_.find(to) == sessions_.end()) {
return std::shared_ptr<WhiteboardSession>();
}
return sessions_[to];
}
OutgoingWhiteboardSession::ref WhiteboardSessionManager::createOutgoingSession(const JID& to) {
JID fullJID = to;
if (fullJID.isBare()) {
fullJID = getFullJID(fullJID);
}
@@ -53,61 +52,61 @@ namespace Swift {
session->onSessionTerminated.connect(boost::bind(&WhiteboardSessionManager::deleteSessionEntry, this, _1));
session->onRequestRejected.connect(boost::bind(&WhiteboardSessionManager::deleteSessionEntry, this, _1));
return session;
}
WhiteboardSession::ref WhiteboardSessionManager::requestSession(const JID& to) {
WhiteboardSession::ref session = getSession(to);
if (!session) {
OutgoingWhiteboardSession::ref outgoingSession = createOutgoingSession(to);
outgoingSession->startSession();
return outgoingSession;
} else {
return session;
}
}
void WhiteboardSessionManager::handleIncomingSession(IncomingWhiteboardSession::ref session) {
sessions_[session->getTo()] = session;
session->onSessionTerminated.connect(boost::bind(&WhiteboardSessionManager::deleteSessionEntry, this, _1));
onSessionRequest(session);
}
JID WhiteboardSessionManager::getFullJID(const JID& bareJID) {
JID fullReceipientJID;
int priority = INT_MIN;
//getAllPresence(bareJID) gives you all presences for the bare JID (i.e. all resources) Remko Tronçon @ 11:11
std::vector<Presence::ref> presences = presenceOracle_->getAllPresence(bareJID);
//iterate over them
- foreach(Presence::ref pres, presences) {
+ for (const auto& pres : presences) {
if (pres->getPriority() > priority) {
// look up caps from the jid
DiscoInfo::ref info = capsProvider_->getCaps(pres->getFrom());
if (info && info->hasFeature(DiscoInfo::WhiteboardFeature)) {
priority = pres->getPriority();
fullReceipientJID = pres->getFrom();
}
}
}
return fullReceipientJID;
}
void WhiteboardSessionManager::deleteSessionEntry(const JID& contact) {
sessions_.erase(contact);
}
void WhiteboardSessionManager::handlePresenceReceived(Presence::ref presence) {
if (!presence->isAvailable()) {
WhiteboardSession::ref session = getSession(presence->getFrom());
if (session) {
session->cancel();
}
}
}
void WhiteboardSessionManager::handleAvailableChanged(bool available) {
if (!available) {
std::map<JID, WhiteboardSession::ref> sessionsCopy = sessions_;
std::map<JID, WhiteboardSession::ref>::iterator it;